PackageManagerService.java revision e17ac1569793c333bb4dce86607a342e7c982ae7
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.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
87
88import android.Manifest;
89import android.app.ActivityManager;
90import android.app.ActivityManagerNative;
91import android.app.AppGlobals;
92import android.app.IActivityManager;
93import android.app.admin.IDevicePolicyManager;
94import android.app.backup.IBackupManager;
95import android.app.usage.UsageStats;
96import android.app.usage.UsageStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.FeatureInfo;
109import android.content.pm.IOnPermissionsChangeListener;
110import android.content.pm.IPackageDataObserver;
111import android.content.pm.IPackageDeleteObserver;
112import android.content.pm.IPackageDeleteObserver2;
113import android.content.pm.IPackageInstallObserver2;
114import android.content.pm.IPackageInstaller;
115import android.content.pm.IPackageManager;
116import android.content.pm.IPackageMoveObserver;
117import android.content.pm.IPackageStatsObserver;
118import android.content.pm.InstrumentationInfo;
119import android.content.pm.IntentFilterVerificationInfo;
120import android.content.pm.KeySet;
121import android.content.pm.ManifestDigest;
122import android.content.pm.PackageCleanItem;
123import android.content.pm.PackageInfo;
124import android.content.pm.PackageInfoLite;
125import android.content.pm.PackageInstaller;
126import android.content.pm.PackageManager;
127import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
128import android.content.pm.PackageManagerInternal;
129import android.content.pm.PackageParser;
130import android.content.pm.PackageParser.ActivityIntentInfo;
131import android.content.pm.PackageParser.PackageLite;
132import android.content.pm.PackageParser.PackageParserException;
133import android.content.pm.PackageStats;
134import android.content.pm.PackageUserState;
135import android.content.pm.ParceledListSlice;
136import android.content.pm.PermissionGroupInfo;
137import android.content.pm.PermissionInfo;
138import android.content.pm.ProviderInfo;
139import android.content.pm.ResolveInfo;
140import android.content.pm.ServiceInfo;
141import android.content.pm.Signature;
142import android.content.pm.UserInfo;
143import android.content.pm.VerificationParams;
144import android.content.pm.VerifierDeviceIdentity;
145import android.content.pm.VerifierInfo;
146import android.content.res.Resources;
147import android.hardware.display.DisplayManager;
148import android.net.Uri;
149import android.os.Debug;
150import android.os.Binder;
151import android.os.Build;
152import android.os.Bundle;
153import android.os.Environment;
154import android.os.Environment.UserEnvironment;
155import android.os.FileUtils;
156import android.os.Handler;
157import android.os.IBinder;
158import android.os.Looper;
159import android.os.Message;
160import android.os.Parcel;
161import android.os.ParcelFileDescriptor;
162import android.os.Process;
163import android.os.RemoteCallbackList;
164import android.os.RemoteException;
165import android.os.ResultReceiver;
166import android.os.SELinux;
167import android.os.ServiceManager;
168import android.os.SystemClock;
169import android.os.SystemProperties;
170import android.os.Trace;
171import android.os.UserHandle;
172import android.os.UserManager;
173import android.os.storage.IMountService;
174import android.os.storage.MountServiceInternal;
175import android.os.storage.StorageEventListener;
176import android.os.storage.StorageManager;
177import android.os.storage.VolumeInfo;
178import android.os.storage.VolumeRecord;
179import android.security.KeyStore;
180import android.security.SystemKeyStore;
181import android.system.ErrnoException;
182import android.system.Os;
183import android.system.StructStat;
184import android.text.TextUtils;
185import android.text.format.DateUtils;
186import android.util.ArrayMap;
187import android.util.ArraySet;
188import android.util.AtomicFile;
189import android.util.DisplayMetrics;
190import android.util.EventLog;
191import android.util.ExceptionUtils;
192import android.util.Log;
193import android.util.LogPrinter;
194import android.util.MathUtils;
195import android.util.PrintStreamPrinter;
196import android.util.Slog;
197import android.util.SparseArray;
198import android.util.SparseBooleanArray;
199import android.util.SparseIntArray;
200import android.util.Xml;
201import android.view.Display;
202
203import dalvik.system.DexFile;
204import dalvik.system.VMRuntime;
205
206import libcore.io.IoUtils;
207import libcore.util.EmptyArray;
208
209import com.android.internal.R;
210import com.android.internal.annotations.GuardedBy;
211import com.android.internal.app.IMediaContainerService;
212import com.android.internal.app.ResolverActivity;
213import com.android.internal.content.NativeLibraryHelper;
214import com.android.internal.content.PackageHelper;
215import com.android.internal.os.IParcelFileDescriptorFactory;
216import com.android.internal.os.SomeArgs;
217import com.android.internal.os.Zygote;
218import com.android.internal.util.ArrayUtils;
219import com.android.internal.util.FastPrintWriter;
220import com.android.internal.util.FastXmlSerializer;
221import com.android.internal.util.IndentingPrintWriter;
222import com.android.internal.util.Preconditions;
223import com.android.server.EventLogTags;
224import com.android.server.FgThread;
225import com.android.server.IntentResolver;
226import com.android.server.LocalServices;
227import com.android.server.ServiceThread;
228import com.android.server.SystemConfig;
229import com.android.server.Watchdog;
230import com.android.server.pm.PermissionsState.PermissionState;
231import com.android.server.pm.Settings.DatabaseVersion;
232import com.android.server.pm.Settings.VersionInfo;
233import com.android.server.storage.DeviceStorageMonitorInternal;
234
235import org.xmlpull.v1.XmlPullParser;
236import org.xmlpull.v1.XmlPullParserException;
237import org.xmlpull.v1.XmlSerializer;
238
239import java.io.BufferedInputStream;
240import java.io.BufferedOutputStream;
241import java.io.BufferedReader;
242import java.io.ByteArrayInputStream;
243import java.io.ByteArrayOutputStream;
244import java.io.File;
245import java.io.FileDescriptor;
246import java.io.FileNotFoundException;
247import java.io.FileOutputStream;
248import java.io.FileReader;
249import java.io.FilenameFilter;
250import java.io.IOException;
251import java.io.InputStream;
252import java.io.PrintWriter;
253import java.nio.charset.StandardCharsets;
254import java.security.NoSuchAlgorithmException;
255import java.security.PublicKey;
256import java.security.cert.CertificateEncodingException;
257import java.security.cert.CertificateException;
258import java.text.SimpleDateFormat;
259import java.util.ArrayList;
260import java.util.Arrays;
261import java.util.Collection;
262import java.util.Collections;
263import java.util.Comparator;
264import java.util.Date;
265import java.util.Iterator;
266import java.util.List;
267import java.util.Map;
268import java.util.Objects;
269import java.util.Set;
270import java.util.concurrent.CountDownLatch;
271import java.util.concurrent.TimeUnit;
272import java.util.concurrent.atomic.AtomicBoolean;
273import java.util.concurrent.atomic.AtomicInteger;
274import java.util.concurrent.atomic.AtomicLong;
275
276/**
277 * Keep track of all those .apks everywhere.
278 *
279 * This is very central to the platform's security; please run the unit
280 * tests whenever making modifications here:
281 *
282runtest -c android.content.pm.PackageManagerTests frameworks-core
283 *
284 * {@hide}
285 */
286public class PackageManagerService extends IPackageManager.Stub {
287    static final String TAG = "PackageManager";
288    static final boolean DEBUG_SETTINGS = false;
289    static final boolean DEBUG_PREFERRED = false;
290    static final boolean DEBUG_UPGRADE = false;
291    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
292    private static final boolean DEBUG_BACKUP = false;
293    private static final boolean DEBUG_INSTALL = false;
294    private static final boolean DEBUG_REMOVE = false;
295    private static final boolean DEBUG_BROADCASTS = false;
296    private static final boolean DEBUG_SHOW_INFO = false;
297    private static final boolean DEBUG_PACKAGE_INFO = false;
298    private static final boolean DEBUG_INTENT_MATCHING = false;
299    private static final boolean DEBUG_PACKAGE_SCANNING = false;
300    private static final boolean DEBUG_VERIFY = false;
301    private static final boolean DEBUG_DEXOPT = false;
302    private static final boolean DEBUG_ABI_SELECTION = false;
303
304    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
305
306    private static final int RADIO_UID = Process.PHONE_UID;
307    private static final int LOG_UID = Process.LOG_UID;
308    private static final int NFC_UID = Process.NFC_UID;
309    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
310    private static final int SHELL_UID = Process.SHELL_UID;
311
312    // Cap the size of permission trees that 3rd party apps can define
313    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
314
315    // Suffix used during package installation when copying/moving
316    // package apks to install directory.
317    private static final String INSTALL_PACKAGE_SUFFIX = "-";
318
319    static final int SCAN_NO_DEX = 1<<1;
320    static final int SCAN_FORCE_DEX = 1<<2;
321    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
322    static final int SCAN_NEW_INSTALL = 1<<4;
323    static final int SCAN_NO_PATHS = 1<<5;
324    static final int SCAN_UPDATE_TIME = 1<<6;
325    static final int SCAN_DEFER_DEX = 1<<7;
326    static final int SCAN_BOOTING = 1<<8;
327    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
328    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
329    static final int SCAN_REPLACING = 1<<11;
330    static final int SCAN_REQUIRE_KNOWN = 1<<12;
331    static final int SCAN_MOVE = 1<<13;
332    static final int SCAN_INITIAL = 1<<14;
333
334    static final int REMOVE_CHATTY = 1<<16;
335
336    private static final int[] EMPTY_INT_ARRAY = new int[0];
337
338    /**
339     * Timeout (in milliseconds) after which the watchdog should declare that
340     * our handler thread is wedged.  The usual default for such things is one
341     * minute but we sometimes do very lengthy I/O operations on this thread,
342     * such as installing multi-gigabyte applications, so ours needs to be longer.
343     */
344    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
345
346    /**
347     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
348     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
349     * settings entry if available, otherwise we use the hardcoded default.  If it's been
350     * more than this long since the last fstrim, we force one during the boot sequence.
351     *
352     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
353     * one gets run at the next available charging+idle time.  This final mandatory
354     * no-fstrim check kicks in only of the other scheduling criteria is never met.
355     */
356    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
357
358    /**
359     * Whether verification is enabled by default.
360     */
361    private static final boolean DEFAULT_VERIFY_ENABLE = true;
362
363    /**
364     * The default maximum time to wait for the verification agent to return in
365     * milliseconds.
366     */
367    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
368
369    /**
370     * The default response for package verification timeout.
371     *
372     * This can be either PackageManager.VERIFICATION_ALLOW or
373     * PackageManager.VERIFICATION_REJECT.
374     */
375    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
376
377    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
378
379    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
380            DEFAULT_CONTAINER_PACKAGE,
381            "com.android.defcontainer.DefaultContainerService");
382
383    private static final String KILL_APP_REASON_GIDS_CHANGED =
384            "permission grant or revoke changed gids";
385
386    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
387            "permissions revoked";
388
389    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
390
391    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
392
393    /** Permission grant: not grant the permission. */
394    private static final int GRANT_DENIED = 1;
395
396    /** Permission grant: grant the permission as an install permission. */
397    private static final int GRANT_INSTALL = 2;
398
399    /** Permission grant: grant the permission as an install permission for a legacy app. */
400    private static final int GRANT_INSTALL_LEGACY = 3;
401
402    /** Permission grant: grant the permission as a runtime one. */
403    private static final int GRANT_RUNTIME = 4;
404
405    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
406    private static final int GRANT_UPGRADE = 5;
407
408    /** Canonical intent used to identify what counts as a "web browser" app */
409    private static final Intent sBrowserIntent;
410    static {
411        sBrowserIntent = new Intent();
412        sBrowserIntent.setAction(Intent.ACTION_VIEW);
413        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
414        sBrowserIntent.setData(Uri.parse("http:"));
415    }
416
417    final ServiceThread mHandlerThread;
418
419    final PackageHandler mHandler;
420
421    /**
422     * Messages for {@link #mHandler} that need to wait for system ready before
423     * being dispatched.
424     */
425    private ArrayList<Message> mPostSystemReadyMessages;
426
427    final int mSdkVersion = Build.VERSION.SDK_INT;
428
429    final Context mContext;
430    final boolean mFactoryTest;
431    final boolean mOnlyCore;
432    final boolean mLazyDexOpt;
433    final long mDexOptLRUThresholdInMills;
434    final DisplayMetrics mMetrics;
435    final int mDefParseFlags;
436    final String[] mSeparateProcesses;
437    final boolean mIsUpgrade;
438
439    // This is where all application persistent data goes.
440    final File mAppDataDir;
441
442    // This is where all application persistent data goes for secondary users.
443    final File mUserAppDataDir;
444
445    /** The location for ASEC container files on internal storage. */
446    final String mAsecInternalPath;
447
448    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
449    // LOCK HELD.  Can be called with mInstallLock held.
450    @GuardedBy("mInstallLock")
451    final Installer mInstaller;
452
453    /** Directory where installed third-party apps stored */
454    final File mAppInstallDir;
455
456    /**
457     * Directory to which applications installed internally have their
458     * 32 bit native libraries copied.
459     */
460    private File mAppLib32InstallDir;
461
462    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
463    // apps.
464    final File mDrmAppPrivateInstallDir;
465
466    // ----------------------------------------------------------------
467
468    // Lock for state used when installing and doing other long running
469    // operations.  Methods that must be called with this lock held have
470    // the suffix "LI".
471    final Object mInstallLock = new Object();
472
473    // ----------------------------------------------------------------
474
475    // Keys are String (package name), values are Package.  This also serves
476    // as the lock for the global state.  Methods that must be called with
477    // this lock held have the prefix "LP".
478    @GuardedBy("mPackages")
479    final ArrayMap<String, PackageParser.Package> mPackages =
480            new ArrayMap<String, PackageParser.Package>();
481
482    // Tracks available target package names -> overlay package paths.
483    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
484        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
485
486    /**
487     * Tracks new system packages [received in an OTA] that we expect to
488     * find updated user-installed versions. Keys are package name, values
489     * are package location.
490     */
491    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
492
493    /**
494     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
495     */
496    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
497    /**
498     * Whether or not system app permissions should be promoted from install to runtime.
499     */
500    boolean mPromoteSystemApps;
501
502    final Settings mSettings;
503    boolean mRestoredSettings;
504
505    // System configuration read by SystemConfig.
506    final int[] mGlobalGids;
507    final SparseArray<ArraySet<String>> mSystemPermissions;
508    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
509
510    // If mac_permissions.xml was found for seinfo labeling.
511    boolean mFoundPolicyFile;
512
513    // If a recursive restorecon of /data/data/<pkg> is needed.
514    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
515
516    public static final class SharedLibraryEntry {
517        public final String path;
518        public final String apk;
519
520        SharedLibraryEntry(String _path, String _apk) {
521            path = _path;
522            apk = _apk;
523        }
524    }
525
526    // Currently known shared libraries.
527    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
528            new ArrayMap<String, SharedLibraryEntry>();
529
530    // All available activities, for your resolving pleasure.
531    final ActivityIntentResolver mActivities =
532            new ActivityIntentResolver();
533
534    // All available receivers, for your resolving pleasure.
535    final ActivityIntentResolver mReceivers =
536            new ActivityIntentResolver();
537
538    // All available services, for your resolving pleasure.
539    final ServiceIntentResolver mServices = new ServiceIntentResolver();
540
541    // All available providers, for your resolving pleasure.
542    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
543
544    // Mapping from provider base names (first directory in content URI codePath)
545    // to the provider information.
546    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
547            new ArrayMap<String, PackageParser.Provider>();
548
549    // Mapping from instrumentation class names to info about them.
550    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
551            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
552
553    // Mapping from permission names to info about them.
554    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
555            new ArrayMap<String, PackageParser.PermissionGroup>();
556
557    // Packages whose data we have transfered into another package, thus
558    // should no longer exist.
559    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
560
561    // Broadcast actions that are only available to the system.
562    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
563
564    /** List of packages waiting for verification. */
565    final SparseArray<PackageVerificationState> mPendingVerification
566            = new SparseArray<PackageVerificationState>();
567
568    /** Set of packages associated with each app op permission. */
569    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
570
571    final PackageInstallerService mInstallerService;
572
573    private final PackageDexOptimizer mPackageDexOptimizer;
574
575    private AtomicInteger mNextMoveId = new AtomicInteger();
576    private final MoveCallbacks mMoveCallbacks;
577
578    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
579
580    // Cache of users who need badging.
581    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
582
583    /** Token for keys in mPendingVerification. */
584    private int mPendingVerificationToken = 0;
585
586    volatile boolean mSystemReady;
587    volatile boolean mSafeMode;
588    volatile boolean mHasSystemUidErrors;
589
590    ApplicationInfo mAndroidApplication;
591    final ActivityInfo mResolveActivity = new ActivityInfo();
592    final ResolveInfo mResolveInfo = new ResolveInfo();
593    ComponentName mResolveComponentName;
594    PackageParser.Package mPlatformPackage;
595    ComponentName mCustomResolverComponentName;
596
597    boolean mResolverReplaced = false;
598
599    private final ComponentName mIntentFilterVerifierComponent;
600    private int mIntentFilterVerificationToken = 0;
601
602    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
603            = new SparseArray<IntentFilterVerificationState>();
604
605    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
606            new DefaultPermissionGrantPolicy(this);
607
608    private static class IFVerificationParams {
609        PackageParser.Package pkg;
610        boolean replacing;
611        int userId;
612        int verifierUid;
613
614        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
615                int _userId, int _verifierUid) {
616            pkg = _pkg;
617            replacing = _replacing;
618            userId = _userId;
619            replacing = _replacing;
620            verifierUid = _verifierUid;
621        }
622    }
623
624    private interface IntentFilterVerifier<T extends IntentFilter> {
625        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
626                                               T filter, String packageName);
627        void startVerifications(int userId);
628        void receiveVerificationResponse(int verificationId);
629    }
630
631    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
632        private Context mContext;
633        private ComponentName mIntentFilterVerifierComponent;
634        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
635
636        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
637            mContext = context;
638            mIntentFilterVerifierComponent = verifierComponent;
639        }
640
641        private String getDefaultScheme() {
642            return IntentFilter.SCHEME_HTTPS;
643        }
644
645        @Override
646        public void startVerifications(int userId) {
647            // Launch verifications requests
648            int count = mCurrentIntentFilterVerifications.size();
649            for (int n=0; n<count; n++) {
650                int verificationId = mCurrentIntentFilterVerifications.get(n);
651                final IntentFilterVerificationState ivs =
652                        mIntentFilterVerificationStates.get(verificationId);
653
654                String packageName = ivs.getPackageName();
655
656                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
657                final int filterCount = filters.size();
658                ArraySet<String> domainsSet = new ArraySet<>();
659                for (int m=0; m<filterCount; m++) {
660                    PackageParser.ActivityIntentInfo filter = filters.get(m);
661                    domainsSet.addAll(filter.getHostsList());
662                }
663                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
664                synchronized (mPackages) {
665                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
666                            packageName, domainsList) != null) {
667                        scheduleWriteSettingsLocked();
668                    }
669                }
670                sendVerificationRequest(userId, verificationId, ivs);
671            }
672            mCurrentIntentFilterVerifications.clear();
673        }
674
675        private void sendVerificationRequest(int userId, int verificationId,
676                IntentFilterVerificationState ivs) {
677
678            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
679            verificationIntent.putExtra(
680                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
681                    verificationId);
682            verificationIntent.putExtra(
683                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
684                    getDefaultScheme());
685            verificationIntent.putExtra(
686                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
687                    ivs.getHostsString());
688            verificationIntent.putExtra(
689                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
690                    ivs.getPackageName());
691            verificationIntent.setComponent(mIntentFilterVerifierComponent);
692            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
693
694            UserHandle user = new UserHandle(userId);
695            mContext.sendBroadcastAsUser(verificationIntent, user);
696            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
697                    "Sending IntentFilter verification broadcast");
698        }
699
700        public void receiveVerificationResponse(int verificationId) {
701            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
702
703            final boolean verified = ivs.isVerified();
704
705            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
706            final int count = filters.size();
707            if (DEBUG_DOMAIN_VERIFICATION) {
708                Slog.i(TAG, "Received verification response " + verificationId
709                        + " for " + count + " filters, verified=" + verified);
710            }
711            for (int n=0; n<count; n++) {
712                PackageParser.ActivityIntentInfo filter = filters.get(n);
713                filter.setVerified(verified);
714
715                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
716                        + " verified with result:" + verified + " and hosts:"
717                        + ivs.getHostsString());
718            }
719
720            mIntentFilterVerificationStates.remove(verificationId);
721
722            final String packageName = ivs.getPackageName();
723            IntentFilterVerificationInfo ivi = null;
724
725            synchronized (mPackages) {
726                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
727            }
728            if (ivi == null) {
729                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
730                        + verificationId + " packageName:" + packageName);
731                return;
732            }
733            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
734                    "Updating IntentFilterVerificationInfo for package " + packageName
735                            +" verificationId:" + verificationId);
736
737            synchronized (mPackages) {
738                if (verified) {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
740                } else {
741                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
742                }
743                scheduleWriteSettingsLocked();
744
745                final int userId = ivs.getUserId();
746                if (userId != UserHandle.USER_ALL) {
747                    final int userStatus =
748                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
749
750                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
751                    boolean needUpdate = false;
752
753                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
754                    // already been set by the User thru the Disambiguation dialog
755                    switch (userStatus) {
756                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
757                            if (verified) {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
759                            } else {
760                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
761                            }
762                            needUpdate = true;
763                            break;
764
765                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
766                            if (verified) {
767                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
768                                needUpdate = true;
769                            }
770                            break;
771
772                        default:
773                            // Nothing to do
774                    }
775
776                    if (needUpdate) {
777                        mSettings.updateIntentFilterVerificationStatusLPw(
778                                packageName, updatedStatus, userId);
779                        scheduleWritePackageRestrictionsLocked(userId);
780                    }
781                }
782            }
783        }
784
785        @Override
786        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
787                    ActivityIntentInfo filter, String packageName) {
788            if (!hasValidDomains(filter)) {
789                return false;
790            }
791            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
792            if (ivs == null) {
793                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
794                        packageName);
795            }
796            if (DEBUG_DOMAIN_VERIFICATION) {
797                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
798            }
799            ivs.addFilter(filter);
800            return true;
801        }
802
803        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
804                int userId, int verificationId, String packageName) {
805            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
806                    verifierUid, userId, packageName);
807            ivs.setPendingState();
808            synchronized (mPackages) {
809                mIntentFilterVerificationStates.append(verificationId, ivs);
810                mCurrentIntentFilterVerifications.add(verificationId);
811            }
812            return ivs;
813        }
814    }
815
816    private static boolean hasValidDomains(ActivityIntentInfo filter) {
817        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
818                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
819                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
820    }
821
822    private IntentFilterVerifier mIntentFilterVerifier;
823
824    // Set of pending broadcasts for aggregating enable/disable of components.
825    static class PendingPackageBroadcasts {
826        // for each user id, a map of <package name -> components within that package>
827        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
828
829        public PendingPackageBroadcasts() {
830            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
831        }
832
833        public ArrayList<String> get(int userId, String packageName) {
834            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
835            return packages.get(packageName);
836        }
837
838        public void put(int userId, String packageName, ArrayList<String> components) {
839            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
840            packages.put(packageName, components);
841        }
842
843        public void remove(int userId, String packageName) {
844            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
845            if (packages != null) {
846                packages.remove(packageName);
847            }
848        }
849
850        public void remove(int userId) {
851            mUidMap.remove(userId);
852        }
853
854        public int userIdCount() {
855            return mUidMap.size();
856        }
857
858        public int userIdAt(int n) {
859            return mUidMap.keyAt(n);
860        }
861
862        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
863            return mUidMap.get(userId);
864        }
865
866        public int size() {
867            // total number of pending broadcast entries across all userIds
868            int num = 0;
869            for (int i = 0; i< mUidMap.size(); i++) {
870                num += mUidMap.valueAt(i).size();
871            }
872            return num;
873        }
874
875        public void clear() {
876            mUidMap.clear();
877        }
878
879        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
880            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
881            if (map == null) {
882                map = new ArrayMap<String, ArrayList<String>>();
883                mUidMap.put(userId, map);
884            }
885            return map;
886        }
887    }
888    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
889
890    // Service Connection to remote media container service to copy
891    // package uri's from external media onto secure containers
892    // or internal storage.
893    private IMediaContainerService mContainerService = null;
894
895    static final int SEND_PENDING_BROADCAST = 1;
896    static final int MCS_BOUND = 3;
897    static final int END_COPY = 4;
898    static final int INIT_COPY = 5;
899    static final int MCS_UNBIND = 6;
900    static final int START_CLEANING_PACKAGE = 7;
901    static final int FIND_INSTALL_LOC = 8;
902    static final int POST_INSTALL = 9;
903    static final int MCS_RECONNECT = 10;
904    static final int MCS_GIVE_UP = 11;
905    static final int UPDATED_MEDIA_STATUS = 12;
906    static final int WRITE_SETTINGS = 13;
907    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
908    static final int PACKAGE_VERIFIED = 15;
909    static final int CHECK_PENDING_VERIFICATION = 16;
910    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
911    static final int INTENT_FILTER_VERIFIED = 18;
912
913    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
914
915    // Delay time in millisecs
916    static final int BROADCAST_DELAY = 10 * 1000;
917
918    static UserManagerService sUserManager;
919
920    // Stores a list of users whose package restrictions file needs to be updated
921    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
922
923    final private DefaultContainerConnection mDefContainerConn =
924            new DefaultContainerConnection();
925    class DefaultContainerConnection implements ServiceConnection {
926        public void onServiceConnected(ComponentName name, IBinder service) {
927            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
928            IMediaContainerService imcs =
929                IMediaContainerService.Stub.asInterface(service);
930            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
931        }
932
933        public void onServiceDisconnected(ComponentName name) {
934            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
935        }
936    }
937
938    // Recordkeeping of restore-after-install operations that are currently in flight
939    // between the Package Manager and the Backup Manager
940    class PostInstallData {
941        public InstallArgs args;
942        public PackageInstalledInfo res;
943
944        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
945            args = _a;
946            res = _r;
947        }
948    }
949
950    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
951    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
952
953    // XML tags for backup/restore of various bits of state
954    private static final String TAG_PREFERRED_BACKUP = "pa";
955    private static final String TAG_DEFAULT_APPS = "da";
956    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
957
958    final String mRequiredVerifierPackage;
959    final String mRequiredInstallerPackage;
960
961    private final PackageUsage mPackageUsage = new PackageUsage();
962
963    private class PackageUsage {
964        private static final int WRITE_INTERVAL
965            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
966
967        private final Object mFileLock = new Object();
968        private final AtomicLong mLastWritten = new AtomicLong(0);
969        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
970
971        private boolean mIsHistoricalPackageUsageAvailable = true;
972
973        boolean isHistoricalPackageUsageAvailable() {
974            return mIsHistoricalPackageUsageAvailable;
975        }
976
977        void write(boolean force) {
978            if (force) {
979                writeInternal();
980                return;
981            }
982            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
983                && !DEBUG_DEXOPT) {
984                return;
985            }
986            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
987                new Thread("PackageUsage_DiskWriter") {
988                    @Override
989                    public void run() {
990                        try {
991                            writeInternal();
992                        } finally {
993                            mBackgroundWriteRunning.set(false);
994                        }
995                    }
996                }.start();
997            }
998        }
999
1000        private void writeInternal() {
1001            synchronized (mPackages) {
1002                synchronized (mFileLock) {
1003                    AtomicFile file = getFile();
1004                    FileOutputStream f = null;
1005                    try {
1006                        f = file.startWrite();
1007                        BufferedOutputStream out = new BufferedOutputStream(f);
1008                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1009                        StringBuilder sb = new StringBuilder();
1010                        for (PackageParser.Package pkg : mPackages.values()) {
1011                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1012                                continue;
1013                            }
1014                            sb.setLength(0);
1015                            sb.append(pkg.packageName);
1016                            sb.append(' ');
1017                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1018                            sb.append('\n');
1019                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1020                        }
1021                        out.flush();
1022                        file.finishWrite(f);
1023                    } catch (IOException e) {
1024                        if (f != null) {
1025                            file.failWrite(f);
1026                        }
1027                        Log.e(TAG, "Failed to write package usage times", e);
1028                    }
1029                }
1030            }
1031            mLastWritten.set(SystemClock.elapsedRealtime());
1032        }
1033
1034        void readLP() {
1035            synchronized (mFileLock) {
1036                AtomicFile file = getFile();
1037                BufferedInputStream in = null;
1038                try {
1039                    in = new BufferedInputStream(file.openRead());
1040                    StringBuffer sb = new StringBuffer();
1041                    while (true) {
1042                        String packageName = readToken(in, sb, ' ');
1043                        if (packageName == null) {
1044                            break;
1045                        }
1046                        String timeInMillisString = readToken(in, sb, '\n');
1047                        if (timeInMillisString == null) {
1048                            throw new IOException("Failed to find last usage time for package "
1049                                                  + packageName);
1050                        }
1051                        PackageParser.Package pkg = mPackages.get(packageName);
1052                        if (pkg == null) {
1053                            continue;
1054                        }
1055                        long timeInMillis;
1056                        try {
1057                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1058                        } catch (NumberFormatException e) {
1059                            throw new IOException("Failed to parse " + timeInMillisString
1060                                                  + " as a long.", e);
1061                        }
1062                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1063                    }
1064                } catch (FileNotFoundException expected) {
1065                    mIsHistoricalPackageUsageAvailable = false;
1066                } catch (IOException e) {
1067                    Log.w(TAG, "Failed to read package usage times", e);
1068                } finally {
1069                    IoUtils.closeQuietly(in);
1070                }
1071            }
1072            mLastWritten.set(SystemClock.elapsedRealtime());
1073        }
1074
1075        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1076                throws IOException {
1077            sb.setLength(0);
1078            while (true) {
1079                int ch = in.read();
1080                if (ch == -1) {
1081                    if (sb.length() == 0) {
1082                        return null;
1083                    }
1084                    throw new IOException("Unexpected EOF");
1085                }
1086                if (ch == endOfToken) {
1087                    return sb.toString();
1088                }
1089                sb.append((char)ch);
1090            }
1091        }
1092
1093        private AtomicFile getFile() {
1094            File dataDir = Environment.getDataDirectory();
1095            File systemDir = new File(dataDir, "system");
1096            File fname = new File(systemDir, "package-usage.list");
1097            return new AtomicFile(fname);
1098        }
1099    }
1100
1101    class PackageHandler extends Handler {
1102        private boolean mBound = false;
1103        final ArrayList<HandlerParams> mPendingInstalls =
1104            new ArrayList<HandlerParams>();
1105
1106        private boolean connectToService() {
1107            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1108                    " DefaultContainerService");
1109            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1110            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1112                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1113                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1114                mBound = true;
1115                return true;
1116            }
1117            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1118            return false;
1119        }
1120
1121        private void disconnectService() {
1122            mContainerService = null;
1123            mBound = false;
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125            mContext.unbindService(mDefContainerConn);
1126            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127        }
1128
1129        PackageHandler(Looper looper) {
1130            super(looper);
1131        }
1132
1133        public void handleMessage(Message msg) {
1134            try {
1135                doHandleMessage(msg);
1136            } finally {
1137                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138            }
1139        }
1140
1141        void doHandleMessage(Message msg) {
1142            switch (msg.what) {
1143                case INIT_COPY: {
1144                    HandlerParams params = (HandlerParams) msg.obj;
1145                    int idx = mPendingInstalls.size();
1146                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1147                    // If a bind was already initiated we dont really
1148                    // need to do anything. The pending install
1149                    // will be processed later on.
1150                    if (!mBound) {
1151                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1152                                System.identityHashCode(mHandler));
1153                        // If this is the only one pending we might
1154                        // have to bind to the service again.
1155                        if (!connectToService()) {
1156                            Slog.e(TAG, "Failed to bind to media container service");
1157                            params.serviceError();
1158                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1159                                    System.identityHashCode(mHandler));
1160                            if (params.traceMethod != null) {
1161                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1162                                        params.traceCookie);
1163                            }
1164                            return;
1165                        } else {
1166                            // Once we bind to the service, the first
1167                            // pending request will be processed.
1168                            mPendingInstalls.add(idx, params);
1169                        }
1170                    } else {
1171                        mPendingInstalls.add(idx, params);
1172                        // Already bound to the service. Just make
1173                        // sure we trigger off processing the first request.
1174                        if (idx == 0) {
1175                            mHandler.sendEmptyMessage(MCS_BOUND);
1176                        }
1177                    }
1178                    break;
1179                }
1180                case MCS_BOUND: {
1181                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1182                    if (msg.obj != null) {
1183                        mContainerService = (IMediaContainerService) msg.obj;
1184                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1185                                System.identityHashCode(mHandler));
1186                    }
1187                    if (mContainerService == null) {
1188                        if (!mBound) {
1189                            // Something seriously wrong since we are not bound and we are not
1190                            // waiting for connection. Bail out.
1191                            Slog.e(TAG, "Cannot bind to media container service");
1192                            for (HandlerParams params : mPendingInstalls) {
1193                                // Indicate service bind error
1194                                params.serviceError();
1195                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1196                                        System.identityHashCode(params));
1197                                if (params.traceMethod != null) {
1198                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1199                                            params.traceMethod, params.traceCookie);
1200                                }
1201                                return;
1202                            }
1203                            mPendingInstalls.clear();
1204                        } else {
1205                            Slog.w(TAG, "Waiting to connect to media container service");
1206                        }
1207                    } else if (mPendingInstalls.size() > 0) {
1208                        HandlerParams params = mPendingInstalls.get(0);
1209                        if (params != null) {
1210                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1211                                    System.identityHashCode(params));
1212                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1213                            if (params.startCopy()) {
1214                                // We are done...  look for more work or to
1215                                // go idle.
1216                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1217                                        "Checking for more work or unbind...");
1218                                // Delete pending install
1219                                if (mPendingInstalls.size() > 0) {
1220                                    mPendingInstalls.remove(0);
1221                                }
1222                                if (mPendingInstalls.size() == 0) {
1223                                    if (mBound) {
1224                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1225                                                "Posting delayed MCS_UNBIND");
1226                                        removeMessages(MCS_UNBIND);
1227                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1228                                        // Unbind after a little delay, to avoid
1229                                        // continual thrashing.
1230                                        sendMessageDelayed(ubmsg, 10000);
1231                                    }
1232                                } else {
1233                                    // There are more pending requests in queue.
1234                                    // Just post MCS_BOUND message to trigger processing
1235                                    // of next pending install.
1236                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                            "Posting MCS_BOUND for next work");
1238                                    mHandler.sendEmptyMessage(MCS_BOUND);
1239                                }
1240                            }
1241                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1242                        }
1243                    } else {
1244                        // Should never happen ideally.
1245                        Slog.w(TAG, "Empty queue");
1246                    }
1247                    break;
1248                }
1249                case MCS_RECONNECT: {
1250                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1251                    if (mPendingInstalls.size() > 0) {
1252                        if (mBound) {
1253                            disconnectService();
1254                        }
1255                        if (!connectToService()) {
1256                            Slog.e(TAG, "Failed to bind to media container service");
1257                            for (HandlerParams params : mPendingInstalls) {
1258                                // Indicate service bind error
1259                                params.serviceError();
1260                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1261                                        System.identityHashCode(params));
1262                            }
1263                            mPendingInstalls.clear();
1264                        }
1265                    }
1266                    break;
1267                }
1268                case MCS_UNBIND: {
1269                    // If there is no actual work left, then time to unbind.
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1271
1272                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1273                        if (mBound) {
1274                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1275
1276                            disconnectService();
1277                        }
1278                    } else if (mPendingInstalls.size() > 0) {
1279                        // There are more pending requests in queue.
1280                        // Just post MCS_BOUND message to trigger processing
1281                        // of next pending install.
1282                        mHandler.sendEmptyMessage(MCS_BOUND);
1283                    }
1284
1285                    break;
1286                }
1287                case MCS_GIVE_UP: {
1288                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1289                    HandlerParams params = mPendingInstalls.remove(0);
1290                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1291                            System.identityHashCode(params));
1292                    break;
1293                }
1294                case SEND_PENDING_BROADCAST: {
1295                    String packages[];
1296                    ArrayList<String> components[];
1297                    int size = 0;
1298                    int uids[];
1299                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1300                    synchronized (mPackages) {
1301                        if (mPendingBroadcasts == null) {
1302                            return;
1303                        }
1304                        size = mPendingBroadcasts.size();
1305                        if (size <= 0) {
1306                            // Nothing to be done. Just return
1307                            return;
1308                        }
1309                        packages = new String[size];
1310                        components = new ArrayList[size];
1311                        uids = new int[size];
1312                        int i = 0;  // filling out the above arrays
1313
1314                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1315                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1316                            Iterator<Map.Entry<String, ArrayList<String>>> it
1317                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1318                                            .entrySet().iterator();
1319                            while (it.hasNext() && i < size) {
1320                                Map.Entry<String, ArrayList<String>> ent = it.next();
1321                                packages[i] = ent.getKey();
1322                                components[i] = ent.getValue();
1323                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1324                                uids[i] = (ps != null)
1325                                        ? UserHandle.getUid(packageUserId, ps.appId)
1326                                        : -1;
1327                                i++;
1328                            }
1329                        }
1330                        size = i;
1331                        mPendingBroadcasts.clear();
1332                    }
1333                    // Send broadcasts
1334                    for (int i = 0; i < size; i++) {
1335                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1336                    }
1337                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1338                    break;
1339                }
1340                case START_CLEANING_PACKAGE: {
1341                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1342                    final String packageName = (String)msg.obj;
1343                    final int userId = msg.arg1;
1344                    final boolean andCode = msg.arg2 != 0;
1345                    synchronized (mPackages) {
1346                        if (userId == UserHandle.USER_ALL) {
1347                            int[] users = sUserManager.getUserIds();
1348                            for (int user : users) {
1349                                mSettings.addPackageToCleanLPw(
1350                                        new PackageCleanItem(user, packageName, andCode));
1351                            }
1352                        } else {
1353                            mSettings.addPackageToCleanLPw(
1354                                    new PackageCleanItem(userId, packageName, andCode));
1355                        }
1356                    }
1357                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358                    startCleaningPackages();
1359                } break;
1360                case POST_INSTALL: {
1361                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1362                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1363                    mRunningInstalls.delete(msg.arg1);
1364                    boolean deleteOld = false;
1365
1366                    if (data != null) {
1367                        InstallArgs args = data.args;
1368                        PackageInstalledInfo res = data.res;
1369
1370                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1371                            final String packageName = res.pkg.applicationInfo.packageName;
1372                            res.removedInfo.sendBroadcast(false, true, false);
1373                            Bundle extras = new Bundle(1);
1374                            extras.putInt(Intent.EXTRA_UID, res.uid);
1375
1376                            // Now that we successfully installed the package, grant runtime
1377                            // permissions if requested before broadcasting the install.
1378                            if ((args.installFlags
1379                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1380                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1381                                        args.installGrantPermissions);
1382                            }
1383
1384                            // Determine the set of users who are adding this
1385                            // package for the first time vs. those who are seeing
1386                            // an update.
1387                            int[] firstUsers;
1388                            int[] updateUsers = new int[0];
1389                            if (res.origUsers == null || res.origUsers.length == 0) {
1390                                firstUsers = res.newUsers;
1391                            } else {
1392                                firstUsers = new int[0];
1393                                for (int i=0; i<res.newUsers.length; i++) {
1394                                    int user = res.newUsers[i];
1395                                    boolean isNew = true;
1396                                    for (int j=0; j<res.origUsers.length; j++) {
1397                                        if (res.origUsers[j] == user) {
1398                                            isNew = false;
1399                                            break;
1400                                        }
1401                                    }
1402                                    if (isNew) {
1403                                        int[] newFirst = new int[firstUsers.length+1];
1404                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1405                                                firstUsers.length);
1406                                        newFirst[firstUsers.length] = user;
1407                                        firstUsers = newFirst;
1408                                    } else {
1409                                        int[] newUpdate = new int[updateUsers.length+1];
1410                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1411                                                updateUsers.length);
1412                                        newUpdate[updateUsers.length] = user;
1413                                        updateUsers = newUpdate;
1414                                    }
1415                                }
1416                            }
1417                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1418                                    packageName, extras, null, null, firstUsers);
1419                            final boolean update = res.removedInfo.removedPackage != null;
1420                            if (update) {
1421                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1422                            }
1423                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1424                                    packageName, extras, null, null, updateUsers);
1425                            if (update) {
1426                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1427                                        packageName, extras, null, null, updateUsers);
1428                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1429                                        null, null, packageName, null, updateUsers);
1430
1431                                // treat asec-hosted packages like removable media on upgrade
1432                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1433                                    if (DEBUG_INSTALL) {
1434                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1435                                                + " is ASEC-hosted -> AVAILABLE");
1436                                    }
1437                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1438                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1439                                    pkgList.add(packageName);
1440                                    sendResourcesChangedBroadcast(true, true,
1441                                            pkgList,uidArray, null);
1442                                }
1443                            }
1444                            if (res.removedInfo.args != null) {
1445                                // Remove the replaced package's older resources safely now
1446                                deleteOld = true;
1447                            }
1448
1449                            // If this app is a browser and it's newly-installed for some
1450                            // users, clear any default-browser state in those users
1451                            if (firstUsers.length > 0) {
1452                                // the app's nature doesn't depend on the user, so we can just
1453                                // check its browser nature in any user and generalize.
1454                                if (packageIsBrowser(packageName, firstUsers[0])) {
1455                                    synchronized (mPackages) {
1456                                        for (int userId : firstUsers) {
1457                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1458                                        }
1459                                    }
1460                                }
1461                            }
1462                            // Log current value of "unknown sources" setting
1463                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1464                                getUnknownSourcesSettings());
1465                        }
1466                        // Force a gc to clear up things
1467                        Runtime.getRuntime().gc();
1468                        // We delete after a gc for applications  on sdcard.
1469                        if (deleteOld) {
1470                            synchronized (mInstallLock) {
1471                                res.removedInfo.args.doPostDeleteLI(true);
1472                            }
1473                        }
1474                        if (args.observer != null) {
1475                            try {
1476                                Bundle extras = extrasForInstallResult(res);
1477                                args.observer.onPackageInstalled(res.name, res.returnCode,
1478                                        res.returnMsg, extras);
1479                            } catch (RemoteException e) {
1480                                Slog.i(TAG, "Observer no longer exists.");
1481                            }
1482                        }
1483                        if (args.traceMethod != null) {
1484                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1485                                    args.traceCookie);
1486                        }
1487                        return;
1488                    } else {
1489                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1490                    }
1491
1492                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1493                } break;
1494                case UPDATED_MEDIA_STATUS: {
1495                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1496                    boolean reportStatus = msg.arg1 == 1;
1497                    boolean doGc = msg.arg2 == 1;
1498                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1499                    if (doGc) {
1500                        // Force a gc to clear up stale containers.
1501                        Runtime.getRuntime().gc();
1502                    }
1503                    if (msg.obj != null) {
1504                        @SuppressWarnings("unchecked")
1505                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1506                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1507                        // Unload containers
1508                        unloadAllContainers(args);
1509                    }
1510                    if (reportStatus) {
1511                        try {
1512                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1513                            PackageHelper.getMountService().finishMediaUpdate();
1514                        } catch (RemoteException e) {
1515                            Log.e(TAG, "MountService not running?");
1516                        }
1517                    }
1518                } break;
1519                case WRITE_SETTINGS: {
1520                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1521                    synchronized (mPackages) {
1522                        removeMessages(WRITE_SETTINGS);
1523                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1524                        mSettings.writeLPr();
1525                        mDirtyUsers.clear();
1526                    }
1527                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1528                } break;
1529                case WRITE_PACKAGE_RESTRICTIONS: {
1530                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1531                    synchronized (mPackages) {
1532                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1533                        for (int userId : mDirtyUsers) {
1534                            mSettings.writePackageRestrictionsLPr(userId);
1535                        }
1536                        mDirtyUsers.clear();
1537                    }
1538                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1539                } break;
1540                case CHECK_PENDING_VERIFICATION: {
1541                    final int verificationId = msg.arg1;
1542                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1543
1544                    if ((state != null) && !state.timeoutExtended()) {
1545                        final InstallArgs args = state.getInstallArgs();
1546                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1547
1548                        Slog.i(TAG, "Verification timed out for " + originUri);
1549                        mPendingVerification.remove(verificationId);
1550
1551                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1552
1553                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1554                            Slog.i(TAG, "Continuing with installation of " + originUri);
1555                            state.setVerifierResponse(Binder.getCallingUid(),
1556                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1557                            broadcastPackageVerified(verificationId, originUri,
1558                                    PackageManager.VERIFICATION_ALLOW,
1559                                    state.getInstallArgs().getUser());
1560                            try {
1561                                ret = args.copyApk(mContainerService, true);
1562                            } catch (RemoteException e) {
1563                                Slog.e(TAG, "Could not contact the ContainerService");
1564                            }
1565                        } else {
1566                            broadcastPackageVerified(verificationId, originUri,
1567                                    PackageManager.VERIFICATION_REJECT,
1568                                    state.getInstallArgs().getUser());
1569                        }
1570
1571                        Trace.asyncTraceEnd(
1572                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1573
1574                        processPendingInstall(args, ret);
1575                        mHandler.sendEmptyMessage(MCS_UNBIND);
1576                    }
1577                    break;
1578                }
1579                case PACKAGE_VERIFIED: {
1580                    final int verificationId = msg.arg1;
1581
1582                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1583                    if (state == null) {
1584                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1585                        break;
1586                    }
1587
1588                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1589
1590                    state.setVerifierResponse(response.callerUid, response.code);
1591
1592                    if (state.isVerificationComplete()) {
1593                        mPendingVerification.remove(verificationId);
1594
1595                        final InstallArgs args = state.getInstallArgs();
1596                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1597
1598                        int ret;
1599                        if (state.isInstallAllowed()) {
1600                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1601                            broadcastPackageVerified(verificationId, originUri,
1602                                    response.code, state.getInstallArgs().getUser());
1603                            try {
1604                                ret = args.copyApk(mContainerService, true);
1605                            } catch (RemoteException e) {
1606                                Slog.e(TAG, "Could not contact the ContainerService");
1607                            }
1608                        } else {
1609                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1610                        }
1611
1612                        Trace.asyncTraceEnd(
1613                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1614
1615                        processPendingInstall(args, ret);
1616                        mHandler.sendEmptyMessage(MCS_UNBIND);
1617                    }
1618
1619                    break;
1620                }
1621                case START_INTENT_FILTER_VERIFICATIONS: {
1622                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1623                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1624                            params.replacing, params.pkg);
1625                    break;
1626                }
1627                case INTENT_FILTER_VERIFIED: {
1628                    final int verificationId = msg.arg1;
1629
1630                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1631                            verificationId);
1632                    if (state == null) {
1633                        Slog.w(TAG, "Invalid IntentFilter verification token "
1634                                + verificationId + " received");
1635                        break;
1636                    }
1637
1638                    final int userId = state.getUserId();
1639
1640                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1641                            "Processing IntentFilter verification with token:"
1642                            + verificationId + " and userId:" + userId);
1643
1644                    final IntentFilterVerificationResponse response =
1645                            (IntentFilterVerificationResponse) msg.obj;
1646
1647                    state.setVerifierResponse(response.callerUid, response.code);
1648
1649                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1650                            "IntentFilter verification with token:" + verificationId
1651                            + " and userId:" + userId
1652                            + " is settings verifier response with response code:"
1653                            + response.code);
1654
1655                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1656                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1657                                + response.getFailedDomainsString());
1658                    }
1659
1660                    if (state.isVerificationComplete()) {
1661                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1662                    } else {
1663                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1664                                "IntentFilter verification with token:" + verificationId
1665                                + " was not said to be complete");
1666                    }
1667
1668                    break;
1669                }
1670            }
1671        }
1672    }
1673
1674    private StorageEventListener mStorageListener = new StorageEventListener() {
1675        @Override
1676        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1677            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1678                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1679                    final String volumeUuid = vol.getFsUuid();
1680
1681                    // Clean up any users or apps that were removed or recreated
1682                    // while this volume was missing
1683                    reconcileUsers(volumeUuid);
1684                    reconcileApps(volumeUuid);
1685
1686                    // Clean up any install sessions that expired or were
1687                    // cancelled while this volume was missing
1688                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1689
1690                    loadPrivatePackages(vol);
1691
1692                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1693                    unloadPrivatePackages(vol);
1694                }
1695            }
1696
1697            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1698                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1699                    updateExternalMediaStatus(true, false);
1700                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1701                    updateExternalMediaStatus(false, false);
1702                }
1703            }
1704        }
1705
1706        @Override
1707        public void onVolumeForgotten(String fsUuid) {
1708            if (TextUtils.isEmpty(fsUuid)) {
1709                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1710                return;
1711            }
1712
1713            // Remove any apps installed on the forgotten volume
1714            synchronized (mPackages) {
1715                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1716                for (PackageSetting ps : packages) {
1717                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1718                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1719                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1720                }
1721
1722                mSettings.onVolumeForgotten(fsUuid);
1723                mSettings.writeLPr();
1724            }
1725        }
1726    };
1727
1728    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1729            String[] grantedPermissions) {
1730        if (userId >= UserHandle.USER_SYSTEM) {
1731            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1732        } else if (userId == UserHandle.USER_ALL) {
1733            final int[] userIds;
1734            synchronized (mPackages) {
1735                userIds = UserManagerService.getInstance().getUserIds();
1736            }
1737            for (int someUserId : userIds) {
1738                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1739            }
1740        }
1741
1742        // We could have touched GID membership, so flush out packages.list
1743        synchronized (mPackages) {
1744            mSettings.writePackageListLPr();
1745        }
1746    }
1747
1748    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1749            String[] grantedPermissions) {
1750        SettingBase sb = (SettingBase) pkg.mExtras;
1751        if (sb == null) {
1752            return;
1753        }
1754
1755        PermissionsState permissionsState = sb.getPermissionsState();
1756
1757        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1758                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1759
1760        synchronized (mPackages) {
1761            for (String permission : pkg.requestedPermissions) {
1762                BasePermission bp = mSettings.mPermissions.get(permission);
1763                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1764                        && (grantedPermissions == null
1765                               || ArrayUtils.contains(grantedPermissions, permission))) {
1766                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1767                    // Installer cannot change immutable permissions.
1768                    if ((flags & immutableFlags) == 0) {
1769                        grantRuntimePermission(pkg.packageName, permission, userId);
1770                    }
1771                }
1772            }
1773        }
1774    }
1775
1776    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1777        Bundle extras = null;
1778        switch (res.returnCode) {
1779            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1780                extras = new Bundle();
1781                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1782                        res.origPermission);
1783                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1784                        res.origPackage);
1785                break;
1786            }
1787            case PackageManager.INSTALL_SUCCEEDED: {
1788                extras = new Bundle();
1789                extras.putBoolean(Intent.EXTRA_REPLACING,
1790                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1791                break;
1792            }
1793        }
1794        return extras;
1795    }
1796
1797    void scheduleWriteSettingsLocked() {
1798        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1799            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1800        }
1801    }
1802
1803    void scheduleWritePackageRestrictionsLocked(int userId) {
1804        if (!sUserManager.exists(userId)) return;
1805        mDirtyUsers.add(userId);
1806        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1807            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1808        }
1809    }
1810
1811    public static PackageManagerService main(Context context, Installer installer,
1812            boolean factoryTest, boolean onlyCore) {
1813        PackageManagerService m = new PackageManagerService(context, installer,
1814                factoryTest, onlyCore);
1815        ServiceManager.addService("package", m);
1816        return m;
1817    }
1818
1819    static String[] splitString(String str, char sep) {
1820        int count = 1;
1821        int i = 0;
1822        while ((i=str.indexOf(sep, i)) >= 0) {
1823            count++;
1824            i++;
1825        }
1826
1827        String[] res = new String[count];
1828        i=0;
1829        count = 0;
1830        int lastI=0;
1831        while ((i=str.indexOf(sep, i)) >= 0) {
1832            res[count] = str.substring(lastI, i);
1833            count++;
1834            i++;
1835            lastI = i;
1836        }
1837        res[count] = str.substring(lastI, str.length());
1838        return res;
1839    }
1840
1841    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1842        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1843                Context.DISPLAY_SERVICE);
1844        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1845    }
1846
1847    public PackageManagerService(Context context, Installer installer,
1848            boolean factoryTest, boolean onlyCore) {
1849        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1850                SystemClock.uptimeMillis());
1851
1852        if (mSdkVersion <= 0) {
1853            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1854        }
1855
1856        mContext = context;
1857        mFactoryTest = factoryTest;
1858        mOnlyCore = onlyCore;
1859        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1860        mMetrics = new DisplayMetrics();
1861        mSettings = new Settings(mPackages);
1862        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1863                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1864        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1865                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1866        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1867                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1868        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1869                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1870        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1871                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1872        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1873                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1874
1875        // TODO: add a property to control this?
1876        long dexOptLRUThresholdInMinutes;
1877        if (mLazyDexOpt) {
1878            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1879        } else {
1880            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1881        }
1882        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1883
1884        String separateProcesses = SystemProperties.get("debug.separate_processes");
1885        if (separateProcesses != null && separateProcesses.length() > 0) {
1886            if ("*".equals(separateProcesses)) {
1887                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1888                mSeparateProcesses = null;
1889                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1890            } else {
1891                mDefParseFlags = 0;
1892                mSeparateProcesses = separateProcesses.split(",");
1893                Slog.w(TAG, "Running with debug.separate_processes: "
1894                        + separateProcesses);
1895            }
1896        } else {
1897            mDefParseFlags = 0;
1898            mSeparateProcesses = null;
1899        }
1900
1901        mInstaller = installer;
1902        mPackageDexOptimizer = new PackageDexOptimizer(this);
1903        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1904
1905        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1906                FgThread.get().getLooper());
1907
1908        getDefaultDisplayMetrics(context, mMetrics);
1909
1910        SystemConfig systemConfig = SystemConfig.getInstance();
1911        mGlobalGids = systemConfig.getGlobalGids();
1912        mSystemPermissions = systemConfig.getSystemPermissions();
1913        mAvailableFeatures = systemConfig.getAvailableFeatures();
1914
1915        synchronized (mInstallLock) {
1916        // writer
1917        synchronized (mPackages) {
1918            mHandlerThread = new ServiceThread(TAG,
1919                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1920            mHandlerThread.start();
1921            mHandler = new PackageHandler(mHandlerThread.getLooper());
1922            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1923
1924            File dataDir = Environment.getDataDirectory();
1925            mAppDataDir = new File(dataDir, "data");
1926            mAppInstallDir = new File(dataDir, "app");
1927            mAppLib32InstallDir = new File(dataDir, "app-lib");
1928            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1929            mUserAppDataDir = new File(dataDir, "user");
1930            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1931
1932            sUserManager = new UserManagerService(context, this,
1933                    mInstallLock, mPackages);
1934
1935            // Propagate permission configuration in to package manager.
1936            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1937                    = systemConfig.getPermissions();
1938            for (int i=0; i<permConfig.size(); i++) {
1939                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1940                BasePermission bp = mSettings.mPermissions.get(perm.name);
1941                if (bp == null) {
1942                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1943                    mSettings.mPermissions.put(perm.name, bp);
1944                }
1945                if (perm.gids != null) {
1946                    bp.setGids(perm.gids, perm.perUser);
1947                }
1948            }
1949
1950            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1951            for (int i=0; i<libConfig.size(); i++) {
1952                mSharedLibraries.put(libConfig.keyAt(i),
1953                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1954            }
1955
1956            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1957
1958            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1959
1960            String customResolverActivity = Resources.getSystem().getString(
1961                    R.string.config_customResolverActivity);
1962            if (TextUtils.isEmpty(customResolverActivity)) {
1963                customResolverActivity = null;
1964            } else {
1965                mCustomResolverComponentName = ComponentName.unflattenFromString(
1966                        customResolverActivity);
1967            }
1968
1969            long startTime = SystemClock.uptimeMillis();
1970
1971            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1972                    startTime);
1973
1974            // Set flag to monitor and not change apk file paths when
1975            // scanning install directories.
1976            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1977
1978            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1979
1980            /**
1981             * Add everything in the in the boot class path to the
1982             * list of process files because dexopt will have been run
1983             * if necessary during zygote startup.
1984             */
1985            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1986            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1987
1988            if (bootClassPath != null) {
1989                String[] bootClassPathElements = splitString(bootClassPath, ':');
1990                for (String element : bootClassPathElements) {
1991                    alreadyDexOpted.add(element);
1992                }
1993            } else {
1994                Slog.w(TAG, "No BOOTCLASSPATH found!");
1995            }
1996
1997            if (systemServerClassPath != null) {
1998                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1999                for (String element : systemServerClassPathElements) {
2000                    alreadyDexOpted.add(element);
2001                }
2002            } else {
2003                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2004            }
2005
2006            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2007            final String[] dexCodeInstructionSets =
2008                    getDexCodeInstructionSets(
2009                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2010
2011            /**
2012             * Ensure all external libraries have had dexopt run on them.
2013             */
2014            if (mSharedLibraries.size() > 0) {
2015                // NOTE: For now, we're compiling these system "shared libraries"
2016                // (and framework jars) into all available architectures. It's possible
2017                // to compile them only when we come across an app that uses them (there's
2018                // already logic for that in scanPackageLI) but that adds some complexity.
2019                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2020                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2021                        final String lib = libEntry.path;
2022                        if (lib == null) {
2023                            continue;
2024                        }
2025
2026                        try {
2027                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2028                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2029                                alreadyDexOpted.add(lib);
2030                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2031                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2032                            }
2033                        } catch (FileNotFoundException e) {
2034                            Slog.w(TAG, "Library not found: " + lib);
2035                        } catch (IOException e) {
2036                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2037                                    + e.getMessage());
2038                        }
2039                    }
2040                }
2041            }
2042
2043            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2044
2045            // Gross hack for now: we know this file doesn't contain any
2046            // code, so don't dexopt it to avoid the resulting log spew.
2047            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2048
2049            // Gross hack for now: we know this file is only part of
2050            // the boot class path for art, so don't dexopt it to
2051            // avoid the resulting log spew.
2052            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2053
2054            /**
2055             * There are a number of commands implemented in Java, which
2056             * we currently need to do the dexopt on so that they can be
2057             * run from a non-root shell.
2058             */
2059            String[] frameworkFiles = frameworkDir.list();
2060            if (frameworkFiles != null) {
2061                // TODO: We could compile these only for the most preferred ABI. We should
2062                // first double check that the dex files for these commands are not referenced
2063                // by other system apps.
2064                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2065                    for (int i=0; i<frameworkFiles.length; i++) {
2066                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2067                        String path = libPath.getPath();
2068                        // Skip the file if we already did it.
2069                        if (alreadyDexOpted.contains(path)) {
2070                            continue;
2071                        }
2072                        // Skip the file if it is not a type we want to dexopt.
2073                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2074                            continue;
2075                        }
2076                        try {
2077                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2078                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2079                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2080                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2081                            }
2082                        } catch (FileNotFoundException e) {
2083                            Slog.w(TAG, "Jar not found: " + path);
2084                        } catch (IOException e) {
2085                            Slog.w(TAG, "Exception reading jar: " + path, e);
2086                        }
2087                    }
2088                }
2089            }
2090
2091            final VersionInfo ver = mSettings.getInternalVersion();
2092            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2093            // when upgrading from pre-M, promote system app permissions from install to runtime
2094            mPromoteSystemApps =
2095                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2096
2097            // save off the names of pre-existing system packages prior to scanning; we don't
2098            // want to automatically grant runtime permissions for new system apps
2099            if (mPromoteSystemApps) {
2100                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2101                while (pkgSettingIter.hasNext()) {
2102                    PackageSetting ps = pkgSettingIter.next();
2103                    if (isSystemApp(ps)) {
2104                        mExistingSystemPackages.add(ps.name);
2105                    }
2106                }
2107            }
2108
2109            // Collect vendor overlay packages.
2110            // (Do this before scanning any apps.)
2111            // For security and version matching reason, only consider
2112            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2113            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2114            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2115                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2116
2117            // Find base frameworks (resource packages without code).
2118            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2119                    | PackageParser.PARSE_IS_SYSTEM_DIR
2120                    | PackageParser.PARSE_IS_PRIVILEGED,
2121                    scanFlags | SCAN_NO_DEX, 0);
2122
2123            // Collected privileged system packages.
2124            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2125            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2126                    | PackageParser.PARSE_IS_SYSTEM_DIR
2127                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2128
2129            // Collect ordinary system packages.
2130            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2131            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2132                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2133
2134            // Collect all vendor packages.
2135            File vendorAppDir = new File("/vendor/app");
2136            try {
2137                vendorAppDir = vendorAppDir.getCanonicalFile();
2138            } catch (IOException e) {
2139                // failed to look up canonical path, continue with original one
2140            }
2141            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2142                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2143
2144            // Collect all OEM packages.
2145            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2146            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2147                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2148
2149            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2150            mInstaller.moveFiles();
2151
2152            // Prune any system packages that no longer exist.
2153            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2154            if (!mOnlyCore) {
2155                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2156                while (psit.hasNext()) {
2157                    PackageSetting ps = psit.next();
2158
2159                    /*
2160                     * If this is not a system app, it can't be a
2161                     * disable system app.
2162                     */
2163                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2164                        continue;
2165                    }
2166
2167                    /*
2168                     * If the package is scanned, it's not erased.
2169                     */
2170                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2171                    if (scannedPkg != null) {
2172                        /*
2173                         * If the system app is both scanned and in the
2174                         * disabled packages list, then it must have been
2175                         * added via OTA. Remove it from the currently
2176                         * scanned package so the previously user-installed
2177                         * application can be scanned.
2178                         */
2179                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2180                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2181                                    + ps.name + "; removing system app.  Last known codePath="
2182                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2183                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2184                                    + scannedPkg.mVersionCode);
2185                            removePackageLI(ps, true);
2186                            mExpectingBetter.put(ps.name, ps.codePath);
2187                        }
2188
2189                        continue;
2190                    }
2191
2192                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2193                        psit.remove();
2194                        logCriticalInfo(Log.WARN, "System package " + ps.name
2195                                + " no longer exists; wiping its data");
2196                        removeDataDirsLI(null, ps.name);
2197                    } else {
2198                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2199                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2200                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2201                        }
2202                    }
2203                }
2204            }
2205
2206            //look for any incomplete package installations
2207            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2208            //clean up list
2209            for(int i = 0; i < deletePkgsList.size(); i++) {
2210                //clean up here
2211                cleanupInstallFailedPackage(deletePkgsList.get(i));
2212            }
2213            //delete tmp files
2214            deleteTempPackageFiles();
2215
2216            // Remove any shared userIDs that have no associated packages
2217            mSettings.pruneSharedUsersLPw();
2218
2219            if (!mOnlyCore) {
2220                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2221                        SystemClock.uptimeMillis());
2222                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2223
2224                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2225                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2226
2227                /**
2228                 * Remove disable package settings for any updated system
2229                 * apps that were removed via an OTA. If they're not a
2230                 * previously-updated app, remove them completely.
2231                 * Otherwise, just revoke their system-level permissions.
2232                 */
2233                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2234                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2235                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2236
2237                    String msg;
2238                    if (deletedPkg == null) {
2239                        msg = "Updated system package " + deletedAppName
2240                                + " no longer exists; wiping its data";
2241                        removeDataDirsLI(null, deletedAppName);
2242                    } else {
2243                        msg = "Updated system app + " + deletedAppName
2244                                + " no longer present; removing system privileges for "
2245                                + deletedAppName;
2246
2247                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2248
2249                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2250                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2251                    }
2252                    logCriticalInfo(Log.WARN, msg);
2253                }
2254
2255                /**
2256                 * Make sure all system apps that we expected to appear on
2257                 * the userdata partition actually showed up. If they never
2258                 * appeared, crawl back and revive the system version.
2259                 */
2260                for (int i = 0; i < mExpectingBetter.size(); i++) {
2261                    final String packageName = mExpectingBetter.keyAt(i);
2262                    if (!mPackages.containsKey(packageName)) {
2263                        final File scanFile = mExpectingBetter.valueAt(i);
2264
2265                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2266                                + " but never showed up; reverting to system");
2267
2268                        final int reparseFlags;
2269                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2270                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2271                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2272                                    | PackageParser.PARSE_IS_PRIVILEGED;
2273                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2274                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2275                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2276                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2277                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2278                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2279                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2280                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2281                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2282                        } else {
2283                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2284                            continue;
2285                        }
2286
2287                        mSettings.enableSystemPackageLPw(packageName);
2288
2289                        try {
2290                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2291                        } catch (PackageManagerException e) {
2292                            Slog.e(TAG, "Failed to parse original system package: "
2293                                    + e.getMessage());
2294                        }
2295                    }
2296                }
2297            }
2298            mExpectingBetter.clear();
2299
2300            // Now that we know all of the shared libraries, update all clients to have
2301            // the correct library paths.
2302            updateAllSharedLibrariesLPw();
2303
2304            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2305                // NOTE: We ignore potential failures here during a system scan (like
2306                // the rest of the commands above) because there's precious little we
2307                // can do about it. A settings error is reported, though.
2308                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2309                        false /* force dexopt */, false /* defer dexopt */,
2310                        false /* boot complete */);
2311            }
2312
2313            // Now that we know all the packages we are keeping,
2314            // read and update their last usage times.
2315            mPackageUsage.readLP();
2316
2317            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2318                    SystemClock.uptimeMillis());
2319            Slog.i(TAG, "Time to scan packages: "
2320                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2321                    + " seconds");
2322
2323            // If the platform SDK has changed since the last time we booted,
2324            // we need to re-grant app permission to catch any new ones that
2325            // appear.  This is really a hack, and means that apps can in some
2326            // cases get permissions that the user didn't initially explicitly
2327            // allow...  it would be nice to have some better way to handle
2328            // this situation.
2329            int updateFlags = UPDATE_PERMISSIONS_ALL;
2330            if (ver.sdkVersion != mSdkVersion) {
2331                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2332                        + mSdkVersion + "; regranting permissions for internal storage");
2333                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2334            }
2335            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2336            ver.sdkVersion = mSdkVersion;
2337
2338            // If this is the first boot or an update from pre-M, and it is a normal
2339            // boot, then we need to initialize the default preferred apps across
2340            // all defined users.
2341            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2342                for (UserInfo user : sUserManager.getUsers(true)) {
2343                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2344                    applyFactoryDefaultBrowserLPw(user.id);
2345                    primeDomainVerificationsLPw(user.id);
2346                }
2347            }
2348
2349            // If this is first boot after an OTA, and a normal boot, then
2350            // we need to clear code cache directories.
2351            if (mIsUpgrade && !onlyCore) {
2352                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2353                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2354                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2355                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2356                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2357                    }
2358                }
2359                ver.fingerprint = Build.FINGERPRINT;
2360            }
2361
2362            checkDefaultBrowser();
2363
2364            // clear only after permissions and other defaults have been updated
2365            mExistingSystemPackages.clear();
2366            mPromoteSystemApps = false;
2367
2368            // All the changes are done during package scanning.
2369            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2370
2371            // can downgrade to reader
2372            mSettings.writeLPr();
2373
2374            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2375                    SystemClock.uptimeMillis());
2376
2377            mRequiredVerifierPackage = getRequiredVerifierLPr();
2378            mRequiredInstallerPackage = getRequiredInstallerLPr();
2379
2380            mInstallerService = new PackageInstallerService(context, this);
2381
2382            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2383            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2384                    mIntentFilterVerifierComponent);
2385
2386        } // synchronized (mPackages)
2387        } // synchronized (mInstallLock)
2388
2389        // Now after opening every single application zip, make sure they
2390        // are all flushed.  Not really needed, but keeps things nice and
2391        // tidy.
2392        Runtime.getRuntime().gc();
2393
2394        // The initial scanning above does many calls into installd while
2395        // holding the mPackages lock, but we're mostly interested in yelling
2396        // once we have a booted system.
2397        mInstaller.setWarnIfHeld(mPackages);
2398
2399        // Expose private service for system components to use.
2400        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2401    }
2402
2403    @Override
2404    public boolean isFirstBoot() {
2405        return !mRestoredSettings;
2406    }
2407
2408    @Override
2409    public boolean isOnlyCoreApps() {
2410        return mOnlyCore;
2411    }
2412
2413    @Override
2414    public boolean isUpgrade() {
2415        return mIsUpgrade;
2416    }
2417
2418    private String getRequiredVerifierLPr() {
2419        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2420        // We only care about verifier that's installed under system user.
2421        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2422                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2423
2424        String requiredVerifier = null;
2425
2426        final int N = receivers.size();
2427        for (int i = 0; i < N; i++) {
2428            final ResolveInfo info = receivers.get(i);
2429
2430            if (info.activityInfo == null) {
2431                continue;
2432            }
2433
2434            final String packageName = info.activityInfo.packageName;
2435
2436            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2437                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2438                continue;
2439            }
2440
2441            if (requiredVerifier != null) {
2442                throw new RuntimeException("There can be only one required verifier");
2443            }
2444
2445            requiredVerifier = packageName;
2446        }
2447
2448        return requiredVerifier;
2449    }
2450
2451    private String getRequiredInstallerLPr() {
2452        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2453        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2454        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2455
2456        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2457                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2458
2459        String requiredInstaller = null;
2460
2461        final int N = installers.size();
2462        for (int i = 0; i < N; i++) {
2463            final ResolveInfo info = installers.get(i);
2464            final String packageName = info.activityInfo.packageName;
2465
2466            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2467                continue;
2468            }
2469
2470            if (requiredInstaller != null) {
2471                throw new RuntimeException("There must be one required installer");
2472            }
2473
2474            requiredInstaller = packageName;
2475        }
2476
2477        if (requiredInstaller == null) {
2478            throw new RuntimeException("There must be one required installer");
2479        }
2480
2481        return requiredInstaller;
2482    }
2483
2484    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2485        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2486        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2487                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2488
2489        ComponentName verifierComponentName = null;
2490
2491        int priority = -1000;
2492        final int N = receivers.size();
2493        for (int i = 0; i < N; i++) {
2494            final ResolveInfo info = receivers.get(i);
2495
2496            if (info.activityInfo == null) {
2497                continue;
2498            }
2499
2500            final String packageName = info.activityInfo.packageName;
2501
2502            final PackageSetting ps = mSettings.mPackages.get(packageName);
2503            if (ps == null) {
2504                continue;
2505            }
2506
2507            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2508                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2509                continue;
2510            }
2511
2512            // Select the IntentFilterVerifier with the highest priority
2513            if (priority < info.priority) {
2514                priority = info.priority;
2515                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2516                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2517                        + verifierComponentName + " with priority: " + info.priority);
2518            }
2519        }
2520
2521        return verifierComponentName;
2522    }
2523
2524    private void primeDomainVerificationsLPw(int userId) {
2525        if (DEBUG_DOMAIN_VERIFICATION) {
2526            Slog.d(TAG, "Priming domain verifications in user " + userId);
2527        }
2528
2529        SystemConfig systemConfig = SystemConfig.getInstance();
2530        ArraySet<String> packages = systemConfig.getLinkedApps();
2531        ArraySet<String> domains = new ArraySet<String>();
2532
2533        for (String packageName : packages) {
2534            PackageParser.Package pkg = mPackages.get(packageName);
2535            if (pkg != null) {
2536                if (!pkg.isSystemApp()) {
2537                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2538                    continue;
2539                }
2540
2541                domains.clear();
2542                for (PackageParser.Activity a : pkg.activities) {
2543                    for (ActivityIntentInfo filter : a.intents) {
2544                        if (hasValidDomains(filter)) {
2545                            domains.addAll(filter.getHostsList());
2546                        }
2547                    }
2548                }
2549
2550                if (domains.size() > 0) {
2551                    if (DEBUG_DOMAIN_VERIFICATION) {
2552                        Slog.v(TAG, "      + " + packageName);
2553                    }
2554                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2555                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2556                    // and then 'always' in the per-user state actually used for intent resolution.
2557                    final IntentFilterVerificationInfo ivi;
2558                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2559                            new ArrayList<String>(domains));
2560                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2561                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2562                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2563                } else {
2564                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2565                            + "' does not handle web links");
2566                }
2567            } else {
2568                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2569            }
2570        }
2571
2572        scheduleWritePackageRestrictionsLocked(userId);
2573        scheduleWriteSettingsLocked();
2574    }
2575
2576    private void applyFactoryDefaultBrowserLPw(int userId) {
2577        // The default browser app's package name is stored in a string resource,
2578        // with a product-specific overlay used for vendor customization.
2579        String browserPkg = mContext.getResources().getString(
2580                com.android.internal.R.string.default_browser);
2581        if (!TextUtils.isEmpty(browserPkg)) {
2582            // non-empty string => required to be a known package
2583            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2584            if (ps == null) {
2585                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2586                browserPkg = null;
2587            } else {
2588                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2589            }
2590        }
2591
2592        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2593        // default.  If there's more than one, just leave everything alone.
2594        if (browserPkg == null) {
2595            calculateDefaultBrowserLPw(userId);
2596        }
2597    }
2598
2599    private void calculateDefaultBrowserLPw(int userId) {
2600        List<String> allBrowsers = resolveAllBrowserApps(userId);
2601        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2602        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2603    }
2604
2605    private List<String> resolveAllBrowserApps(int userId) {
2606        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2607        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2608                PackageManager.MATCH_ALL, userId);
2609
2610        final int count = list.size();
2611        List<String> result = new ArrayList<String>(count);
2612        for (int i=0; i<count; i++) {
2613            ResolveInfo info = list.get(i);
2614            if (info.activityInfo == null
2615                    || !info.handleAllWebDataURI
2616                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2617                    || result.contains(info.activityInfo.packageName)) {
2618                continue;
2619            }
2620            result.add(info.activityInfo.packageName);
2621        }
2622
2623        return result;
2624    }
2625
2626    private boolean packageIsBrowser(String packageName, int userId) {
2627        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2628                PackageManager.MATCH_ALL, userId);
2629        final int N = list.size();
2630        for (int i = 0; i < N; i++) {
2631            ResolveInfo info = list.get(i);
2632            if (packageName.equals(info.activityInfo.packageName)) {
2633                return true;
2634            }
2635        }
2636        return false;
2637    }
2638
2639    private void checkDefaultBrowser() {
2640        final int myUserId = UserHandle.myUserId();
2641        final String packageName = getDefaultBrowserPackageName(myUserId);
2642        if (packageName != null) {
2643            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2644            if (info == null) {
2645                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2646                synchronized (mPackages) {
2647                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2648                }
2649            }
2650        }
2651    }
2652
2653    @Override
2654    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2655            throws RemoteException {
2656        try {
2657            return super.onTransact(code, data, reply, flags);
2658        } catch (RuntimeException e) {
2659            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2660                Slog.wtf(TAG, "Package Manager Crash", e);
2661            }
2662            throw e;
2663        }
2664    }
2665
2666    void cleanupInstallFailedPackage(PackageSetting ps) {
2667        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2668
2669        removeDataDirsLI(ps.volumeUuid, ps.name);
2670        if (ps.codePath != null) {
2671            if (ps.codePath.isDirectory()) {
2672                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2673            } else {
2674                ps.codePath.delete();
2675            }
2676        }
2677        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2678            if (ps.resourcePath.isDirectory()) {
2679                FileUtils.deleteContents(ps.resourcePath);
2680            }
2681            ps.resourcePath.delete();
2682        }
2683        mSettings.removePackageLPw(ps.name);
2684    }
2685
2686    static int[] appendInts(int[] cur, int[] add) {
2687        if (add == null) return cur;
2688        if (cur == null) return add;
2689        final int N = add.length;
2690        for (int i=0; i<N; i++) {
2691            cur = appendInt(cur, add[i]);
2692        }
2693        return cur;
2694    }
2695
2696    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2697        if (!sUserManager.exists(userId)) return null;
2698        final PackageSetting ps = (PackageSetting) p.mExtras;
2699        if (ps == null) {
2700            return null;
2701        }
2702
2703        final PermissionsState permissionsState = ps.getPermissionsState();
2704
2705        final int[] gids = permissionsState.computeGids(userId);
2706        final Set<String> permissions = permissionsState.getPermissions(userId);
2707        final PackageUserState state = ps.readUserState(userId);
2708
2709        return PackageParser.generatePackageInfo(p, gids, flags,
2710                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2711    }
2712
2713    @Override
2714    public boolean isPackageFrozen(String packageName) {
2715        synchronized (mPackages) {
2716            final PackageSetting ps = mSettings.mPackages.get(packageName);
2717            if (ps != null) {
2718                return ps.frozen;
2719            }
2720        }
2721        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2722        return true;
2723    }
2724
2725    @Override
2726    public boolean isPackageAvailable(String packageName, int userId) {
2727        if (!sUserManager.exists(userId)) return false;
2728        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2729        synchronized (mPackages) {
2730            PackageParser.Package p = mPackages.get(packageName);
2731            if (p != null) {
2732                final PackageSetting ps = (PackageSetting) p.mExtras;
2733                if (ps != null) {
2734                    final PackageUserState state = ps.readUserState(userId);
2735                    if (state != null) {
2736                        return PackageParser.isAvailable(state);
2737                    }
2738                }
2739            }
2740        }
2741        return false;
2742    }
2743
2744    @Override
2745    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2746        if (!sUserManager.exists(userId)) return null;
2747        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2748        // reader
2749        synchronized (mPackages) {
2750            PackageParser.Package p = mPackages.get(packageName);
2751            if (DEBUG_PACKAGE_INFO)
2752                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2753            if (p != null) {
2754                return generatePackageInfo(p, flags, userId);
2755            }
2756            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2757                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2758            }
2759        }
2760        return null;
2761    }
2762
2763    @Override
2764    public String[] currentToCanonicalPackageNames(String[] names) {
2765        String[] out = new String[names.length];
2766        // reader
2767        synchronized (mPackages) {
2768            for (int i=names.length-1; i>=0; i--) {
2769                PackageSetting ps = mSettings.mPackages.get(names[i]);
2770                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2771            }
2772        }
2773        return out;
2774    }
2775
2776    @Override
2777    public String[] canonicalToCurrentPackageNames(String[] names) {
2778        String[] out = new String[names.length];
2779        // reader
2780        synchronized (mPackages) {
2781            for (int i=names.length-1; i>=0; i--) {
2782                String cur = mSettings.mRenamedPackages.get(names[i]);
2783                out[i] = cur != null ? cur : names[i];
2784            }
2785        }
2786        return out;
2787    }
2788
2789    @Override
2790    public int getPackageUid(String packageName, int userId) {
2791        return getPackageUidEtc(packageName, 0, userId);
2792    }
2793
2794    @Override
2795    public int getPackageUidEtc(String packageName, int flags, int userId) {
2796        if (!sUserManager.exists(userId)) return -1;
2797        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2798
2799        // reader
2800        synchronized (mPackages) {
2801            final PackageParser.Package p = mPackages.get(packageName);
2802            if (p != null) {
2803                return UserHandle.getUid(userId, p.applicationInfo.uid);
2804            }
2805            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2806                final PackageSetting ps = mSettings.mPackages.get(packageName);
2807                if (ps != null) {
2808                    return UserHandle.getUid(userId, ps.appId);
2809                }
2810            }
2811        }
2812
2813        return -1;
2814    }
2815
2816    @Override
2817    public int[] getPackageGids(String packageName, int userId) {
2818        return getPackageGidsEtc(packageName, 0, userId);
2819    }
2820
2821    @Override
2822    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2823        if (!sUserManager.exists(userId)) {
2824            return null;
2825        }
2826
2827        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2828                "getPackageGids");
2829
2830        // reader
2831        synchronized (mPackages) {
2832            final PackageParser.Package p = mPackages.get(packageName);
2833            if (p != null) {
2834                PackageSetting ps = (PackageSetting) p.mExtras;
2835                return ps.getPermissionsState().computeGids(userId);
2836            }
2837            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2838                final PackageSetting ps = mSettings.mPackages.get(packageName);
2839                if (ps != null) {
2840                    return ps.getPermissionsState().computeGids(userId);
2841                }
2842            }
2843        }
2844
2845        return null;
2846    }
2847
2848    static PermissionInfo generatePermissionInfo(
2849            BasePermission bp, int flags) {
2850        if (bp.perm != null) {
2851            return PackageParser.generatePermissionInfo(bp.perm, flags);
2852        }
2853        PermissionInfo pi = new PermissionInfo();
2854        pi.name = bp.name;
2855        pi.packageName = bp.sourcePackage;
2856        pi.nonLocalizedLabel = bp.name;
2857        pi.protectionLevel = bp.protectionLevel;
2858        return pi;
2859    }
2860
2861    @Override
2862    public PermissionInfo getPermissionInfo(String name, int flags) {
2863        // reader
2864        synchronized (mPackages) {
2865            final BasePermission p = mSettings.mPermissions.get(name);
2866            if (p != null) {
2867                return generatePermissionInfo(p, flags);
2868            }
2869            return null;
2870        }
2871    }
2872
2873    @Override
2874    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2875        // reader
2876        synchronized (mPackages) {
2877            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2878            for (BasePermission p : mSettings.mPermissions.values()) {
2879                if (group == null) {
2880                    if (p.perm == null || p.perm.info.group == null) {
2881                        out.add(generatePermissionInfo(p, flags));
2882                    }
2883                } else {
2884                    if (p.perm != null && group.equals(p.perm.info.group)) {
2885                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2886                    }
2887                }
2888            }
2889
2890            if (out.size() > 0) {
2891                return out;
2892            }
2893            return mPermissionGroups.containsKey(group) ? out : null;
2894        }
2895    }
2896
2897    @Override
2898    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2899        // reader
2900        synchronized (mPackages) {
2901            return PackageParser.generatePermissionGroupInfo(
2902                    mPermissionGroups.get(name), flags);
2903        }
2904    }
2905
2906    @Override
2907    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2908        // reader
2909        synchronized (mPackages) {
2910            final int N = mPermissionGroups.size();
2911            ArrayList<PermissionGroupInfo> out
2912                    = new ArrayList<PermissionGroupInfo>(N);
2913            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2914                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2915            }
2916            return out;
2917        }
2918    }
2919
2920    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2921            int userId) {
2922        if (!sUserManager.exists(userId)) return null;
2923        PackageSetting ps = mSettings.mPackages.get(packageName);
2924        if (ps != null) {
2925            if (ps.pkg == null) {
2926                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2927                        flags, userId);
2928                if (pInfo != null) {
2929                    return pInfo.applicationInfo;
2930                }
2931                return null;
2932            }
2933            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2934                    ps.readUserState(userId), userId);
2935        }
2936        return null;
2937    }
2938
2939    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2940            int userId) {
2941        if (!sUserManager.exists(userId)) return null;
2942        PackageSetting ps = mSettings.mPackages.get(packageName);
2943        if (ps != null) {
2944            PackageParser.Package pkg = ps.pkg;
2945            if (pkg == null) {
2946                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2947                    return null;
2948                }
2949                // Only data remains, so we aren't worried about code paths
2950                pkg = new PackageParser.Package(packageName);
2951                pkg.applicationInfo.packageName = packageName;
2952                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2953                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2954                pkg.applicationInfo.uid = ps.appId;
2955                pkg.applicationInfo.initForUser(userId);
2956                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2957                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2958            }
2959            return generatePackageInfo(pkg, flags, userId);
2960        }
2961        return null;
2962    }
2963
2964    @Override
2965    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2966        if (!sUserManager.exists(userId)) return null;
2967        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2968        // writer
2969        synchronized (mPackages) {
2970            PackageParser.Package p = mPackages.get(packageName);
2971            if (DEBUG_PACKAGE_INFO) Log.v(
2972                    TAG, "getApplicationInfo " + packageName
2973                    + ": " + p);
2974            if (p != null) {
2975                PackageSetting ps = mSettings.mPackages.get(packageName);
2976                if (ps == null) return null;
2977                // Note: isEnabledLP() does not apply here - always return info
2978                return PackageParser.generateApplicationInfo(
2979                        p, flags, ps.readUserState(userId), userId);
2980            }
2981            if ("android".equals(packageName)||"system".equals(packageName)) {
2982                return mAndroidApplication;
2983            }
2984            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2985                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2986            }
2987        }
2988        return null;
2989    }
2990
2991    @Override
2992    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2993            final IPackageDataObserver observer) {
2994        mContext.enforceCallingOrSelfPermission(
2995                android.Manifest.permission.CLEAR_APP_CACHE, null);
2996        // Queue up an async operation since clearing cache may take a little while.
2997        mHandler.post(new Runnable() {
2998            public void run() {
2999                mHandler.removeCallbacks(this);
3000                int retCode = -1;
3001                synchronized (mInstallLock) {
3002                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3003                    if (retCode < 0) {
3004                        Slog.w(TAG, "Couldn't clear application caches");
3005                    }
3006                }
3007                if (observer != null) {
3008                    try {
3009                        observer.onRemoveCompleted(null, (retCode >= 0));
3010                    } catch (RemoteException e) {
3011                        Slog.w(TAG, "RemoveException when invoking call back");
3012                    }
3013                }
3014            }
3015        });
3016    }
3017
3018    @Override
3019    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3020            final IntentSender pi) {
3021        mContext.enforceCallingOrSelfPermission(
3022                android.Manifest.permission.CLEAR_APP_CACHE, null);
3023        // Queue up an async operation since clearing cache may take a little while.
3024        mHandler.post(new Runnable() {
3025            public void run() {
3026                mHandler.removeCallbacks(this);
3027                int retCode = -1;
3028                synchronized (mInstallLock) {
3029                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3030                    if (retCode < 0) {
3031                        Slog.w(TAG, "Couldn't clear application caches");
3032                    }
3033                }
3034                if(pi != null) {
3035                    try {
3036                        // Callback via pending intent
3037                        int code = (retCode >= 0) ? 1 : 0;
3038                        pi.sendIntent(null, code, null,
3039                                null, null);
3040                    } catch (SendIntentException e1) {
3041                        Slog.i(TAG, "Failed to send pending intent");
3042                    }
3043                }
3044            }
3045        });
3046    }
3047
3048    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3049        synchronized (mInstallLock) {
3050            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3051                throw new IOException("Failed to free enough space");
3052            }
3053        }
3054    }
3055
3056    /**
3057     * Augment the given flags depending on current user running state. This is
3058     * purposefully done before acquiring {@link #mPackages} lock.
3059     */
3060    private int augmentFlagsForUser(int flags, int userId) {
3061        final IActivityManager am = ActivityManagerNative.getDefault();
3062        if (am == null) {
3063            // We must be early in boot, so the best we can do is assume the
3064            // user is fully running.
3065            return flags;
3066        }
3067        final long token = Binder.clearCallingIdentity();
3068        try {
3069            if (am.isUserRunning(userId, ActivityManager.FLAG_WITH_AMNESIA)) {
3070                flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA;
3071            }
3072        } catch (RemoteException e) {
3073            throw e.rethrowAsRuntimeException();
3074        } finally {
3075            Binder.restoreCallingIdentity(token);
3076        }
3077        return flags;
3078    }
3079
3080    @Override
3081    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3082        if (!sUserManager.exists(userId)) return null;
3083        flags = augmentFlagsForUser(flags, userId);
3084        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3085        synchronized (mPackages) {
3086            PackageParser.Activity a = mActivities.mActivities.get(component);
3087
3088            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3089            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3090                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3091                if (ps == null) return null;
3092                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3093                        userId);
3094            }
3095            if (mResolveComponentName.equals(component)) {
3096                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3097                        new PackageUserState(), userId);
3098            }
3099        }
3100        return null;
3101    }
3102
3103    @Override
3104    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3105            String resolvedType) {
3106        synchronized (mPackages) {
3107            if (component.equals(mResolveComponentName)) {
3108                // The resolver supports EVERYTHING!
3109                return true;
3110            }
3111            PackageParser.Activity a = mActivities.mActivities.get(component);
3112            if (a == null) {
3113                return false;
3114            }
3115            for (int i=0; i<a.intents.size(); i++) {
3116                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3117                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3118                    return true;
3119                }
3120            }
3121            return false;
3122        }
3123    }
3124
3125    @Override
3126    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3127        if (!sUserManager.exists(userId)) return null;
3128        flags = augmentFlagsForUser(flags, userId);
3129        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3130        synchronized (mPackages) {
3131            PackageParser.Activity a = mReceivers.mActivities.get(component);
3132            if (DEBUG_PACKAGE_INFO) Log.v(
3133                TAG, "getReceiverInfo " + component + ": " + a);
3134            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3135                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3136                if (ps == null) return null;
3137                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3138                        userId);
3139            }
3140        }
3141        return null;
3142    }
3143
3144    @Override
3145    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3146        if (!sUserManager.exists(userId)) return null;
3147        flags = augmentFlagsForUser(flags, userId);
3148        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3149        synchronized (mPackages) {
3150            PackageParser.Service s = mServices.mServices.get(component);
3151            if (DEBUG_PACKAGE_INFO) Log.v(
3152                TAG, "getServiceInfo " + component + ": " + s);
3153            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3154                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3155                if (ps == null) return null;
3156                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3157                        userId);
3158            }
3159        }
3160        return null;
3161    }
3162
3163    @Override
3164    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3165        if (!sUserManager.exists(userId)) return null;
3166        flags = augmentFlagsForUser(flags, userId);
3167        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3168        synchronized (mPackages) {
3169            PackageParser.Provider p = mProviders.mProviders.get(component);
3170            if (DEBUG_PACKAGE_INFO) Log.v(
3171                TAG, "getProviderInfo " + component + ": " + p);
3172            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3173                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3174                if (ps == null) return null;
3175                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3176                        userId);
3177            }
3178        }
3179        return null;
3180    }
3181
3182    @Override
3183    public String[] getSystemSharedLibraryNames() {
3184        Set<String> libSet;
3185        synchronized (mPackages) {
3186            libSet = mSharedLibraries.keySet();
3187            int size = libSet.size();
3188            if (size > 0) {
3189                String[] libs = new String[size];
3190                libSet.toArray(libs);
3191                return libs;
3192            }
3193        }
3194        return null;
3195    }
3196
3197    /**
3198     * @hide
3199     */
3200    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3201        synchronized (mPackages) {
3202            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3203            if (lib != null && lib.apk != null) {
3204                return mPackages.get(lib.apk);
3205            }
3206        }
3207        return null;
3208    }
3209
3210    @Override
3211    public FeatureInfo[] getSystemAvailableFeatures() {
3212        Collection<FeatureInfo> featSet;
3213        synchronized (mPackages) {
3214            featSet = mAvailableFeatures.values();
3215            int size = featSet.size();
3216            if (size > 0) {
3217                FeatureInfo[] features = new FeatureInfo[size+1];
3218                featSet.toArray(features);
3219                FeatureInfo fi = new FeatureInfo();
3220                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3221                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3222                features[size] = fi;
3223                return features;
3224            }
3225        }
3226        return null;
3227    }
3228
3229    @Override
3230    public boolean hasSystemFeature(String name) {
3231        synchronized (mPackages) {
3232            return mAvailableFeatures.containsKey(name);
3233        }
3234    }
3235
3236    private void checkValidCaller(int uid, int userId) {
3237        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3238            return;
3239
3240        throw new SecurityException("Caller uid=" + uid
3241                + " is not privileged to communicate with user=" + userId);
3242    }
3243
3244    @Override
3245    public int checkPermission(String permName, String pkgName, int userId) {
3246        if (!sUserManager.exists(userId)) {
3247            return PackageManager.PERMISSION_DENIED;
3248        }
3249
3250        synchronized (mPackages) {
3251            final PackageParser.Package p = mPackages.get(pkgName);
3252            if (p != null && p.mExtras != null) {
3253                final PackageSetting ps = (PackageSetting) p.mExtras;
3254                final PermissionsState permissionsState = ps.getPermissionsState();
3255                if (permissionsState.hasPermission(permName, userId)) {
3256                    return PackageManager.PERMISSION_GRANTED;
3257                }
3258                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3259                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3260                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3261                    return PackageManager.PERMISSION_GRANTED;
3262                }
3263            }
3264        }
3265
3266        return PackageManager.PERMISSION_DENIED;
3267    }
3268
3269    @Override
3270    public int checkUidPermission(String permName, int uid) {
3271        final int userId = UserHandle.getUserId(uid);
3272
3273        if (!sUserManager.exists(userId)) {
3274            return PackageManager.PERMISSION_DENIED;
3275        }
3276
3277        synchronized (mPackages) {
3278            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3279            if (obj != null) {
3280                final SettingBase ps = (SettingBase) obj;
3281                final PermissionsState permissionsState = ps.getPermissionsState();
3282                if (permissionsState.hasPermission(permName, userId)) {
3283                    return PackageManager.PERMISSION_GRANTED;
3284                }
3285                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3286                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3287                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3288                    return PackageManager.PERMISSION_GRANTED;
3289                }
3290            } else {
3291                ArraySet<String> perms = mSystemPermissions.get(uid);
3292                if (perms != null) {
3293                    if (perms.contains(permName)) {
3294                        return PackageManager.PERMISSION_GRANTED;
3295                    }
3296                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3297                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3298                        return PackageManager.PERMISSION_GRANTED;
3299                    }
3300                }
3301            }
3302        }
3303
3304        return PackageManager.PERMISSION_DENIED;
3305    }
3306
3307    @Override
3308    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3309        if (UserHandle.getCallingUserId() != userId) {
3310            mContext.enforceCallingPermission(
3311                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3312                    "isPermissionRevokedByPolicy for user " + userId);
3313        }
3314
3315        if (checkPermission(permission, packageName, userId)
3316                == PackageManager.PERMISSION_GRANTED) {
3317            return false;
3318        }
3319
3320        final long identity = Binder.clearCallingIdentity();
3321        try {
3322            final int flags = getPermissionFlags(permission, packageName, userId);
3323            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3324        } finally {
3325            Binder.restoreCallingIdentity(identity);
3326        }
3327    }
3328
3329    @Override
3330    public String getPermissionControllerPackageName() {
3331        synchronized (mPackages) {
3332            return mRequiredInstallerPackage;
3333        }
3334    }
3335
3336    /**
3337     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3338     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3339     * @param checkShell TODO(yamasani):
3340     * @param message the message to log on security exception
3341     */
3342    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3343            boolean checkShell, String message) {
3344        if (userId < 0) {
3345            throw new IllegalArgumentException("Invalid userId " + userId);
3346        }
3347        if (checkShell) {
3348            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3349        }
3350        if (userId == UserHandle.getUserId(callingUid)) return;
3351        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3352            if (requireFullPermission) {
3353                mContext.enforceCallingOrSelfPermission(
3354                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3355            } else {
3356                try {
3357                    mContext.enforceCallingOrSelfPermission(
3358                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3359                } catch (SecurityException se) {
3360                    mContext.enforceCallingOrSelfPermission(
3361                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3362                }
3363            }
3364        }
3365    }
3366
3367    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3368        if (callingUid == Process.SHELL_UID) {
3369            if (userHandle >= 0
3370                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3371                throw new SecurityException("Shell does not have permission to access user "
3372                        + userHandle);
3373            } else if (userHandle < 0) {
3374                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3375                        + Debug.getCallers(3));
3376            }
3377        }
3378    }
3379
3380    private BasePermission findPermissionTreeLP(String permName) {
3381        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3382            if (permName.startsWith(bp.name) &&
3383                    permName.length() > bp.name.length() &&
3384                    permName.charAt(bp.name.length()) == '.') {
3385                return bp;
3386            }
3387        }
3388        return null;
3389    }
3390
3391    private BasePermission checkPermissionTreeLP(String permName) {
3392        if (permName != null) {
3393            BasePermission bp = findPermissionTreeLP(permName);
3394            if (bp != null) {
3395                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3396                    return bp;
3397                }
3398                throw new SecurityException("Calling uid "
3399                        + Binder.getCallingUid()
3400                        + " is not allowed to add to permission tree "
3401                        + bp.name + " owned by uid " + bp.uid);
3402            }
3403        }
3404        throw new SecurityException("No permission tree found for " + permName);
3405    }
3406
3407    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3408        if (s1 == null) {
3409            return s2 == null;
3410        }
3411        if (s2 == null) {
3412            return false;
3413        }
3414        if (s1.getClass() != s2.getClass()) {
3415            return false;
3416        }
3417        return s1.equals(s2);
3418    }
3419
3420    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3421        if (pi1.icon != pi2.icon) return false;
3422        if (pi1.logo != pi2.logo) return false;
3423        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3424        if (!compareStrings(pi1.name, pi2.name)) return false;
3425        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3426        // We'll take care of setting this one.
3427        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3428        // These are not currently stored in settings.
3429        //if (!compareStrings(pi1.group, pi2.group)) return false;
3430        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3431        //if (pi1.labelRes != pi2.labelRes) return false;
3432        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3433        return true;
3434    }
3435
3436    int permissionInfoFootprint(PermissionInfo info) {
3437        int size = info.name.length();
3438        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3439        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3440        return size;
3441    }
3442
3443    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3444        int size = 0;
3445        for (BasePermission perm : mSettings.mPermissions.values()) {
3446            if (perm.uid == tree.uid) {
3447                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3448            }
3449        }
3450        return size;
3451    }
3452
3453    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3454        // We calculate the max size of permissions defined by this uid and throw
3455        // if that plus the size of 'info' would exceed our stated maximum.
3456        if (tree.uid != Process.SYSTEM_UID) {
3457            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3458            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3459                throw new SecurityException("Permission tree size cap exceeded");
3460            }
3461        }
3462    }
3463
3464    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3465        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3466            throw new SecurityException("Label must be specified in permission");
3467        }
3468        BasePermission tree = checkPermissionTreeLP(info.name);
3469        BasePermission bp = mSettings.mPermissions.get(info.name);
3470        boolean added = bp == null;
3471        boolean changed = true;
3472        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3473        if (added) {
3474            enforcePermissionCapLocked(info, tree);
3475            bp = new BasePermission(info.name, tree.sourcePackage,
3476                    BasePermission.TYPE_DYNAMIC);
3477        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3478            throw new SecurityException(
3479                    "Not allowed to modify non-dynamic permission "
3480                    + info.name);
3481        } else {
3482            if (bp.protectionLevel == fixedLevel
3483                    && bp.perm.owner.equals(tree.perm.owner)
3484                    && bp.uid == tree.uid
3485                    && comparePermissionInfos(bp.perm.info, info)) {
3486                changed = false;
3487            }
3488        }
3489        bp.protectionLevel = fixedLevel;
3490        info = new PermissionInfo(info);
3491        info.protectionLevel = fixedLevel;
3492        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3493        bp.perm.info.packageName = tree.perm.info.packageName;
3494        bp.uid = tree.uid;
3495        if (added) {
3496            mSettings.mPermissions.put(info.name, bp);
3497        }
3498        if (changed) {
3499            if (!async) {
3500                mSettings.writeLPr();
3501            } else {
3502                scheduleWriteSettingsLocked();
3503            }
3504        }
3505        return added;
3506    }
3507
3508    @Override
3509    public boolean addPermission(PermissionInfo info) {
3510        synchronized (mPackages) {
3511            return addPermissionLocked(info, false);
3512        }
3513    }
3514
3515    @Override
3516    public boolean addPermissionAsync(PermissionInfo info) {
3517        synchronized (mPackages) {
3518            return addPermissionLocked(info, true);
3519        }
3520    }
3521
3522    @Override
3523    public void removePermission(String name) {
3524        synchronized (mPackages) {
3525            checkPermissionTreeLP(name);
3526            BasePermission bp = mSettings.mPermissions.get(name);
3527            if (bp != null) {
3528                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3529                    throw new SecurityException(
3530                            "Not allowed to modify non-dynamic permission "
3531                            + name);
3532                }
3533                mSettings.mPermissions.remove(name);
3534                mSettings.writeLPr();
3535            }
3536        }
3537    }
3538
3539    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3540            BasePermission bp) {
3541        int index = pkg.requestedPermissions.indexOf(bp.name);
3542        if (index == -1) {
3543            throw new SecurityException("Package " + pkg.packageName
3544                    + " has not requested permission " + bp.name);
3545        }
3546        if (!bp.isRuntime() && !bp.isDevelopment()) {
3547            throw new SecurityException("Permission " + bp.name
3548                    + " is not a changeable permission type");
3549        }
3550    }
3551
3552    @Override
3553    public void grantRuntimePermission(String packageName, String name, final int userId) {
3554        if (!sUserManager.exists(userId)) {
3555            Log.e(TAG, "No such user:" + userId);
3556            return;
3557        }
3558
3559        mContext.enforceCallingOrSelfPermission(
3560                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3561                "grantRuntimePermission");
3562
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3564                "grantRuntimePermission");
3565
3566        final int uid;
3567        final SettingBase sb;
3568
3569        synchronized (mPackages) {
3570            final PackageParser.Package pkg = mPackages.get(packageName);
3571            if (pkg == null) {
3572                throw new IllegalArgumentException("Unknown package: " + packageName);
3573            }
3574
3575            final BasePermission bp = mSettings.mPermissions.get(name);
3576            if (bp == null) {
3577                throw new IllegalArgumentException("Unknown permission: " + name);
3578            }
3579
3580            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3581
3582            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3583            sb = (SettingBase) pkg.mExtras;
3584            if (sb == null) {
3585                throw new IllegalArgumentException("Unknown package: " + packageName);
3586            }
3587
3588            final PermissionsState permissionsState = sb.getPermissionsState();
3589
3590            final int flags = permissionsState.getPermissionFlags(name, userId);
3591            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3592                throw new SecurityException("Cannot grant system fixed permission: "
3593                        + name + " for package: " + packageName);
3594            }
3595
3596            if (bp.isDevelopment()) {
3597                // Development permissions must be handled specially, since they are not
3598                // normal runtime permissions.  For now they apply to all users.
3599                if (permissionsState.grantInstallPermission(bp) !=
3600                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3601                    scheduleWriteSettingsLocked();
3602                }
3603                return;
3604            }
3605
3606            final int result = permissionsState.grantRuntimePermission(bp, userId);
3607            switch (result) {
3608                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3609                    return;
3610                }
3611
3612                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3613                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3614                    mHandler.post(new Runnable() {
3615                        @Override
3616                        public void run() {
3617                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3618                        }
3619                    });
3620                }
3621                break;
3622            }
3623
3624            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3625
3626            // Not critical if that is lost - app has to request again.
3627            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3628        }
3629
3630        // Only need to do this if user is initialized. Otherwise it's a new user
3631        // and there are no processes running as the user yet and there's no need
3632        // to make an expensive call to remount processes for the changed permissions.
3633        if (READ_EXTERNAL_STORAGE.equals(name)
3634                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3635            final long token = Binder.clearCallingIdentity();
3636            try {
3637                if (sUserManager.isInitialized(userId)) {
3638                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3639                            MountServiceInternal.class);
3640                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3641                }
3642            } finally {
3643                Binder.restoreCallingIdentity(token);
3644            }
3645        }
3646    }
3647
3648    @Override
3649    public void revokeRuntimePermission(String packageName, String name, int userId) {
3650        if (!sUserManager.exists(userId)) {
3651            Log.e(TAG, "No such user:" + userId);
3652            return;
3653        }
3654
3655        mContext.enforceCallingOrSelfPermission(
3656                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3657                "revokeRuntimePermission");
3658
3659        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3660                "revokeRuntimePermission");
3661
3662        final int appId;
3663
3664        synchronized (mPackages) {
3665            final PackageParser.Package pkg = mPackages.get(packageName);
3666            if (pkg == null) {
3667                throw new IllegalArgumentException("Unknown package: " + packageName);
3668            }
3669
3670            final BasePermission bp = mSettings.mPermissions.get(name);
3671            if (bp == null) {
3672                throw new IllegalArgumentException("Unknown permission: " + name);
3673            }
3674
3675            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3676
3677            SettingBase sb = (SettingBase) pkg.mExtras;
3678            if (sb == null) {
3679                throw new IllegalArgumentException("Unknown package: " + packageName);
3680            }
3681
3682            final PermissionsState permissionsState = sb.getPermissionsState();
3683
3684            final int flags = permissionsState.getPermissionFlags(name, userId);
3685            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3686                throw new SecurityException("Cannot revoke system fixed permission: "
3687                        + name + " for package: " + packageName);
3688            }
3689
3690            if (bp.isDevelopment()) {
3691                // Development permissions must be handled specially, since they are not
3692                // normal runtime permissions.  For now they apply to all users.
3693                if (permissionsState.revokeInstallPermission(bp) !=
3694                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3695                    scheduleWriteSettingsLocked();
3696                }
3697                return;
3698            }
3699
3700            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3701                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3702                return;
3703            }
3704
3705            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3706
3707            // Critical, after this call app should never have the permission.
3708            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3709
3710            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3711        }
3712
3713        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3714    }
3715
3716    @Override
3717    public void resetRuntimePermissions() {
3718        mContext.enforceCallingOrSelfPermission(
3719                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3720                "revokeRuntimePermission");
3721
3722        int callingUid = Binder.getCallingUid();
3723        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3724            mContext.enforceCallingOrSelfPermission(
3725                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3726                    "resetRuntimePermissions");
3727        }
3728
3729        synchronized (mPackages) {
3730            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3731            for (int userId : UserManagerService.getInstance().getUserIds()) {
3732                final int packageCount = mPackages.size();
3733                for (int i = 0; i < packageCount; i++) {
3734                    PackageParser.Package pkg = mPackages.valueAt(i);
3735                    if (!(pkg.mExtras instanceof PackageSetting)) {
3736                        continue;
3737                    }
3738                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3739                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3740                }
3741            }
3742        }
3743    }
3744
3745    @Override
3746    public int getPermissionFlags(String name, String packageName, int userId) {
3747        if (!sUserManager.exists(userId)) {
3748            return 0;
3749        }
3750
3751        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3752
3753        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3754                "getPermissionFlags");
3755
3756        synchronized (mPackages) {
3757            final PackageParser.Package pkg = mPackages.get(packageName);
3758            if (pkg == null) {
3759                throw new IllegalArgumentException("Unknown package: " + packageName);
3760            }
3761
3762            final BasePermission bp = mSettings.mPermissions.get(name);
3763            if (bp == null) {
3764                throw new IllegalArgumentException("Unknown permission: " + name);
3765            }
3766
3767            SettingBase sb = (SettingBase) pkg.mExtras;
3768            if (sb == null) {
3769                throw new IllegalArgumentException("Unknown package: " + packageName);
3770            }
3771
3772            PermissionsState permissionsState = sb.getPermissionsState();
3773            return permissionsState.getPermissionFlags(name, userId);
3774        }
3775    }
3776
3777    @Override
3778    public void updatePermissionFlags(String name, String packageName, int flagMask,
3779            int flagValues, int userId) {
3780        if (!sUserManager.exists(userId)) {
3781            return;
3782        }
3783
3784        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3785
3786        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3787                "updatePermissionFlags");
3788
3789        // Only the system can change these flags and nothing else.
3790        if (getCallingUid() != Process.SYSTEM_UID) {
3791            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3792            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3793            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3794            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3795        }
3796
3797        synchronized (mPackages) {
3798            final PackageParser.Package pkg = mPackages.get(packageName);
3799            if (pkg == null) {
3800                throw new IllegalArgumentException("Unknown package: " + packageName);
3801            }
3802
3803            final BasePermission bp = mSettings.mPermissions.get(name);
3804            if (bp == null) {
3805                throw new IllegalArgumentException("Unknown permission: " + name);
3806            }
3807
3808            SettingBase sb = (SettingBase) pkg.mExtras;
3809            if (sb == null) {
3810                throw new IllegalArgumentException("Unknown package: " + packageName);
3811            }
3812
3813            PermissionsState permissionsState = sb.getPermissionsState();
3814
3815            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3816
3817            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3818                // Install and runtime permissions are stored in different places,
3819                // so figure out what permission changed and persist the change.
3820                if (permissionsState.getInstallPermissionState(name) != null) {
3821                    scheduleWriteSettingsLocked();
3822                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3823                        || hadState) {
3824                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3825                }
3826            }
3827        }
3828    }
3829
3830    /**
3831     * Update the permission flags for all packages and runtime permissions of a user in order
3832     * to allow device or profile owner to remove POLICY_FIXED.
3833     */
3834    @Override
3835    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3836        if (!sUserManager.exists(userId)) {
3837            return;
3838        }
3839
3840        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3841
3842        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3843                "updatePermissionFlagsForAllApps");
3844
3845        // Only the system can change system fixed flags.
3846        if (getCallingUid() != Process.SYSTEM_UID) {
3847            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3848            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3849        }
3850
3851        synchronized (mPackages) {
3852            boolean changed = false;
3853            final int packageCount = mPackages.size();
3854            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3855                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3856                SettingBase sb = (SettingBase) pkg.mExtras;
3857                if (sb == null) {
3858                    continue;
3859                }
3860                PermissionsState permissionsState = sb.getPermissionsState();
3861                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3862                        userId, flagMask, flagValues);
3863            }
3864            if (changed) {
3865                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3866            }
3867        }
3868    }
3869
3870    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3871        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3872                != PackageManager.PERMISSION_GRANTED
3873            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3874                != PackageManager.PERMISSION_GRANTED) {
3875            throw new SecurityException(message + " requires "
3876                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3877                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3878        }
3879    }
3880
3881    @Override
3882    public boolean shouldShowRequestPermissionRationale(String permissionName,
3883            String packageName, int userId) {
3884        if (UserHandle.getCallingUserId() != userId) {
3885            mContext.enforceCallingPermission(
3886                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3887                    "canShowRequestPermissionRationale for user " + userId);
3888        }
3889
3890        final int uid = getPackageUid(packageName, userId);
3891        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3892            return false;
3893        }
3894
3895        if (checkPermission(permissionName, packageName, userId)
3896                == PackageManager.PERMISSION_GRANTED) {
3897            return false;
3898        }
3899
3900        final int flags;
3901
3902        final long identity = Binder.clearCallingIdentity();
3903        try {
3904            flags = getPermissionFlags(permissionName,
3905                    packageName, userId);
3906        } finally {
3907            Binder.restoreCallingIdentity(identity);
3908        }
3909
3910        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3911                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3912                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3913
3914        if ((flags & fixedFlags) != 0) {
3915            return false;
3916        }
3917
3918        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3919    }
3920
3921    @Override
3922    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3923        mContext.enforceCallingOrSelfPermission(
3924                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3925                "addOnPermissionsChangeListener");
3926
3927        synchronized (mPackages) {
3928            mOnPermissionChangeListeners.addListenerLocked(listener);
3929        }
3930    }
3931
3932    @Override
3933    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3934        synchronized (mPackages) {
3935            mOnPermissionChangeListeners.removeListenerLocked(listener);
3936        }
3937    }
3938
3939    @Override
3940    public boolean isProtectedBroadcast(String actionName) {
3941        synchronized (mPackages) {
3942            return mProtectedBroadcasts.contains(actionName);
3943        }
3944    }
3945
3946    @Override
3947    public int checkSignatures(String pkg1, String pkg2) {
3948        synchronized (mPackages) {
3949            final PackageParser.Package p1 = mPackages.get(pkg1);
3950            final PackageParser.Package p2 = mPackages.get(pkg2);
3951            if (p1 == null || p1.mExtras == null
3952                    || p2 == null || p2.mExtras == null) {
3953                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3954            }
3955            return compareSignatures(p1.mSignatures, p2.mSignatures);
3956        }
3957    }
3958
3959    @Override
3960    public int checkUidSignatures(int uid1, int uid2) {
3961        // Map to base uids.
3962        uid1 = UserHandle.getAppId(uid1);
3963        uid2 = UserHandle.getAppId(uid2);
3964        // reader
3965        synchronized (mPackages) {
3966            Signature[] s1;
3967            Signature[] s2;
3968            Object obj = mSettings.getUserIdLPr(uid1);
3969            if (obj != null) {
3970                if (obj instanceof SharedUserSetting) {
3971                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3972                } else if (obj instanceof PackageSetting) {
3973                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3974                } else {
3975                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3976                }
3977            } else {
3978                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3979            }
3980            obj = mSettings.getUserIdLPr(uid2);
3981            if (obj != null) {
3982                if (obj instanceof SharedUserSetting) {
3983                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3984                } else if (obj instanceof PackageSetting) {
3985                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3986                } else {
3987                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3988                }
3989            } else {
3990                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3991            }
3992            return compareSignatures(s1, s2);
3993        }
3994    }
3995
3996    private void killUid(int appId, int userId, String reason) {
3997        final long identity = Binder.clearCallingIdentity();
3998        try {
3999            IActivityManager am = ActivityManagerNative.getDefault();
4000            if (am != null) {
4001                try {
4002                    am.killUid(appId, userId, reason);
4003                } catch (RemoteException e) {
4004                    /* ignore - same process */
4005                }
4006            }
4007        } finally {
4008            Binder.restoreCallingIdentity(identity);
4009        }
4010    }
4011
4012    /**
4013     * Compares two sets of signatures. Returns:
4014     * <br />
4015     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4016     * <br />
4017     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4018     * <br />
4019     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4020     * <br />
4021     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4022     * <br />
4023     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4024     */
4025    static int compareSignatures(Signature[] s1, Signature[] s2) {
4026        if (s1 == null) {
4027            return s2 == null
4028                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4029                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4030        }
4031
4032        if (s2 == null) {
4033            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4034        }
4035
4036        if (s1.length != s2.length) {
4037            return PackageManager.SIGNATURE_NO_MATCH;
4038        }
4039
4040        // Since both signature sets are of size 1, we can compare without HashSets.
4041        if (s1.length == 1) {
4042            return s1[0].equals(s2[0]) ?
4043                    PackageManager.SIGNATURE_MATCH :
4044                    PackageManager.SIGNATURE_NO_MATCH;
4045        }
4046
4047        ArraySet<Signature> set1 = new ArraySet<Signature>();
4048        for (Signature sig : s1) {
4049            set1.add(sig);
4050        }
4051        ArraySet<Signature> set2 = new ArraySet<Signature>();
4052        for (Signature sig : s2) {
4053            set2.add(sig);
4054        }
4055        // Make sure s2 contains all signatures in s1.
4056        if (set1.equals(set2)) {
4057            return PackageManager.SIGNATURE_MATCH;
4058        }
4059        return PackageManager.SIGNATURE_NO_MATCH;
4060    }
4061
4062    /**
4063     * If the database version for this type of package (internal storage or
4064     * external storage) is less than the version where package signatures
4065     * were updated, return true.
4066     */
4067    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4068        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4069        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4070    }
4071
4072    /**
4073     * Used for backward compatibility to make sure any packages with
4074     * certificate chains get upgraded to the new style. {@code existingSigs}
4075     * will be in the old format (since they were stored on disk from before the
4076     * system upgrade) and {@code scannedSigs} will be in the newer format.
4077     */
4078    private int compareSignaturesCompat(PackageSignatures existingSigs,
4079            PackageParser.Package scannedPkg) {
4080        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4081            return PackageManager.SIGNATURE_NO_MATCH;
4082        }
4083
4084        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4085        for (Signature sig : existingSigs.mSignatures) {
4086            existingSet.add(sig);
4087        }
4088        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4089        for (Signature sig : scannedPkg.mSignatures) {
4090            try {
4091                Signature[] chainSignatures = sig.getChainSignatures();
4092                for (Signature chainSig : chainSignatures) {
4093                    scannedCompatSet.add(chainSig);
4094                }
4095            } catch (CertificateEncodingException e) {
4096                scannedCompatSet.add(sig);
4097            }
4098        }
4099        /*
4100         * Make sure the expanded scanned set contains all signatures in the
4101         * existing one.
4102         */
4103        if (scannedCompatSet.equals(existingSet)) {
4104            // Migrate the old signatures to the new scheme.
4105            existingSigs.assignSignatures(scannedPkg.mSignatures);
4106            // The new KeySets will be re-added later in the scanning process.
4107            synchronized (mPackages) {
4108                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4109            }
4110            return PackageManager.SIGNATURE_MATCH;
4111        }
4112        return PackageManager.SIGNATURE_NO_MATCH;
4113    }
4114
4115    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4116        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4117        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4118    }
4119
4120    private int compareSignaturesRecover(PackageSignatures existingSigs,
4121            PackageParser.Package scannedPkg) {
4122        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4123            return PackageManager.SIGNATURE_NO_MATCH;
4124        }
4125
4126        String msg = null;
4127        try {
4128            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4129                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4130                        + scannedPkg.packageName);
4131                return PackageManager.SIGNATURE_MATCH;
4132            }
4133        } catch (CertificateException e) {
4134            msg = e.getMessage();
4135        }
4136
4137        logCriticalInfo(Log.INFO,
4138                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4139        return PackageManager.SIGNATURE_NO_MATCH;
4140    }
4141
4142    @Override
4143    public String[] getPackagesForUid(int uid) {
4144        uid = UserHandle.getAppId(uid);
4145        // reader
4146        synchronized (mPackages) {
4147            Object obj = mSettings.getUserIdLPr(uid);
4148            if (obj instanceof SharedUserSetting) {
4149                final SharedUserSetting sus = (SharedUserSetting) obj;
4150                final int N = sus.packages.size();
4151                final String[] res = new String[N];
4152                final Iterator<PackageSetting> it = sus.packages.iterator();
4153                int i = 0;
4154                while (it.hasNext()) {
4155                    res[i++] = it.next().name;
4156                }
4157                return res;
4158            } else if (obj instanceof PackageSetting) {
4159                final PackageSetting ps = (PackageSetting) obj;
4160                return new String[] { ps.name };
4161            }
4162        }
4163        return null;
4164    }
4165
4166    @Override
4167    public String getNameForUid(int uid) {
4168        // reader
4169        synchronized (mPackages) {
4170            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4171            if (obj instanceof SharedUserSetting) {
4172                final SharedUserSetting sus = (SharedUserSetting) obj;
4173                return sus.name + ":" + sus.userId;
4174            } else if (obj instanceof PackageSetting) {
4175                final PackageSetting ps = (PackageSetting) obj;
4176                return ps.name;
4177            }
4178        }
4179        return null;
4180    }
4181
4182    @Override
4183    public int getUidForSharedUser(String sharedUserName) {
4184        if(sharedUserName == null) {
4185            return -1;
4186        }
4187        // reader
4188        synchronized (mPackages) {
4189            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4190            if (suid == null) {
4191                return -1;
4192            }
4193            return suid.userId;
4194        }
4195    }
4196
4197    @Override
4198    public int getFlagsForUid(int uid) {
4199        synchronized (mPackages) {
4200            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4201            if (obj instanceof SharedUserSetting) {
4202                final SharedUserSetting sus = (SharedUserSetting) obj;
4203                return sus.pkgFlags;
4204            } else if (obj instanceof PackageSetting) {
4205                final PackageSetting ps = (PackageSetting) obj;
4206                return ps.pkgFlags;
4207            }
4208        }
4209        return 0;
4210    }
4211
4212    @Override
4213    public int getPrivateFlagsForUid(int uid) {
4214        synchronized (mPackages) {
4215            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4216            if (obj instanceof SharedUserSetting) {
4217                final SharedUserSetting sus = (SharedUserSetting) obj;
4218                return sus.pkgPrivateFlags;
4219            } else if (obj instanceof PackageSetting) {
4220                final PackageSetting ps = (PackageSetting) obj;
4221                return ps.pkgPrivateFlags;
4222            }
4223        }
4224        return 0;
4225    }
4226
4227    @Override
4228    public boolean isUidPrivileged(int uid) {
4229        uid = UserHandle.getAppId(uid);
4230        // reader
4231        synchronized (mPackages) {
4232            Object obj = mSettings.getUserIdLPr(uid);
4233            if (obj instanceof SharedUserSetting) {
4234                final SharedUserSetting sus = (SharedUserSetting) obj;
4235                final Iterator<PackageSetting> it = sus.packages.iterator();
4236                while (it.hasNext()) {
4237                    if (it.next().isPrivileged()) {
4238                        return true;
4239                    }
4240                }
4241            } else if (obj instanceof PackageSetting) {
4242                final PackageSetting ps = (PackageSetting) obj;
4243                return ps.isPrivileged();
4244            }
4245        }
4246        return false;
4247    }
4248
4249    @Override
4250    public String[] getAppOpPermissionPackages(String permissionName) {
4251        synchronized (mPackages) {
4252            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4253            if (pkgs == null) {
4254                return null;
4255            }
4256            return pkgs.toArray(new String[pkgs.size()]);
4257        }
4258    }
4259
4260    @Override
4261    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4262            int flags, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        flags = augmentFlagsForUser(flags, userId);
4265        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4266        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4267        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4268    }
4269
4270    @Override
4271    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4272            IntentFilter filter, int match, ComponentName activity) {
4273        final int userId = UserHandle.getCallingUserId();
4274        if (DEBUG_PREFERRED) {
4275            Log.v(TAG, "setLastChosenActivity intent=" + intent
4276                + " resolvedType=" + resolvedType
4277                + " flags=" + flags
4278                + " filter=" + filter
4279                + " match=" + match
4280                + " activity=" + activity);
4281            filter.dump(new PrintStreamPrinter(System.out), "    ");
4282        }
4283        intent.setComponent(null);
4284        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4285        // Find any earlier preferred or last chosen entries and nuke them
4286        findPreferredActivity(intent, resolvedType,
4287                flags, query, 0, false, true, false, userId);
4288        // Add the new activity as the last chosen for this filter
4289        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4290                "Setting last chosen");
4291    }
4292
4293    @Override
4294    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4295        final int userId = UserHandle.getCallingUserId();
4296        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4297        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4298        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4299                false, false, false, userId);
4300    }
4301
4302    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4303            int flags, List<ResolveInfo> query, int userId) {
4304        if (query != null) {
4305            final int N = query.size();
4306            if (N == 1) {
4307                return query.get(0);
4308            } else if (N > 1) {
4309                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4310                // If there is more than one activity with the same priority,
4311                // then let the user decide between them.
4312                ResolveInfo r0 = query.get(0);
4313                ResolveInfo r1 = query.get(1);
4314                if (DEBUG_INTENT_MATCHING || debug) {
4315                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4316                            + r1.activityInfo.name + "=" + r1.priority);
4317                }
4318                // If the first activity has a higher priority, or a different
4319                // default, then it is always desireable to pick it.
4320                if (r0.priority != r1.priority
4321                        || r0.preferredOrder != r1.preferredOrder
4322                        || r0.isDefault != r1.isDefault) {
4323                    return query.get(0);
4324                }
4325                // If we have saved a preference for a preferred activity for
4326                // this Intent, use that.
4327                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4328                        flags, query, r0.priority, true, false, debug, userId);
4329                if (ri != null) {
4330                    return ri;
4331                }
4332                ri = new ResolveInfo(mResolveInfo);
4333                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4334                ri.activityInfo.applicationInfo = new ApplicationInfo(
4335                        ri.activityInfo.applicationInfo);
4336                if (userId != 0) {
4337                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4338                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4339                }
4340                // Make sure that the resolver is displayable in car mode
4341                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4342                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4343                return ri;
4344            }
4345        }
4346        return null;
4347    }
4348
4349    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4350            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4351        final int N = query.size();
4352        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4353                .get(userId);
4354        // Get the list of persistent preferred activities that handle the intent
4355        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4356        List<PersistentPreferredActivity> pprefs = ppir != null
4357                ? ppir.queryIntent(intent, resolvedType,
4358                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4359                : null;
4360        if (pprefs != null && pprefs.size() > 0) {
4361            final int M = pprefs.size();
4362            for (int i=0; i<M; i++) {
4363                final PersistentPreferredActivity ppa = pprefs.get(i);
4364                if (DEBUG_PREFERRED || debug) {
4365                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4366                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4367                            + "\n  component=" + ppa.mComponent);
4368                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4369                }
4370                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4371                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4372                if (DEBUG_PREFERRED || debug) {
4373                    Slog.v(TAG, "Found persistent preferred activity:");
4374                    if (ai != null) {
4375                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4376                    } else {
4377                        Slog.v(TAG, "  null");
4378                    }
4379                }
4380                if (ai == null) {
4381                    // This previously registered persistent preferred activity
4382                    // component is no longer known. Ignore it and do NOT remove it.
4383                    continue;
4384                }
4385                for (int j=0; j<N; j++) {
4386                    final ResolveInfo ri = query.get(j);
4387                    if (!ri.activityInfo.applicationInfo.packageName
4388                            .equals(ai.applicationInfo.packageName)) {
4389                        continue;
4390                    }
4391                    if (!ri.activityInfo.name.equals(ai.name)) {
4392                        continue;
4393                    }
4394                    //  Found a persistent preference that can handle the intent.
4395                    if (DEBUG_PREFERRED || debug) {
4396                        Slog.v(TAG, "Returning persistent preferred activity: " +
4397                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4398                    }
4399                    return ri;
4400                }
4401            }
4402        }
4403        return null;
4404    }
4405
4406    // TODO: handle preferred activities missing while user has amnesia
4407    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4408            List<ResolveInfo> query, int priority, boolean always,
4409            boolean removeMatches, boolean debug, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        flags = augmentFlagsForUser(flags, userId);
4412        // writer
4413        synchronized (mPackages) {
4414            if (intent.getSelector() != null) {
4415                intent = intent.getSelector();
4416            }
4417            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4418
4419            // Try to find a matching persistent preferred activity.
4420            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4421                    debug, userId);
4422
4423            // If a persistent preferred activity matched, use it.
4424            if (pri != null) {
4425                return pri;
4426            }
4427
4428            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4429            // Get the list of preferred activities that handle the intent
4430            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4431            List<PreferredActivity> prefs = pir != null
4432                    ? pir.queryIntent(intent, resolvedType,
4433                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4434                    : null;
4435            if (prefs != null && prefs.size() > 0) {
4436                boolean changed = false;
4437                try {
4438                    // First figure out how good the original match set is.
4439                    // We will only allow preferred activities that came
4440                    // from the same match quality.
4441                    int match = 0;
4442
4443                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4444
4445                    final int N = query.size();
4446                    for (int j=0; j<N; j++) {
4447                        final ResolveInfo ri = query.get(j);
4448                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4449                                + ": 0x" + Integer.toHexString(match));
4450                        if (ri.match > match) {
4451                            match = ri.match;
4452                        }
4453                    }
4454
4455                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4456                            + Integer.toHexString(match));
4457
4458                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4459                    final int M = prefs.size();
4460                    for (int i=0; i<M; i++) {
4461                        final PreferredActivity pa = prefs.get(i);
4462                        if (DEBUG_PREFERRED || debug) {
4463                            Slog.v(TAG, "Checking PreferredActivity ds="
4464                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4465                                    + "\n  component=" + pa.mPref.mComponent);
4466                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4467                        }
4468                        if (pa.mPref.mMatch != match) {
4469                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4470                                    + Integer.toHexString(pa.mPref.mMatch));
4471                            continue;
4472                        }
4473                        // If it's not an "always" type preferred activity and that's what we're
4474                        // looking for, skip it.
4475                        if (always && !pa.mPref.mAlways) {
4476                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4477                            continue;
4478                        }
4479                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4480                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4481                        if (DEBUG_PREFERRED || debug) {
4482                            Slog.v(TAG, "Found preferred activity:");
4483                            if (ai != null) {
4484                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4485                            } else {
4486                                Slog.v(TAG, "  null");
4487                            }
4488                        }
4489                        if (ai == null) {
4490                            // This previously registered preferred activity
4491                            // component is no longer known.  Most likely an update
4492                            // to the app was installed and in the new version this
4493                            // component no longer exists.  Clean it up by removing
4494                            // it from the preferred activities list, and skip it.
4495                            Slog.w(TAG, "Removing dangling preferred activity: "
4496                                    + pa.mPref.mComponent);
4497                            pir.removeFilter(pa);
4498                            changed = true;
4499                            continue;
4500                        }
4501                        for (int j=0; j<N; j++) {
4502                            final ResolveInfo ri = query.get(j);
4503                            if (!ri.activityInfo.applicationInfo.packageName
4504                                    .equals(ai.applicationInfo.packageName)) {
4505                                continue;
4506                            }
4507                            if (!ri.activityInfo.name.equals(ai.name)) {
4508                                continue;
4509                            }
4510
4511                            if (removeMatches) {
4512                                pir.removeFilter(pa);
4513                                changed = true;
4514                                if (DEBUG_PREFERRED) {
4515                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4516                                }
4517                                break;
4518                            }
4519
4520                            // Okay we found a previously set preferred or last chosen app.
4521                            // If the result set is different from when this
4522                            // was created, we need to clear it and re-ask the
4523                            // user their preference, if we're looking for an "always" type entry.
4524                            if (always && !pa.mPref.sameSet(query)) {
4525                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4526                                        + intent + " type " + resolvedType);
4527                                if (DEBUG_PREFERRED) {
4528                                    Slog.v(TAG, "Removing preferred activity since set changed "
4529                                            + pa.mPref.mComponent);
4530                                }
4531                                pir.removeFilter(pa);
4532                                // Re-add the filter as a "last chosen" entry (!always)
4533                                PreferredActivity lastChosen = new PreferredActivity(
4534                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4535                                pir.addFilter(lastChosen);
4536                                changed = true;
4537                                return null;
4538                            }
4539
4540                            // Yay! Either the set matched or we're looking for the last chosen
4541                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4542                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4543                            return ri;
4544                        }
4545                    }
4546                } finally {
4547                    if (changed) {
4548                        if (DEBUG_PREFERRED) {
4549                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4550                        }
4551                        scheduleWritePackageRestrictionsLocked(userId);
4552                    }
4553                }
4554            }
4555        }
4556        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4557        return null;
4558    }
4559
4560    /*
4561     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4562     */
4563    @Override
4564    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4565            int targetUserId) {
4566        mContext.enforceCallingOrSelfPermission(
4567                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4568        List<CrossProfileIntentFilter> matches =
4569                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4570        if (matches != null) {
4571            int size = matches.size();
4572            for (int i = 0; i < size; i++) {
4573                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4574            }
4575        }
4576        if (hasWebURI(intent)) {
4577            // cross-profile app linking works only towards the parent.
4578            final UserInfo parent = getProfileParent(sourceUserId);
4579            synchronized(mPackages) {
4580                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4581                        intent, resolvedType, 0, sourceUserId, parent.id);
4582                return xpDomainInfo != null;
4583            }
4584        }
4585        return false;
4586    }
4587
4588    private UserInfo getProfileParent(int userId) {
4589        final long identity = Binder.clearCallingIdentity();
4590        try {
4591            return sUserManager.getProfileParent(userId);
4592        } finally {
4593            Binder.restoreCallingIdentity(identity);
4594        }
4595    }
4596
4597    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4598            String resolvedType, int userId) {
4599        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4600        if (resolver != null) {
4601            return resolver.queryIntent(intent, resolvedType, false, userId);
4602        }
4603        return null;
4604    }
4605
4606    @Override
4607    public List<ResolveInfo> queryIntentActivities(Intent intent,
4608            String resolvedType, int flags, int userId) {
4609        if (!sUserManager.exists(userId)) return Collections.emptyList();
4610        flags = augmentFlagsForUser(flags, userId);
4611        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4612        ComponentName comp = intent.getComponent();
4613        if (comp == null) {
4614            if (intent.getSelector() != null) {
4615                intent = intent.getSelector();
4616                comp = intent.getComponent();
4617            }
4618        }
4619
4620        if (comp != null) {
4621            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4622            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4623            if (ai != null) {
4624                final ResolveInfo ri = new ResolveInfo();
4625                ri.activityInfo = ai;
4626                list.add(ri);
4627            }
4628            return list;
4629        }
4630
4631        // reader
4632        synchronized (mPackages) {
4633            final String pkgName = intent.getPackage();
4634            if (pkgName == null) {
4635                List<CrossProfileIntentFilter> matchingFilters =
4636                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4637                // Check for results that need to skip the current profile.
4638                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4639                        resolvedType, flags, userId);
4640                if (xpResolveInfo != null) {
4641                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4642                    result.add(xpResolveInfo);
4643                    return filterIfNotSystemUser(result, userId);
4644                }
4645
4646                // Check for results in the current profile.
4647                List<ResolveInfo> result = mActivities.queryIntent(
4648                        intent, resolvedType, flags, userId);
4649
4650                // Check for cross profile results.
4651                xpResolveInfo = queryCrossProfileIntents(
4652                        matchingFilters, intent, resolvedType, flags, userId);
4653                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4654                    result.add(xpResolveInfo);
4655                    Collections.sort(result, mResolvePrioritySorter);
4656                }
4657                result = filterIfNotSystemUser(result, userId);
4658                if (hasWebURI(intent)) {
4659                    CrossProfileDomainInfo xpDomainInfo = null;
4660                    final UserInfo parent = getProfileParent(userId);
4661                    if (parent != null) {
4662                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4663                                flags, userId, parent.id);
4664                    }
4665                    if (xpDomainInfo != null) {
4666                        if (xpResolveInfo != null) {
4667                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4668                            // in the result.
4669                            result.remove(xpResolveInfo);
4670                        }
4671                        if (result.size() == 0) {
4672                            result.add(xpDomainInfo.resolveInfo);
4673                            return result;
4674                        }
4675                    } else if (result.size() <= 1) {
4676                        return result;
4677                    }
4678                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4679                            xpDomainInfo, userId);
4680                    Collections.sort(result, mResolvePrioritySorter);
4681                }
4682                return result;
4683            }
4684            final PackageParser.Package pkg = mPackages.get(pkgName);
4685            if (pkg != null) {
4686                return filterIfNotSystemUser(
4687                        mActivities.queryIntentForPackage(
4688                                intent, resolvedType, flags, pkg.activities, userId),
4689                        userId);
4690            }
4691            return new ArrayList<ResolveInfo>();
4692        }
4693    }
4694
4695    private static class CrossProfileDomainInfo {
4696        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4697        ResolveInfo resolveInfo;
4698        /* Best domain verification status of the activities found in the other profile */
4699        int bestDomainVerificationStatus;
4700    }
4701
4702    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4703            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4704        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4705                sourceUserId)) {
4706            return null;
4707        }
4708        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4709                resolvedType, flags, parentUserId);
4710
4711        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4712            return null;
4713        }
4714        CrossProfileDomainInfo result = null;
4715        int size = resultTargetUser.size();
4716        for (int i = 0; i < size; i++) {
4717            ResolveInfo riTargetUser = resultTargetUser.get(i);
4718            // Intent filter verification is only for filters that specify a host. So don't return
4719            // those that handle all web uris.
4720            if (riTargetUser.handleAllWebDataURI) {
4721                continue;
4722            }
4723            String packageName = riTargetUser.activityInfo.packageName;
4724            PackageSetting ps = mSettings.mPackages.get(packageName);
4725            if (ps == null) {
4726                continue;
4727            }
4728            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4729            int status = (int)(verificationState >> 32);
4730            if (result == null) {
4731                result = new CrossProfileDomainInfo();
4732                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4733                        sourceUserId, parentUserId);
4734                result.bestDomainVerificationStatus = status;
4735            } else {
4736                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4737                        result.bestDomainVerificationStatus);
4738            }
4739        }
4740        // Don't consider matches with status NEVER across profiles.
4741        if (result != null && result.bestDomainVerificationStatus
4742                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4743            return null;
4744        }
4745        return result;
4746    }
4747
4748    /**
4749     * Verification statuses are ordered from the worse to the best, except for
4750     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4751     */
4752    private int bestDomainVerificationStatus(int status1, int status2) {
4753        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4754            return status2;
4755        }
4756        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4757            return status1;
4758        }
4759        return (int) MathUtils.max(status1, status2);
4760    }
4761
4762    private boolean isUserEnabled(int userId) {
4763        long callingId = Binder.clearCallingIdentity();
4764        try {
4765            UserInfo userInfo = sUserManager.getUserInfo(userId);
4766            return userInfo != null && userInfo.isEnabled();
4767        } finally {
4768            Binder.restoreCallingIdentity(callingId);
4769        }
4770    }
4771
4772    /**
4773     * Filter out activities with systemUserOnly flag set, when current user is not System.
4774     *
4775     * @return filtered list
4776     */
4777    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4778        if (userId == UserHandle.USER_SYSTEM) {
4779            return resolveInfos;
4780        }
4781        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4782            ResolveInfo info = resolveInfos.get(i);
4783            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4784                resolveInfos.remove(i);
4785            }
4786        }
4787        return resolveInfos;
4788    }
4789
4790    private static boolean hasWebURI(Intent intent) {
4791        if (intent.getData() == null) {
4792            return false;
4793        }
4794        final String scheme = intent.getScheme();
4795        if (TextUtils.isEmpty(scheme)) {
4796            return false;
4797        }
4798        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4799    }
4800
4801    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4802            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4803            int userId) {
4804        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4805
4806        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4807            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4808                    candidates.size());
4809        }
4810
4811        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4812        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4813        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4814        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4815        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4816        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4817
4818        synchronized (mPackages) {
4819            final int count = candidates.size();
4820            // First, try to use linked apps. Partition the candidates into four lists:
4821            // one for the final results, one for the "do not use ever", one for "undefined status"
4822            // and finally one for "browser app type".
4823            for (int n=0; n<count; n++) {
4824                ResolveInfo info = candidates.get(n);
4825                String packageName = info.activityInfo.packageName;
4826                PackageSetting ps = mSettings.mPackages.get(packageName);
4827                if (ps != null) {
4828                    // Add to the special match all list (Browser use case)
4829                    if (info.handleAllWebDataURI) {
4830                        matchAllList.add(info);
4831                        continue;
4832                    }
4833                    // Try to get the status from User settings first
4834                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4835                    int status = (int)(packedStatus >> 32);
4836                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4837                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4838                        if (DEBUG_DOMAIN_VERIFICATION) {
4839                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4840                                    + " : linkgen=" + linkGeneration);
4841                        }
4842                        // Use link-enabled generation as preferredOrder, i.e.
4843                        // prefer newly-enabled over earlier-enabled.
4844                        info.preferredOrder = linkGeneration;
4845                        alwaysList.add(info);
4846                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4847                        if (DEBUG_DOMAIN_VERIFICATION) {
4848                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4849                        }
4850                        neverList.add(info);
4851                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4852                        if (DEBUG_DOMAIN_VERIFICATION) {
4853                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4854                        }
4855                        alwaysAskList.add(info);
4856                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4857                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4858                        if (DEBUG_DOMAIN_VERIFICATION) {
4859                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4860                        }
4861                        undefinedList.add(info);
4862                    }
4863                }
4864            }
4865
4866            // We'll want to include browser possibilities in a few cases
4867            boolean includeBrowser = false;
4868
4869            // First try to add the "always" resolution(s) for the current user, if any
4870            if (alwaysList.size() > 0) {
4871                result.addAll(alwaysList);
4872            } else {
4873                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4874                result.addAll(undefinedList);
4875                // Maybe add one for the other profile.
4876                if (xpDomainInfo != null && (
4877                        xpDomainInfo.bestDomainVerificationStatus
4878                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4879                    result.add(xpDomainInfo.resolveInfo);
4880                }
4881                includeBrowser = true;
4882            }
4883
4884            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4885            // If there were 'always' entries their preferred order has been set, so we also
4886            // back that off to make the alternatives equivalent
4887            if (alwaysAskList.size() > 0) {
4888                for (ResolveInfo i : result) {
4889                    i.preferredOrder = 0;
4890                }
4891                result.addAll(alwaysAskList);
4892                includeBrowser = true;
4893            }
4894
4895            if (includeBrowser) {
4896                // Also add browsers (all of them or only the default one)
4897                if (DEBUG_DOMAIN_VERIFICATION) {
4898                    Slog.v(TAG, "   ...including browsers in candidate set");
4899                }
4900                if ((matchFlags & MATCH_ALL) != 0) {
4901                    result.addAll(matchAllList);
4902                } else {
4903                    // Browser/generic handling case.  If there's a default browser, go straight
4904                    // to that (but only if there is no other higher-priority match).
4905                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4906                    int maxMatchPrio = 0;
4907                    ResolveInfo defaultBrowserMatch = null;
4908                    final int numCandidates = matchAllList.size();
4909                    for (int n = 0; n < numCandidates; n++) {
4910                        ResolveInfo info = matchAllList.get(n);
4911                        // track the highest overall match priority...
4912                        if (info.priority > maxMatchPrio) {
4913                            maxMatchPrio = info.priority;
4914                        }
4915                        // ...and the highest-priority default browser match
4916                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4917                            if (defaultBrowserMatch == null
4918                                    || (defaultBrowserMatch.priority < info.priority)) {
4919                                if (debug) {
4920                                    Slog.v(TAG, "Considering default browser match " + info);
4921                                }
4922                                defaultBrowserMatch = info;
4923                            }
4924                        }
4925                    }
4926                    if (defaultBrowserMatch != null
4927                            && defaultBrowserMatch.priority >= maxMatchPrio
4928                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4929                    {
4930                        if (debug) {
4931                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4932                        }
4933                        result.add(defaultBrowserMatch);
4934                    } else {
4935                        result.addAll(matchAllList);
4936                    }
4937                }
4938
4939                // If there is nothing selected, add all candidates and remove the ones that the user
4940                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4941                if (result.size() == 0) {
4942                    result.addAll(candidates);
4943                    result.removeAll(neverList);
4944                }
4945            }
4946        }
4947        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4948            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4949                    result.size());
4950            for (ResolveInfo info : result) {
4951                Slog.v(TAG, "  + " + info.activityInfo);
4952            }
4953        }
4954        return result;
4955    }
4956
4957    // Returns a packed value as a long:
4958    //
4959    // high 'int'-sized word: link status: undefined/ask/never/always.
4960    // low 'int'-sized word: relative priority among 'always' results.
4961    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4962        long result = ps.getDomainVerificationStatusForUser(userId);
4963        // if none available, get the master status
4964        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4965            if (ps.getIntentFilterVerificationInfo() != null) {
4966                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4967            }
4968        }
4969        return result;
4970    }
4971
4972    private ResolveInfo querySkipCurrentProfileIntents(
4973            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4974            int flags, int sourceUserId) {
4975        if (matchingFilters != null) {
4976            int size = matchingFilters.size();
4977            for (int i = 0; i < size; i ++) {
4978                CrossProfileIntentFilter filter = matchingFilters.get(i);
4979                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4980                    // Checking if there are activities in the target user that can handle the
4981                    // intent.
4982                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4983                            resolvedType, flags, sourceUserId);
4984                    if (resolveInfo != null) {
4985                        return resolveInfo;
4986                    }
4987                }
4988            }
4989        }
4990        return null;
4991    }
4992
4993    // Return matching ResolveInfo if any for skip current profile intent filters.
4994    private ResolveInfo queryCrossProfileIntents(
4995            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4996            int flags, int sourceUserId) {
4997        if (matchingFilters != null) {
4998            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4999            // match the same intent. For performance reasons, it is better not to
5000            // run queryIntent twice for the same userId
5001            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5002            int size = matchingFilters.size();
5003            for (int i = 0; i < size; i++) {
5004                CrossProfileIntentFilter filter = matchingFilters.get(i);
5005                int targetUserId = filter.getTargetUserId();
5006                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
5007                        && !alreadyTriedUserIds.get(targetUserId)) {
5008                    // Checking if there are activities in the target user that can handle the
5009                    // intent.
5010                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5011                            resolvedType, flags, sourceUserId);
5012                    if (resolveInfo != null) return resolveInfo;
5013                    alreadyTriedUserIds.put(targetUserId, true);
5014                }
5015            }
5016        }
5017        return null;
5018    }
5019
5020    /**
5021     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5022     * will forward the intent to the filter's target user.
5023     * Otherwise, returns null.
5024     */
5025    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5026            String resolvedType, int flags, int sourceUserId) {
5027        int targetUserId = filter.getTargetUserId();
5028        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5029                resolvedType, flags, targetUserId);
5030        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5031                && isUserEnabled(targetUserId)) {
5032            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5033        }
5034        return null;
5035    }
5036
5037    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5038            int sourceUserId, int targetUserId) {
5039        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5040        long ident = Binder.clearCallingIdentity();
5041        boolean targetIsProfile;
5042        try {
5043            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5044        } finally {
5045            Binder.restoreCallingIdentity(ident);
5046        }
5047        String className;
5048        if (targetIsProfile) {
5049            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5050        } else {
5051            className = FORWARD_INTENT_TO_PARENT;
5052        }
5053        ComponentName forwardingActivityComponentName = new ComponentName(
5054                mAndroidApplication.packageName, className);
5055        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5056                sourceUserId);
5057        if (!targetIsProfile) {
5058            forwardingActivityInfo.showUserIcon = targetUserId;
5059            forwardingResolveInfo.noResourceId = true;
5060        }
5061        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5062        forwardingResolveInfo.priority = 0;
5063        forwardingResolveInfo.preferredOrder = 0;
5064        forwardingResolveInfo.match = 0;
5065        forwardingResolveInfo.isDefault = true;
5066        forwardingResolveInfo.filter = filter;
5067        forwardingResolveInfo.targetUserId = targetUserId;
5068        return forwardingResolveInfo;
5069    }
5070
5071    @Override
5072    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5073            Intent[] specifics, String[] specificTypes, Intent intent,
5074            String resolvedType, int flags, int userId) {
5075        if (!sUserManager.exists(userId)) return Collections.emptyList();
5076        flags = augmentFlagsForUser(flags, userId);
5077        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5078                false, "query intent activity options");
5079        final String resultsAction = intent.getAction();
5080
5081        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5082                | PackageManager.GET_RESOLVED_FILTER, userId);
5083
5084        if (DEBUG_INTENT_MATCHING) {
5085            Log.v(TAG, "Query " + intent + ": " + results);
5086        }
5087
5088        int specificsPos = 0;
5089        int N;
5090
5091        // todo: note that the algorithm used here is O(N^2).  This
5092        // isn't a problem in our current environment, but if we start running
5093        // into situations where we have more than 5 or 10 matches then this
5094        // should probably be changed to something smarter...
5095
5096        // First we go through and resolve each of the specific items
5097        // that were supplied, taking care of removing any corresponding
5098        // duplicate items in the generic resolve list.
5099        if (specifics != null) {
5100            for (int i=0; i<specifics.length; i++) {
5101                final Intent sintent = specifics[i];
5102                if (sintent == null) {
5103                    continue;
5104                }
5105
5106                if (DEBUG_INTENT_MATCHING) {
5107                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5108                }
5109
5110                String action = sintent.getAction();
5111                if (resultsAction != null && resultsAction.equals(action)) {
5112                    // If this action was explicitly requested, then don't
5113                    // remove things that have it.
5114                    action = null;
5115                }
5116
5117                ResolveInfo ri = null;
5118                ActivityInfo ai = null;
5119
5120                ComponentName comp = sintent.getComponent();
5121                if (comp == null) {
5122                    ri = resolveIntent(
5123                        sintent,
5124                        specificTypes != null ? specificTypes[i] : null,
5125                            flags, userId);
5126                    if (ri == null) {
5127                        continue;
5128                    }
5129                    if (ri == mResolveInfo) {
5130                        // ACK!  Must do something better with this.
5131                    }
5132                    ai = ri.activityInfo;
5133                    comp = new ComponentName(ai.applicationInfo.packageName,
5134                            ai.name);
5135                } else {
5136                    ai = getActivityInfo(comp, flags, userId);
5137                    if (ai == null) {
5138                        continue;
5139                    }
5140                }
5141
5142                // Look for any generic query activities that are duplicates
5143                // of this specific one, and remove them from the results.
5144                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5145                N = results.size();
5146                int j;
5147                for (j=specificsPos; j<N; j++) {
5148                    ResolveInfo sri = results.get(j);
5149                    if ((sri.activityInfo.name.equals(comp.getClassName())
5150                            && sri.activityInfo.applicationInfo.packageName.equals(
5151                                    comp.getPackageName()))
5152                        || (action != null && sri.filter.matchAction(action))) {
5153                        results.remove(j);
5154                        if (DEBUG_INTENT_MATCHING) Log.v(
5155                            TAG, "Removing duplicate item from " + j
5156                            + " due to specific " + specificsPos);
5157                        if (ri == null) {
5158                            ri = sri;
5159                        }
5160                        j--;
5161                        N--;
5162                    }
5163                }
5164
5165                // Add this specific item to its proper place.
5166                if (ri == null) {
5167                    ri = new ResolveInfo();
5168                    ri.activityInfo = ai;
5169                }
5170                results.add(specificsPos, ri);
5171                ri.specificIndex = i;
5172                specificsPos++;
5173            }
5174        }
5175
5176        // Now we go through the remaining generic results and remove any
5177        // duplicate actions that are found here.
5178        N = results.size();
5179        for (int i=specificsPos; i<N-1; i++) {
5180            final ResolveInfo rii = results.get(i);
5181            if (rii.filter == null) {
5182                continue;
5183            }
5184
5185            // Iterate over all of the actions of this result's intent
5186            // filter...  typically this should be just one.
5187            final Iterator<String> it = rii.filter.actionsIterator();
5188            if (it == null) {
5189                continue;
5190            }
5191            while (it.hasNext()) {
5192                final String action = it.next();
5193                if (resultsAction != null && resultsAction.equals(action)) {
5194                    // If this action was explicitly requested, then don't
5195                    // remove things that have it.
5196                    continue;
5197                }
5198                for (int j=i+1; j<N; j++) {
5199                    final ResolveInfo rij = results.get(j);
5200                    if (rij.filter != null && rij.filter.hasAction(action)) {
5201                        results.remove(j);
5202                        if (DEBUG_INTENT_MATCHING) Log.v(
5203                            TAG, "Removing duplicate item from " + j
5204                            + " due to action " + action + " at " + i);
5205                        j--;
5206                        N--;
5207                    }
5208                }
5209            }
5210
5211            // If the caller didn't request filter information, drop it now
5212            // so we don't have to marshall/unmarshall it.
5213            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5214                rii.filter = null;
5215            }
5216        }
5217
5218        // Filter out the caller activity if so requested.
5219        if (caller != null) {
5220            N = results.size();
5221            for (int i=0; i<N; i++) {
5222                ActivityInfo ainfo = results.get(i).activityInfo;
5223                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5224                        && caller.getClassName().equals(ainfo.name)) {
5225                    results.remove(i);
5226                    break;
5227                }
5228            }
5229        }
5230
5231        // If the caller didn't request filter information,
5232        // drop them now so we don't have to
5233        // marshall/unmarshall it.
5234        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5235            N = results.size();
5236            for (int i=0; i<N; i++) {
5237                results.get(i).filter = null;
5238            }
5239        }
5240
5241        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5242        return results;
5243    }
5244
5245    @Override
5246    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5247            int userId) {
5248        if (!sUserManager.exists(userId)) return Collections.emptyList();
5249        flags = augmentFlagsForUser(flags, userId);
5250        ComponentName comp = intent.getComponent();
5251        if (comp == null) {
5252            if (intent.getSelector() != null) {
5253                intent = intent.getSelector();
5254                comp = intent.getComponent();
5255            }
5256        }
5257        if (comp != null) {
5258            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5259            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5260            if (ai != null) {
5261                ResolveInfo ri = new ResolveInfo();
5262                ri.activityInfo = ai;
5263                list.add(ri);
5264            }
5265            return list;
5266        }
5267
5268        // reader
5269        synchronized (mPackages) {
5270            String pkgName = intent.getPackage();
5271            if (pkgName == null) {
5272                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5273            }
5274            final PackageParser.Package pkg = mPackages.get(pkgName);
5275            if (pkg != null) {
5276                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5277                        userId);
5278            }
5279            return null;
5280        }
5281    }
5282
5283    @Override
5284    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5285        if (!sUserManager.exists(userId)) return null;
5286        flags = augmentFlagsForUser(flags, userId);
5287        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5288        if (query != null) {
5289            if (query.size() >= 1) {
5290                // If there is more than one service with the same priority,
5291                // just arbitrarily pick the first one.
5292                return query.get(0);
5293            }
5294        }
5295        return null;
5296    }
5297
5298    @Override
5299    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5300            int userId) {
5301        if (!sUserManager.exists(userId)) return Collections.emptyList();
5302        flags = augmentFlagsForUser(flags, userId);
5303        ComponentName comp = intent.getComponent();
5304        if (comp == null) {
5305            if (intent.getSelector() != null) {
5306                intent = intent.getSelector();
5307                comp = intent.getComponent();
5308            }
5309        }
5310        if (comp != null) {
5311            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5312            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5313            if (si != null) {
5314                final ResolveInfo ri = new ResolveInfo();
5315                ri.serviceInfo = si;
5316                list.add(ri);
5317            }
5318            return list;
5319        }
5320
5321        // reader
5322        synchronized (mPackages) {
5323            String pkgName = intent.getPackage();
5324            if (pkgName == null) {
5325                return mServices.queryIntent(intent, resolvedType, flags, userId);
5326            }
5327            final PackageParser.Package pkg = mPackages.get(pkgName);
5328            if (pkg != null) {
5329                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5330                        userId);
5331            }
5332            return null;
5333        }
5334    }
5335
5336    @Override
5337    public List<ResolveInfo> queryIntentContentProviders(
5338            Intent intent, String resolvedType, int flags, int userId) {
5339        if (!sUserManager.exists(userId)) return Collections.emptyList();
5340        flags = augmentFlagsForUser(flags, userId);
5341        ComponentName comp = intent.getComponent();
5342        if (comp == null) {
5343            if (intent.getSelector() != null) {
5344                intent = intent.getSelector();
5345                comp = intent.getComponent();
5346            }
5347        }
5348        if (comp != null) {
5349            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5350            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5351            if (pi != null) {
5352                final ResolveInfo ri = new ResolveInfo();
5353                ri.providerInfo = pi;
5354                list.add(ri);
5355            }
5356            return list;
5357        }
5358
5359        // reader
5360        synchronized (mPackages) {
5361            String pkgName = intent.getPackage();
5362            if (pkgName == null) {
5363                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5364            }
5365            final PackageParser.Package pkg = mPackages.get(pkgName);
5366            if (pkg != null) {
5367                return mProviders.queryIntentForPackage(
5368                        intent, resolvedType, flags, pkg.providers, userId);
5369            }
5370            return null;
5371        }
5372    }
5373
5374    @Override
5375    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5376        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5377
5378        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5379
5380        // writer
5381        synchronized (mPackages) {
5382            ArrayList<PackageInfo> list;
5383            if (listUninstalled) {
5384                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5385                for (PackageSetting ps : mSettings.mPackages.values()) {
5386                    PackageInfo pi;
5387                    if (ps.pkg != null) {
5388                        pi = generatePackageInfo(ps.pkg, flags, userId);
5389                    } else {
5390                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5391                    }
5392                    if (pi != null) {
5393                        list.add(pi);
5394                    }
5395                }
5396            } else {
5397                list = new ArrayList<PackageInfo>(mPackages.size());
5398                for (PackageParser.Package p : mPackages.values()) {
5399                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5400                    if (pi != null) {
5401                        list.add(pi);
5402                    }
5403                }
5404            }
5405
5406            return new ParceledListSlice<PackageInfo>(list);
5407        }
5408    }
5409
5410    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5411            String[] permissions, boolean[] tmp, int flags, int userId) {
5412        int numMatch = 0;
5413        final PermissionsState permissionsState = ps.getPermissionsState();
5414        for (int i=0; i<permissions.length; i++) {
5415            final String permission = permissions[i];
5416            if (permissionsState.hasPermission(permission, userId)) {
5417                tmp[i] = true;
5418                numMatch++;
5419            } else {
5420                tmp[i] = false;
5421            }
5422        }
5423        if (numMatch == 0) {
5424            return;
5425        }
5426        PackageInfo pi;
5427        if (ps.pkg != null) {
5428            pi = generatePackageInfo(ps.pkg, flags, userId);
5429        } else {
5430            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5431        }
5432        // The above might return null in cases of uninstalled apps or install-state
5433        // skew across users/profiles.
5434        if (pi != null) {
5435            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5436                if (numMatch == permissions.length) {
5437                    pi.requestedPermissions = permissions;
5438                } else {
5439                    pi.requestedPermissions = new String[numMatch];
5440                    numMatch = 0;
5441                    for (int i=0; i<permissions.length; i++) {
5442                        if (tmp[i]) {
5443                            pi.requestedPermissions[numMatch] = permissions[i];
5444                            numMatch++;
5445                        }
5446                    }
5447                }
5448            }
5449            list.add(pi);
5450        }
5451    }
5452
5453    @Override
5454    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5455            String[] permissions, int flags, int userId) {
5456        if (!sUserManager.exists(userId)) return null;
5457        flags = augmentFlagsForUser(flags, userId);
5458        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5459
5460        // writer
5461        synchronized (mPackages) {
5462            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5463            boolean[] tmpBools = new boolean[permissions.length];
5464            if (listUninstalled) {
5465                for (PackageSetting ps : mSettings.mPackages.values()) {
5466                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5467                }
5468            } else {
5469                for (PackageParser.Package pkg : mPackages.values()) {
5470                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5471                    if (ps != null) {
5472                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5473                                userId);
5474                    }
5475                }
5476            }
5477
5478            return new ParceledListSlice<PackageInfo>(list);
5479        }
5480    }
5481
5482    @Override
5483    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5484        if (!sUserManager.exists(userId)) return null;
5485        flags = augmentFlagsForUser(flags, userId);
5486        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5487
5488        // writer
5489        synchronized (mPackages) {
5490            ArrayList<ApplicationInfo> list;
5491            if (listUninstalled) {
5492                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5493                for (PackageSetting ps : mSettings.mPackages.values()) {
5494                    ApplicationInfo ai;
5495                    if (ps.pkg != null) {
5496                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5497                                ps.readUserState(userId), userId);
5498                    } else {
5499                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5500                    }
5501                    if (ai != null) {
5502                        list.add(ai);
5503                    }
5504                }
5505            } else {
5506                list = new ArrayList<ApplicationInfo>(mPackages.size());
5507                for (PackageParser.Package p : mPackages.values()) {
5508                    if (p.mExtras != null) {
5509                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5510                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5511                        if (ai != null) {
5512                            list.add(ai);
5513                        }
5514                    }
5515                }
5516            }
5517
5518            return new ParceledListSlice<ApplicationInfo>(list);
5519        }
5520    }
5521
5522    public List<ApplicationInfo> getPersistentApplications(int flags) {
5523        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5524
5525        // reader
5526        synchronized (mPackages) {
5527            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5528            final int userId = UserHandle.getCallingUserId();
5529            while (i.hasNext()) {
5530                final PackageParser.Package p = i.next();
5531                if (p.applicationInfo != null
5532                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5533                        && (!mSafeMode || isSystemApp(p))) {
5534                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5535                    if (ps != null) {
5536                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5537                                ps.readUserState(userId), userId);
5538                        if (ai != null) {
5539                            finalList.add(ai);
5540                        }
5541                    }
5542                }
5543            }
5544        }
5545
5546        return finalList;
5547    }
5548
5549    @Override
5550    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5551        if (!sUserManager.exists(userId)) return null;
5552        flags = augmentFlagsForUser(flags, userId);
5553        // reader
5554        synchronized (mPackages) {
5555            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5556            PackageSetting ps = provider != null
5557                    ? mSettings.mPackages.get(provider.owner.packageName)
5558                    : null;
5559            return ps != null
5560                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5561                    && (!mSafeMode || (provider.info.applicationInfo.flags
5562                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5563                    ? PackageParser.generateProviderInfo(provider, flags,
5564                            ps.readUserState(userId), userId)
5565                    : null;
5566        }
5567    }
5568
5569    /**
5570     * @deprecated
5571     */
5572    @Deprecated
5573    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5574        // reader
5575        synchronized (mPackages) {
5576            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5577                    .entrySet().iterator();
5578            final int userId = UserHandle.getCallingUserId();
5579            while (i.hasNext()) {
5580                Map.Entry<String, PackageParser.Provider> entry = i.next();
5581                PackageParser.Provider p = entry.getValue();
5582                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5583
5584                if (ps != null && p.syncable
5585                        && (!mSafeMode || (p.info.applicationInfo.flags
5586                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5587                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5588                            ps.readUserState(userId), userId);
5589                    if (info != null) {
5590                        outNames.add(entry.getKey());
5591                        outInfo.add(info);
5592                    }
5593                }
5594            }
5595        }
5596    }
5597
5598    @Override
5599    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5600            int uid, int flags) {
5601        final int userId = processName != null ? UserHandle.getUserId(uid)
5602                : UserHandle.getCallingUserId();
5603        if (!sUserManager.exists(userId)) return null;
5604        flags = augmentFlagsForUser(flags, userId);
5605
5606        ArrayList<ProviderInfo> finalList = null;
5607        // reader
5608        synchronized (mPackages) {
5609            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5610            while (i.hasNext()) {
5611                final PackageParser.Provider p = i.next();
5612                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5613                if (ps != null && p.info.authority != null
5614                        && (processName == null
5615                                || (p.info.processName.equals(processName)
5616                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5617                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5618                        && (!mSafeMode
5619                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5620                    if (finalList == null) {
5621                        finalList = new ArrayList<ProviderInfo>(3);
5622                    }
5623                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5624                            ps.readUserState(userId), userId);
5625                    if (info != null) {
5626                        finalList.add(info);
5627                    }
5628                }
5629            }
5630        }
5631
5632        if (finalList != null) {
5633            Collections.sort(finalList, mProviderInitOrderSorter);
5634            return new ParceledListSlice<ProviderInfo>(finalList);
5635        }
5636
5637        return null;
5638    }
5639
5640    @Override
5641    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5642            int flags) {
5643        // reader
5644        synchronized (mPackages) {
5645            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5646            return PackageParser.generateInstrumentationInfo(i, flags);
5647        }
5648    }
5649
5650    @Override
5651    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5652            int flags) {
5653        ArrayList<InstrumentationInfo> finalList =
5654            new ArrayList<InstrumentationInfo>();
5655
5656        // reader
5657        synchronized (mPackages) {
5658            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5659            while (i.hasNext()) {
5660                final PackageParser.Instrumentation p = i.next();
5661                if (targetPackage == null
5662                        || targetPackage.equals(p.info.targetPackage)) {
5663                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5664                            flags);
5665                    if (ii != null) {
5666                        finalList.add(ii);
5667                    }
5668                }
5669            }
5670        }
5671
5672        return finalList;
5673    }
5674
5675    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5676        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5677        if (overlays == null) {
5678            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5679            return;
5680        }
5681        for (PackageParser.Package opkg : overlays.values()) {
5682            // Not much to do if idmap fails: we already logged the error
5683            // and we certainly don't want to abort installation of pkg simply
5684            // because an overlay didn't fit properly. For these reasons,
5685            // ignore the return value of createIdmapForPackagePairLI.
5686            createIdmapForPackagePairLI(pkg, opkg);
5687        }
5688    }
5689
5690    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5691            PackageParser.Package opkg) {
5692        if (!opkg.mTrustedOverlay) {
5693            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5694                    opkg.baseCodePath + ": overlay not trusted");
5695            return false;
5696        }
5697        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5698        if (overlaySet == null) {
5699            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5700                    opkg.baseCodePath + " but target package has no known overlays");
5701            return false;
5702        }
5703        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5704        // TODO: generate idmap for split APKs
5705        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5706            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5707                    + opkg.baseCodePath);
5708            return false;
5709        }
5710        PackageParser.Package[] overlayArray =
5711            overlaySet.values().toArray(new PackageParser.Package[0]);
5712        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5713            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5714                return p1.mOverlayPriority - p2.mOverlayPriority;
5715            }
5716        };
5717        Arrays.sort(overlayArray, cmp);
5718
5719        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5720        int i = 0;
5721        for (PackageParser.Package p : overlayArray) {
5722            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5723        }
5724        return true;
5725    }
5726
5727    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5728        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5729        try {
5730            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5731        } finally {
5732            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5733        }
5734    }
5735
5736    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5737        final File[] files = dir.listFiles();
5738        if (ArrayUtils.isEmpty(files)) {
5739            Log.d(TAG, "No files in app dir " + dir);
5740            return;
5741        }
5742
5743        if (DEBUG_PACKAGE_SCANNING) {
5744            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5745                    + " flags=0x" + Integer.toHexString(parseFlags));
5746        }
5747
5748        for (File file : files) {
5749            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5750                    && !PackageInstallerService.isStageName(file.getName());
5751            if (!isPackage) {
5752                // Ignore entries which are not packages
5753                continue;
5754            }
5755            try {
5756                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5757                        scanFlags, currentTime, null);
5758            } catch (PackageManagerException e) {
5759                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5760
5761                // Delete invalid userdata apps
5762                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5763                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5764                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5765                    if (file.isDirectory()) {
5766                        mInstaller.rmPackageDir(file.getAbsolutePath());
5767                    } else {
5768                        file.delete();
5769                    }
5770                }
5771            }
5772        }
5773    }
5774
5775    private static File getSettingsProblemFile() {
5776        File dataDir = Environment.getDataDirectory();
5777        File systemDir = new File(dataDir, "system");
5778        File fname = new File(systemDir, "uiderrors.txt");
5779        return fname;
5780    }
5781
5782    static void reportSettingsProblem(int priority, String msg) {
5783        logCriticalInfo(priority, msg);
5784    }
5785
5786    static void logCriticalInfo(int priority, String msg) {
5787        Slog.println(priority, TAG, msg);
5788        EventLogTags.writePmCriticalInfo(msg);
5789        try {
5790            File fname = getSettingsProblemFile();
5791            FileOutputStream out = new FileOutputStream(fname, true);
5792            PrintWriter pw = new FastPrintWriter(out);
5793            SimpleDateFormat formatter = new SimpleDateFormat();
5794            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5795            pw.println(dateString + ": " + msg);
5796            pw.close();
5797            FileUtils.setPermissions(
5798                    fname.toString(),
5799                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5800                    -1, -1);
5801        } catch (java.io.IOException e) {
5802        }
5803    }
5804
5805    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5806            PackageParser.Package pkg, File srcFile, int parseFlags)
5807            throws PackageManagerException {
5808        if (ps != null
5809                && ps.codePath.equals(srcFile)
5810                && ps.timeStamp == srcFile.lastModified()
5811                && !isCompatSignatureUpdateNeeded(pkg)
5812                && !isRecoverSignatureUpdateNeeded(pkg)) {
5813            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5814            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5815            ArraySet<PublicKey> signingKs;
5816            synchronized (mPackages) {
5817                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5818            }
5819            if (ps.signatures.mSignatures != null
5820                    && ps.signatures.mSignatures.length != 0
5821                    && signingKs != null) {
5822                // Optimization: reuse the existing cached certificates
5823                // if the package appears to be unchanged.
5824                pkg.mSignatures = ps.signatures.mSignatures;
5825                pkg.mSigningKeys = signingKs;
5826                return;
5827            }
5828
5829            Slog.w(TAG, "PackageSetting for " + ps.name
5830                    + " is missing signatures.  Collecting certs again to recover them.");
5831        } else {
5832            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5833        }
5834
5835        try {
5836            pp.collectCertificates(pkg, parseFlags);
5837            pp.collectManifestDigest(pkg);
5838        } catch (PackageParserException e) {
5839            throw PackageManagerException.from(e);
5840        }
5841    }
5842
5843    /**
5844     *  Traces a package scan.
5845     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5846     */
5847    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5848            long currentTime, UserHandle user) throws PackageManagerException {
5849        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5850        try {
5851            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5852        } finally {
5853            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5854        }
5855    }
5856
5857    /**
5858     *  Scans a package and returns the newly parsed package.
5859     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5860     */
5861    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5862            long currentTime, UserHandle user) throws PackageManagerException {
5863        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5864        parseFlags |= mDefParseFlags;
5865        PackageParser pp = new PackageParser();
5866        pp.setSeparateProcesses(mSeparateProcesses);
5867        pp.setOnlyCoreApps(mOnlyCore);
5868        pp.setDisplayMetrics(mMetrics);
5869
5870        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5871            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5872        }
5873
5874        final PackageParser.Package pkg;
5875        try {
5876            pkg = pp.parsePackage(scanFile, parseFlags);
5877        } catch (PackageParserException e) {
5878            throw PackageManagerException.from(e);
5879        }
5880
5881        PackageSetting ps = null;
5882        PackageSetting updatedPkg;
5883        // reader
5884        synchronized (mPackages) {
5885            // Look to see if we already know about this package.
5886            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5887            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5888                // This package has been renamed to its original name.  Let's
5889                // use that.
5890                ps = mSettings.peekPackageLPr(oldName);
5891            }
5892            // If there was no original package, see one for the real package name.
5893            if (ps == null) {
5894                ps = mSettings.peekPackageLPr(pkg.packageName);
5895            }
5896            // Check to see if this package could be hiding/updating a system
5897            // package.  Must look for it either under the original or real
5898            // package name depending on our state.
5899            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5900            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5901        }
5902        boolean updatedPkgBetter = false;
5903        // First check if this is a system package that may involve an update
5904        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
5905            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5906            // it needs to drop FLAG_PRIVILEGED.
5907            if (locationIsPrivileged(scanFile)) {
5908                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5909            } else {
5910                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5911            }
5912
5913            if (ps != null && !ps.codePath.equals(scanFile)) {
5914                // The path has changed from what was last scanned...  check the
5915                // version of the new path against what we have stored to determine
5916                // what to do.
5917                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5918                if (pkg.mVersionCode <= ps.versionCode) {
5919                    // The system package has been updated and the code path does not match
5920                    // Ignore entry. Skip it.
5921                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5922                            + " ignored: updated version " + ps.versionCode
5923                            + " better than this " + pkg.mVersionCode);
5924                    if (!updatedPkg.codePath.equals(scanFile)) {
5925                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5926                                + ps.name + " changing from " + updatedPkg.codePathString
5927                                + " to " + scanFile);
5928                        updatedPkg.codePath = scanFile;
5929                        updatedPkg.codePathString = scanFile.toString();
5930                        updatedPkg.resourcePath = scanFile;
5931                        updatedPkg.resourcePathString = scanFile.toString();
5932                    }
5933                    updatedPkg.pkg = pkg;
5934                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5935                            "Package " + ps.name + " at " + scanFile
5936                                    + " ignored: updated version " + ps.versionCode
5937                                    + " better than this " + pkg.mVersionCode);
5938                } else {
5939                    // The current app on the system partition is better than
5940                    // what we have updated to on the data partition; switch
5941                    // back to the system partition version.
5942                    // At this point, its safely assumed that package installation for
5943                    // apps in system partition will go through. If not there won't be a working
5944                    // version of the app
5945                    // writer
5946                    synchronized (mPackages) {
5947                        // Just remove the loaded entries from package lists.
5948                        mPackages.remove(ps.name);
5949                    }
5950
5951                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5952                            + " reverting from " + ps.codePathString
5953                            + ": new version " + pkg.mVersionCode
5954                            + " better than installed " + ps.versionCode);
5955
5956                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5957                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5958                    synchronized (mInstallLock) {
5959                        args.cleanUpResourcesLI();
5960                    }
5961                    synchronized (mPackages) {
5962                        mSettings.enableSystemPackageLPw(ps.name);
5963                    }
5964                    updatedPkgBetter = true;
5965                }
5966            }
5967        }
5968
5969        if (updatedPkg != null) {
5970            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5971            // initially
5972            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5973
5974            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5975            // flag set initially
5976            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5977                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5978            }
5979        }
5980
5981        // Verify certificates against what was last scanned
5982        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5983
5984        /*
5985         * A new system app appeared, but we already had a non-system one of the
5986         * same name installed earlier.
5987         */
5988        boolean shouldHideSystemApp = false;
5989        if (updatedPkg == null && ps != null
5990                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5991            /*
5992             * Check to make sure the signatures match first. If they don't,
5993             * wipe the installed application and its data.
5994             */
5995            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5996                    != PackageManager.SIGNATURE_MATCH) {
5997                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5998                        + " signatures don't match existing userdata copy; removing");
5999                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6000                ps = null;
6001            } else {
6002                /*
6003                 * If the newly-added system app is an older version than the
6004                 * already installed version, hide it. It will be scanned later
6005                 * and re-added like an update.
6006                 */
6007                if (pkg.mVersionCode <= ps.versionCode) {
6008                    shouldHideSystemApp = true;
6009                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6010                            + " but new version " + pkg.mVersionCode + " better than installed "
6011                            + ps.versionCode + "; hiding system");
6012                } else {
6013                    /*
6014                     * The newly found system app is a newer version that the
6015                     * one previously installed. Simply remove the
6016                     * already-installed application and replace it with our own
6017                     * while keeping the application data.
6018                     */
6019                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6020                            + " reverting from " + ps.codePathString + ": new version "
6021                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6022                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6023                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6024                    synchronized (mInstallLock) {
6025                        args.cleanUpResourcesLI();
6026                    }
6027                }
6028            }
6029        }
6030
6031        // The apk is forward locked (not public) if its code and resources
6032        // are kept in different files. (except for app in either system or
6033        // vendor path).
6034        // TODO grab this value from PackageSettings
6035        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6036            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6037                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6038            }
6039        }
6040
6041        // TODO: extend to support forward-locked splits
6042        String resourcePath = null;
6043        String baseResourcePath = null;
6044        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6045            if (ps != null && ps.resourcePathString != null) {
6046                resourcePath = ps.resourcePathString;
6047                baseResourcePath = ps.resourcePathString;
6048            } else {
6049                // Should not happen at all. Just log an error.
6050                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6051            }
6052        } else {
6053            resourcePath = pkg.codePath;
6054            baseResourcePath = pkg.baseCodePath;
6055        }
6056
6057        // Set application objects path explicitly.
6058        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6059        pkg.applicationInfo.setCodePath(pkg.codePath);
6060        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6061        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6062        pkg.applicationInfo.setResourcePath(resourcePath);
6063        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6064        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6065
6066        // Note that we invoke the following method only if we are about to unpack an application
6067        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6068                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6069
6070        /*
6071         * If the system app should be overridden by a previously installed
6072         * data, hide the system app now and let the /data/app scan pick it up
6073         * again.
6074         */
6075        if (shouldHideSystemApp) {
6076            synchronized (mPackages) {
6077                mSettings.disableSystemPackageLPw(pkg.packageName);
6078            }
6079        }
6080
6081        return scannedPkg;
6082    }
6083
6084    private static String fixProcessName(String defProcessName,
6085            String processName, int uid) {
6086        if (processName == null) {
6087            return defProcessName;
6088        }
6089        return processName;
6090    }
6091
6092    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6093            throws PackageManagerException {
6094        if (pkgSetting.signatures.mSignatures != null) {
6095            // Already existing package. Make sure signatures match
6096            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6097                    == PackageManager.SIGNATURE_MATCH;
6098            if (!match) {
6099                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6100                        == PackageManager.SIGNATURE_MATCH;
6101            }
6102            if (!match) {
6103                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6104                        == PackageManager.SIGNATURE_MATCH;
6105            }
6106            if (!match) {
6107                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6108                        + pkg.packageName + " signatures do not match the "
6109                        + "previously installed version; ignoring!");
6110            }
6111        }
6112
6113        // Check for shared user signatures
6114        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6115            // Already existing package. Make sure signatures match
6116            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6117                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6118            if (!match) {
6119                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6120                        == PackageManager.SIGNATURE_MATCH;
6121            }
6122            if (!match) {
6123                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6124                        == PackageManager.SIGNATURE_MATCH;
6125            }
6126            if (!match) {
6127                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6128                        "Package " + pkg.packageName
6129                        + " has no signatures that match those in shared user "
6130                        + pkgSetting.sharedUser.name + "; ignoring!");
6131            }
6132        }
6133    }
6134
6135    /**
6136     * Enforces that only the system UID or root's UID can call a method exposed
6137     * via Binder.
6138     *
6139     * @param message used as message if SecurityException is thrown
6140     * @throws SecurityException if the caller is not system or root
6141     */
6142    private static final void enforceSystemOrRoot(String message) {
6143        final int uid = Binder.getCallingUid();
6144        if (uid != Process.SYSTEM_UID && uid != 0) {
6145            throw new SecurityException(message);
6146        }
6147    }
6148
6149    @Override
6150    public void performBootDexOpt() {
6151        enforceSystemOrRoot("Only the system can request dexopt be performed");
6152
6153        // Before everything else, see whether we need to fstrim.
6154        try {
6155            IMountService ms = PackageHelper.getMountService();
6156            if (ms != null) {
6157                final boolean isUpgrade = isUpgrade();
6158                boolean doTrim = isUpgrade;
6159                if (doTrim) {
6160                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6161                } else {
6162                    final long interval = android.provider.Settings.Global.getLong(
6163                            mContext.getContentResolver(),
6164                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6165                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6166                    if (interval > 0) {
6167                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6168                        if (timeSinceLast > interval) {
6169                            doTrim = true;
6170                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6171                                    + "; running immediately");
6172                        }
6173                    }
6174                }
6175                if (doTrim) {
6176                    if (!isFirstBoot()) {
6177                        try {
6178                            ActivityManagerNative.getDefault().showBootMessage(
6179                                    mContext.getResources().getString(
6180                                            R.string.android_upgrading_fstrim), true);
6181                        } catch (RemoteException e) {
6182                        }
6183                    }
6184                    ms.runMaintenance();
6185                }
6186            } else {
6187                Slog.e(TAG, "Mount service unavailable!");
6188            }
6189        } catch (RemoteException e) {
6190            // Can't happen; MountService is local
6191        }
6192
6193        final ArraySet<PackageParser.Package> pkgs;
6194        synchronized (mPackages) {
6195            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6196        }
6197
6198        if (pkgs != null) {
6199            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6200            // in case the device runs out of space.
6201            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6202            // Give priority to core apps.
6203            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6204                PackageParser.Package pkg = it.next();
6205                if (pkg.coreApp) {
6206                    if (DEBUG_DEXOPT) {
6207                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6208                    }
6209                    sortedPkgs.add(pkg);
6210                    it.remove();
6211                }
6212            }
6213            // Give priority to system apps that listen for pre boot complete.
6214            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6215            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6216            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6217                PackageParser.Package pkg = it.next();
6218                if (pkgNames.contains(pkg.packageName)) {
6219                    if (DEBUG_DEXOPT) {
6220                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6221                    }
6222                    sortedPkgs.add(pkg);
6223                    it.remove();
6224                }
6225            }
6226            // Filter out packages that aren't recently used.
6227            filterRecentlyUsedApps(pkgs);
6228            // Add all remaining apps.
6229            for (PackageParser.Package pkg : pkgs) {
6230                if (DEBUG_DEXOPT) {
6231                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6232                }
6233                sortedPkgs.add(pkg);
6234            }
6235
6236            // If we want to be lazy, filter everything that wasn't recently used.
6237            if (mLazyDexOpt) {
6238                filterRecentlyUsedApps(sortedPkgs);
6239            }
6240
6241            int i = 0;
6242            int total = sortedPkgs.size();
6243            File dataDir = Environment.getDataDirectory();
6244            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6245            if (lowThreshold == 0) {
6246                throw new IllegalStateException("Invalid low memory threshold");
6247            }
6248            for (PackageParser.Package pkg : sortedPkgs) {
6249                long usableSpace = dataDir.getUsableSpace();
6250                if (usableSpace < lowThreshold) {
6251                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6252                    break;
6253                }
6254                performBootDexOpt(pkg, ++i, total);
6255            }
6256        }
6257    }
6258
6259    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6260        // Filter out packages that aren't recently used.
6261        //
6262        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6263        // should do a full dexopt.
6264        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6265            int total = pkgs.size();
6266            int skipped = 0;
6267            long now = System.currentTimeMillis();
6268            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6269                PackageParser.Package pkg = i.next();
6270                long then = pkg.mLastPackageUsageTimeInMills;
6271                if (then + mDexOptLRUThresholdInMills < now) {
6272                    if (DEBUG_DEXOPT) {
6273                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6274                              ((then == 0) ? "never" : new Date(then)));
6275                    }
6276                    i.remove();
6277                    skipped++;
6278                }
6279            }
6280            if (DEBUG_DEXOPT) {
6281                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6282            }
6283        }
6284    }
6285
6286    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6287        List<ResolveInfo> ris = null;
6288        try {
6289            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6290                    intent, null, 0, userId);
6291        } catch (RemoteException e) {
6292        }
6293        ArraySet<String> pkgNames = new ArraySet<String>();
6294        if (ris != null) {
6295            for (ResolveInfo ri : ris) {
6296                pkgNames.add(ri.activityInfo.packageName);
6297            }
6298        }
6299        return pkgNames;
6300    }
6301
6302    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6303        if (DEBUG_DEXOPT) {
6304            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6305        }
6306        if (!isFirstBoot()) {
6307            try {
6308                ActivityManagerNative.getDefault().showBootMessage(
6309                        mContext.getResources().getString(R.string.android_upgrading_apk,
6310                                curr, total), true);
6311            } catch (RemoteException e) {
6312            }
6313        }
6314        PackageParser.Package p = pkg;
6315        synchronized (mInstallLock) {
6316            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6317                    false /* force dex */, false /* defer */, true /* include dependencies */,
6318                    false /* boot complete */, false /*useJit*/);
6319        }
6320    }
6321
6322    @Override
6323    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6324        return performDexOptTraced(packageName, instructionSet, false);
6325    }
6326
6327    public boolean performDexOpt(
6328            String packageName, String instructionSet, boolean backgroundDexopt) {
6329        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6330    }
6331
6332    private boolean performDexOptTraced(
6333            String packageName, String instructionSet, boolean backgroundDexopt) {
6334        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6335        try {
6336            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6337        } finally {
6338            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6339        }
6340    }
6341
6342    private boolean performDexOptInternal(
6343            String packageName, String instructionSet, boolean backgroundDexopt) {
6344        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6345        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6346        if (!dexopt && !updateUsage) {
6347            // We aren't going to dexopt or update usage, so bail early.
6348            return false;
6349        }
6350        PackageParser.Package p;
6351        final String targetInstructionSet;
6352        synchronized (mPackages) {
6353            p = mPackages.get(packageName);
6354            if (p == null) {
6355                return false;
6356            }
6357            if (updateUsage) {
6358                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6359            }
6360            mPackageUsage.write(false);
6361            if (!dexopt) {
6362                // We aren't going to dexopt, so bail early.
6363                return false;
6364            }
6365
6366            targetInstructionSet = instructionSet != null ? instructionSet :
6367                    getPrimaryInstructionSet(p.applicationInfo);
6368            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6369                return false;
6370            }
6371        }
6372        long callingId = Binder.clearCallingIdentity();
6373        try {
6374            synchronized (mInstallLock) {
6375                final String[] instructionSets = new String[] { targetInstructionSet };
6376                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6377                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6378                        true /* boot complete */, false /*useJit*/);
6379                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6380            }
6381        } finally {
6382            Binder.restoreCallingIdentity(callingId);
6383        }
6384    }
6385
6386    public ArraySet<String> getPackagesThatNeedDexOpt() {
6387        ArraySet<String> pkgs = null;
6388        synchronized (mPackages) {
6389            for (PackageParser.Package p : mPackages.values()) {
6390                if (DEBUG_DEXOPT) {
6391                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6392                }
6393                if (!p.mDexOptPerformed.isEmpty()) {
6394                    continue;
6395                }
6396                if (pkgs == null) {
6397                    pkgs = new ArraySet<String>();
6398                }
6399                pkgs.add(p.packageName);
6400            }
6401        }
6402        return pkgs;
6403    }
6404
6405    public void shutdown() {
6406        mPackageUsage.write(true);
6407    }
6408
6409    @Override
6410    public void forceDexOpt(String packageName) {
6411        enforceSystemOrRoot("forceDexOpt");
6412
6413        PackageParser.Package pkg;
6414        synchronized (mPackages) {
6415            pkg = mPackages.get(packageName);
6416            if (pkg == null) {
6417                throw new IllegalArgumentException("Missing package: " + packageName);
6418            }
6419        }
6420
6421        synchronized (mInstallLock) {
6422            final String[] instructionSets = new String[] {
6423                    getPrimaryInstructionSet(pkg.applicationInfo) };
6424
6425            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6426
6427            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6428                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6429                    true /* boot complete */, false /*useJit*/);
6430
6431            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6432            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6433                throw new IllegalStateException("Failed to dexopt: " + res);
6434            }
6435        }
6436    }
6437
6438    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6439        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6440            Slog.w(TAG, "Unable to update from " + oldPkg.name
6441                    + " to " + newPkg.packageName
6442                    + ": old package not in system partition");
6443            return false;
6444        } else if (mPackages.get(oldPkg.name) != null) {
6445            Slog.w(TAG, "Unable to update from " + oldPkg.name
6446                    + " to " + newPkg.packageName
6447                    + ": old package still exists");
6448            return false;
6449        }
6450        return true;
6451    }
6452
6453    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6454        int[] users = sUserManager.getUserIds();
6455        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6456        if (res < 0) {
6457            return res;
6458        }
6459        for (int user : users) {
6460            if (user != 0) {
6461                res = mInstaller.createUserData(volumeUuid, packageName,
6462                        UserHandle.getUid(user, uid), user, seinfo);
6463                if (res < 0) {
6464                    return res;
6465                }
6466            }
6467        }
6468        return res;
6469    }
6470
6471    private int removeDataDirsLI(String volumeUuid, String packageName) {
6472        int[] users = sUserManager.getUserIds();
6473        int res = 0;
6474        for (int user : users) {
6475            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6476            if (resInner < 0) {
6477                res = resInner;
6478            }
6479        }
6480
6481        return res;
6482    }
6483
6484    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6485        int[] users = sUserManager.getUserIds();
6486        int res = 0;
6487        for (int user : users) {
6488            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6489            if (resInner < 0) {
6490                res = resInner;
6491            }
6492        }
6493        return res;
6494    }
6495
6496    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6497            PackageParser.Package changingLib) {
6498        if (file.path != null) {
6499            usesLibraryFiles.add(file.path);
6500            return;
6501        }
6502        PackageParser.Package p = mPackages.get(file.apk);
6503        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6504            // If we are doing this while in the middle of updating a library apk,
6505            // then we need to make sure to use that new apk for determining the
6506            // dependencies here.  (We haven't yet finished committing the new apk
6507            // to the package manager state.)
6508            if (p == null || p.packageName.equals(changingLib.packageName)) {
6509                p = changingLib;
6510            }
6511        }
6512        if (p != null) {
6513            usesLibraryFiles.addAll(p.getAllCodePaths());
6514        }
6515    }
6516
6517    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6518            PackageParser.Package changingLib) throws PackageManagerException {
6519        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6520            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6521            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6522            for (int i=0; i<N; i++) {
6523                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6524                if (file == null) {
6525                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6526                            "Package " + pkg.packageName + " requires unavailable shared library "
6527                            + pkg.usesLibraries.get(i) + "; failing!");
6528                }
6529                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6530            }
6531            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6532            for (int i=0; i<N; i++) {
6533                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6534                if (file == null) {
6535                    Slog.w(TAG, "Package " + pkg.packageName
6536                            + " desires unavailable shared library "
6537                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6538                } else {
6539                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6540                }
6541            }
6542            N = usesLibraryFiles.size();
6543            if (N > 0) {
6544                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6545            } else {
6546                pkg.usesLibraryFiles = null;
6547            }
6548        }
6549    }
6550
6551    private static boolean hasString(List<String> list, List<String> which) {
6552        if (list == null) {
6553            return false;
6554        }
6555        for (int i=list.size()-1; i>=0; i--) {
6556            for (int j=which.size()-1; j>=0; j--) {
6557                if (which.get(j).equals(list.get(i))) {
6558                    return true;
6559                }
6560            }
6561        }
6562        return false;
6563    }
6564
6565    private void updateAllSharedLibrariesLPw() {
6566        for (PackageParser.Package pkg : mPackages.values()) {
6567            try {
6568                updateSharedLibrariesLPw(pkg, null);
6569            } catch (PackageManagerException e) {
6570                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6571            }
6572        }
6573    }
6574
6575    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6576            PackageParser.Package changingPkg) {
6577        ArrayList<PackageParser.Package> res = null;
6578        for (PackageParser.Package pkg : mPackages.values()) {
6579            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6580                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6581                if (res == null) {
6582                    res = new ArrayList<PackageParser.Package>();
6583                }
6584                res.add(pkg);
6585                try {
6586                    updateSharedLibrariesLPw(pkg, changingPkg);
6587                } catch (PackageManagerException e) {
6588                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6589                }
6590            }
6591        }
6592        return res;
6593    }
6594
6595    /**
6596     * Derive the value of the {@code cpuAbiOverride} based on the provided
6597     * value and an optional stored value from the package settings.
6598     */
6599    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6600        String cpuAbiOverride = null;
6601
6602        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6603            cpuAbiOverride = null;
6604        } else if (abiOverride != null) {
6605            cpuAbiOverride = abiOverride;
6606        } else if (settings != null) {
6607            cpuAbiOverride = settings.cpuAbiOverrideString;
6608        }
6609
6610        return cpuAbiOverride;
6611    }
6612
6613    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6614            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6615        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6616        try {
6617            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6618        } finally {
6619            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6620        }
6621    }
6622
6623    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6624            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6625        boolean success = false;
6626        try {
6627            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6628                    currentTime, user);
6629            success = true;
6630            return res;
6631        } finally {
6632            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6633                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6634            }
6635        }
6636    }
6637
6638    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6639            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6640        final File scanFile = new File(pkg.codePath);
6641        if (pkg.applicationInfo.getCodePath() == null ||
6642                pkg.applicationInfo.getResourcePath() == null) {
6643            // Bail out. The resource and code paths haven't been set.
6644            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6645                    "Code and resource paths haven't been set correctly");
6646        }
6647
6648        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6649            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6650        } else {
6651            // Only allow system apps to be flagged as core apps.
6652            pkg.coreApp = false;
6653        }
6654
6655        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6656            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6657        }
6658
6659        if (mCustomResolverComponentName != null &&
6660                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6661            setUpCustomResolverActivity(pkg);
6662        }
6663
6664        if (pkg.packageName.equals("android")) {
6665            synchronized (mPackages) {
6666                if (mAndroidApplication != null) {
6667                    Slog.w(TAG, "*************************************************");
6668                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6669                    Slog.w(TAG, " file=" + scanFile);
6670                    Slog.w(TAG, "*************************************************");
6671                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6672                            "Core android package being redefined.  Skipping.");
6673                }
6674
6675                // Set up information for our fall-back user intent resolution activity.
6676                mPlatformPackage = pkg;
6677                pkg.mVersionCode = mSdkVersion;
6678                mAndroidApplication = pkg.applicationInfo;
6679
6680                if (!mResolverReplaced) {
6681                    mResolveActivity.applicationInfo = mAndroidApplication;
6682                    mResolveActivity.name = ResolverActivity.class.getName();
6683                    mResolveActivity.packageName = mAndroidApplication.packageName;
6684                    mResolveActivity.processName = "system:ui";
6685                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6686                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6687                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6688                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6689                    mResolveActivity.exported = true;
6690                    mResolveActivity.enabled = true;
6691                    mResolveInfo.activityInfo = mResolveActivity;
6692                    mResolveInfo.priority = 0;
6693                    mResolveInfo.preferredOrder = 0;
6694                    mResolveInfo.match = 0;
6695                    mResolveComponentName = new ComponentName(
6696                            mAndroidApplication.packageName, mResolveActivity.name);
6697                }
6698            }
6699        }
6700
6701        if (DEBUG_PACKAGE_SCANNING) {
6702            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6703                Log.d(TAG, "Scanning package " + pkg.packageName);
6704        }
6705
6706        if (mPackages.containsKey(pkg.packageName)
6707                || mSharedLibraries.containsKey(pkg.packageName)) {
6708            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6709                    "Application package " + pkg.packageName
6710                    + " already installed.  Skipping duplicate.");
6711        }
6712
6713        // If we're only installing presumed-existing packages, require that the
6714        // scanned APK is both already known and at the path previously established
6715        // for it.  Previously unknown packages we pick up normally, but if we have an
6716        // a priori expectation about this package's install presence, enforce it.
6717        // With a singular exception for new system packages. When an OTA contains
6718        // a new system package, we allow the codepath to change from a system location
6719        // to the user-installed location. If we don't allow this change, any newer,
6720        // user-installed version of the application will be ignored.
6721        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6722            if (mExpectingBetter.containsKey(pkg.packageName)) {
6723                logCriticalInfo(Log.WARN,
6724                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6725            } else {
6726                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6727                if (known != null) {
6728                    if (DEBUG_PACKAGE_SCANNING) {
6729                        Log.d(TAG, "Examining " + pkg.codePath
6730                                + " and requiring known paths " + known.codePathString
6731                                + " & " + known.resourcePathString);
6732                    }
6733                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6734                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6735                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6736                                "Application package " + pkg.packageName
6737                                + " found at " + pkg.applicationInfo.getCodePath()
6738                                + " but expected at " + known.codePathString + "; ignoring.");
6739                    }
6740                }
6741            }
6742        }
6743
6744        // Initialize package source and resource directories
6745        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6746        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6747
6748        SharedUserSetting suid = null;
6749        PackageSetting pkgSetting = null;
6750
6751        if (!isSystemApp(pkg)) {
6752            // Only system apps can use these features.
6753            pkg.mOriginalPackages = null;
6754            pkg.mRealPackage = null;
6755            pkg.mAdoptPermissions = null;
6756        }
6757
6758        // writer
6759        synchronized (mPackages) {
6760            if (pkg.mSharedUserId != null) {
6761                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6762                if (suid == null) {
6763                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6764                            "Creating application package " + pkg.packageName
6765                            + " for shared user failed");
6766                }
6767                if (DEBUG_PACKAGE_SCANNING) {
6768                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6769                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6770                                + "): packages=" + suid.packages);
6771                }
6772            }
6773
6774            // Check if we are renaming from an original package name.
6775            PackageSetting origPackage = null;
6776            String realName = null;
6777            if (pkg.mOriginalPackages != null) {
6778                // This package may need to be renamed to a previously
6779                // installed name.  Let's check on that...
6780                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6781                if (pkg.mOriginalPackages.contains(renamed)) {
6782                    // This package had originally been installed as the
6783                    // original name, and we have already taken care of
6784                    // transitioning to the new one.  Just update the new
6785                    // one to continue using the old name.
6786                    realName = pkg.mRealPackage;
6787                    if (!pkg.packageName.equals(renamed)) {
6788                        // Callers into this function may have already taken
6789                        // care of renaming the package; only do it here if
6790                        // it is not already done.
6791                        pkg.setPackageName(renamed);
6792                    }
6793
6794                } else {
6795                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6796                        if ((origPackage = mSettings.peekPackageLPr(
6797                                pkg.mOriginalPackages.get(i))) != null) {
6798                            // We do have the package already installed under its
6799                            // original name...  should we use it?
6800                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6801                                // New package is not compatible with original.
6802                                origPackage = null;
6803                                continue;
6804                            } else if (origPackage.sharedUser != null) {
6805                                // Make sure uid is compatible between packages.
6806                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6807                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6808                                            + " to " + pkg.packageName + ": old uid "
6809                                            + origPackage.sharedUser.name
6810                                            + " differs from " + pkg.mSharedUserId);
6811                                    origPackage = null;
6812                                    continue;
6813                                }
6814                            } else {
6815                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6816                                        + pkg.packageName + " to old name " + origPackage.name);
6817                            }
6818                            break;
6819                        }
6820                    }
6821                }
6822            }
6823
6824            if (mTransferedPackages.contains(pkg.packageName)) {
6825                Slog.w(TAG, "Package " + pkg.packageName
6826                        + " was transferred to another, but its .apk remains");
6827            }
6828
6829            // Just create the setting, don't add it yet. For already existing packages
6830            // the PkgSetting exists already and doesn't have to be created.
6831            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6832                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6833                    pkg.applicationInfo.primaryCpuAbi,
6834                    pkg.applicationInfo.secondaryCpuAbi,
6835                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6836                    user, false);
6837            if (pkgSetting == null) {
6838                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6839                        "Creating application package " + pkg.packageName + " failed");
6840            }
6841
6842            if (pkgSetting.origPackage != null) {
6843                // If we are first transitioning from an original package,
6844                // fix up the new package's name now.  We need to do this after
6845                // looking up the package under its new name, so getPackageLP
6846                // can take care of fiddling things correctly.
6847                pkg.setPackageName(origPackage.name);
6848
6849                // File a report about this.
6850                String msg = "New package " + pkgSetting.realName
6851                        + " renamed to replace old package " + pkgSetting.name;
6852                reportSettingsProblem(Log.WARN, msg);
6853
6854                // Make a note of it.
6855                mTransferedPackages.add(origPackage.name);
6856
6857                // No longer need to retain this.
6858                pkgSetting.origPackage = null;
6859            }
6860
6861            if (realName != null) {
6862                // Make a note of it.
6863                mTransferedPackages.add(pkg.packageName);
6864            }
6865
6866            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6867                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6868            }
6869
6870            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6871                // Check all shared libraries and map to their actual file path.
6872                // We only do this here for apps not on a system dir, because those
6873                // are the only ones that can fail an install due to this.  We
6874                // will take care of the system apps by updating all of their
6875                // library paths after the scan is done.
6876                updateSharedLibrariesLPw(pkg, null);
6877            }
6878
6879            if (mFoundPolicyFile) {
6880                SELinuxMMAC.assignSeinfoValue(pkg);
6881            }
6882
6883            pkg.applicationInfo.uid = pkgSetting.appId;
6884            pkg.mExtras = pkgSetting;
6885            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6886                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6887                    // We just determined the app is signed correctly, so bring
6888                    // over the latest parsed certs.
6889                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6890                } else {
6891                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6892                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6893                                "Package " + pkg.packageName + " upgrade keys do not match the "
6894                                + "previously installed version");
6895                    } else {
6896                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6897                        String msg = "System package " + pkg.packageName
6898                            + " signature changed; retaining data.";
6899                        reportSettingsProblem(Log.WARN, msg);
6900                    }
6901                }
6902            } else {
6903                try {
6904                    verifySignaturesLP(pkgSetting, pkg);
6905                    // We just determined the app is signed correctly, so bring
6906                    // over the latest parsed certs.
6907                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6908                } catch (PackageManagerException e) {
6909                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6910                        throw e;
6911                    }
6912                    // The signature has changed, but this package is in the system
6913                    // image...  let's recover!
6914                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6915                    // However...  if this package is part of a shared user, but it
6916                    // doesn't match the signature of the shared user, let's fail.
6917                    // What this means is that you can't change the signatures
6918                    // associated with an overall shared user, which doesn't seem all
6919                    // that unreasonable.
6920                    if (pkgSetting.sharedUser != null) {
6921                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6922                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6923                            throw new PackageManagerException(
6924                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6925                                            "Signature mismatch for shared user : "
6926                                            + pkgSetting.sharedUser);
6927                        }
6928                    }
6929                    // File a report about this.
6930                    String msg = "System package " + pkg.packageName
6931                        + " signature changed; retaining data.";
6932                    reportSettingsProblem(Log.WARN, msg);
6933                }
6934            }
6935            // Verify that this new package doesn't have any content providers
6936            // that conflict with existing packages.  Only do this if the
6937            // package isn't already installed, since we don't want to break
6938            // things that are installed.
6939            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6940                final int N = pkg.providers.size();
6941                int i;
6942                for (i=0; i<N; i++) {
6943                    PackageParser.Provider p = pkg.providers.get(i);
6944                    if (p.info.authority != null) {
6945                        String names[] = p.info.authority.split(";");
6946                        for (int j = 0; j < names.length; j++) {
6947                            if (mProvidersByAuthority.containsKey(names[j])) {
6948                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6949                                final String otherPackageName =
6950                                        ((other != null && other.getComponentName() != null) ?
6951                                                other.getComponentName().getPackageName() : "?");
6952                                throw new PackageManagerException(
6953                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6954                                                "Can't install because provider name " + names[j]
6955                                                + " (in package " + pkg.applicationInfo.packageName
6956                                                + ") is already used by " + otherPackageName);
6957                            }
6958                        }
6959                    }
6960                }
6961            }
6962
6963            if (pkg.mAdoptPermissions != null) {
6964                // This package wants to adopt ownership of permissions from
6965                // another package.
6966                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6967                    final String origName = pkg.mAdoptPermissions.get(i);
6968                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6969                    if (orig != null) {
6970                        if (verifyPackageUpdateLPr(orig, pkg)) {
6971                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6972                                    + pkg.packageName);
6973                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6974                        }
6975                    }
6976                }
6977            }
6978        }
6979
6980        final String pkgName = pkg.packageName;
6981
6982        final long scanFileTime = scanFile.lastModified();
6983        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6984        pkg.applicationInfo.processName = fixProcessName(
6985                pkg.applicationInfo.packageName,
6986                pkg.applicationInfo.processName,
6987                pkg.applicationInfo.uid);
6988
6989        if (pkg != mPlatformPackage) {
6990            // This is a normal package, need to make its data directory.
6991            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
6992                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
6993
6994            boolean uidError = false;
6995            if (dataPath.exists()) {
6996                int currentUid = 0;
6997                try {
6998                    StructStat stat = Os.stat(dataPath.getPath());
6999                    currentUid = stat.st_uid;
7000                } catch (ErrnoException e) {
7001                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7002                }
7003
7004                // If we have mismatched owners for the data path, we have a problem.
7005                if (currentUid != pkg.applicationInfo.uid) {
7006                    boolean recovered = false;
7007                    if (currentUid == 0) {
7008                        // The directory somehow became owned by root.  Wow.
7009                        // This is probably because the system was stopped while
7010                        // installd was in the middle of messing with its libs
7011                        // directory.  Ask installd to fix that.
7012                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7013                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7014                        if (ret >= 0) {
7015                            recovered = true;
7016                            String msg = "Package " + pkg.packageName
7017                                    + " unexpectedly changed to uid 0; recovered to " +
7018                                    + pkg.applicationInfo.uid;
7019                            reportSettingsProblem(Log.WARN, msg);
7020                        }
7021                    }
7022                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7023                            || (scanFlags&SCAN_BOOTING) != 0)) {
7024                        // If this is a system app, we can at least delete its
7025                        // current data so the application will still work.
7026                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7027                        if (ret >= 0) {
7028                            // TODO: Kill the processes first
7029                            // Old data gone!
7030                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7031                                    ? "System package " : "Third party package ";
7032                            String msg = prefix + pkg.packageName
7033                                    + " has changed from uid: "
7034                                    + currentUid + " to "
7035                                    + pkg.applicationInfo.uid + "; old data erased";
7036                            reportSettingsProblem(Log.WARN, msg);
7037                            recovered = true;
7038
7039                            // And now re-install the app.
7040                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7041                                    pkg.applicationInfo.seinfo);
7042                            if (ret == -1) {
7043                                // Ack should not happen!
7044                                msg = prefix + pkg.packageName
7045                                        + " could not have data directory re-created after delete.";
7046                                reportSettingsProblem(Log.WARN, msg);
7047                                throw new PackageManagerException(
7048                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
7049                            }
7050                        }
7051                        if (!recovered) {
7052                            mHasSystemUidErrors = true;
7053                        }
7054                    } else if (!recovered) {
7055                        // If we allow this install to proceed, we will be broken.
7056                        // Abort, abort!
7057                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7058                                "scanPackageLI");
7059                    }
7060                    if (!recovered) {
7061                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7062                            + pkg.applicationInfo.uid + "/fs_"
7063                            + currentUid;
7064                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7065                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7066                        String msg = "Package " + pkg.packageName
7067                                + " has mismatched uid: "
7068                                + currentUid + " on disk, "
7069                                + pkg.applicationInfo.uid + " in settings";
7070                        // writer
7071                        synchronized (mPackages) {
7072                            mSettings.mReadMessages.append(msg);
7073                            mSettings.mReadMessages.append('\n');
7074                            uidError = true;
7075                            if (!pkgSetting.uidError) {
7076                                reportSettingsProblem(Log.ERROR, msg);
7077                            }
7078                        }
7079                    }
7080                }
7081
7082                if (mShouldRestoreconData) {
7083                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7084                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7085                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7086                }
7087            } else {
7088                if (DEBUG_PACKAGE_SCANNING) {
7089                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7090                        Log.v(TAG, "Want this data dir: " + dataPath);
7091                }
7092                //invoke installer to do the actual installation
7093                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7094                        pkg.applicationInfo.seinfo);
7095                if (ret < 0) {
7096                    // Error from installer
7097                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7098                            "Unable to create data dirs [errorCode=" + ret + "]");
7099                }
7100            }
7101
7102            // Get all of our default paths setup
7103            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7104
7105            pkgSetting.uidError = uidError;
7106        }
7107
7108        final String path = scanFile.getPath();
7109        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7110
7111        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7112            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7113
7114            // Some system apps still use directory structure for native libraries
7115            // in which case we might end up not detecting abi solely based on apk
7116            // structure. Try to detect abi based on directory structure.
7117            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7118                    pkg.applicationInfo.primaryCpuAbi == null) {
7119                setBundledAppAbisAndRoots(pkg, pkgSetting);
7120                setNativeLibraryPaths(pkg);
7121            }
7122
7123        } else {
7124            if ((scanFlags & SCAN_MOVE) != 0) {
7125                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7126                // but we already have this packages package info in the PackageSetting. We just
7127                // use that and derive the native library path based on the new codepath.
7128                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7129                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7130            }
7131
7132            // Set native library paths again. For moves, the path will be updated based on the
7133            // ABIs we've determined above. For non-moves, the path will be updated based on the
7134            // ABIs we determined during compilation, but the path will depend on the final
7135            // package path (after the rename away from the stage path).
7136            setNativeLibraryPaths(pkg);
7137        }
7138
7139        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7140        final int[] userIds = sUserManager.getUserIds();
7141        synchronized (mInstallLock) {
7142            // Make sure all user data directories are ready to roll; we're okay
7143            // if they already exist
7144            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7145                for (int userId : userIds) {
7146                    if (userId != UserHandle.USER_SYSTEM) {
7147                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7148                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7149                                pkg.applicationInfo.seinfo);
7150                    }
7151                }
7152            }
7153
7154            // Create a native library symlink only if we have native libraries
7155            // and if the native libraries are 32 bit libraries. We do not provide
7156            // this symlink for 64 bit libraries.
7157            if (pkg.applicationInfo.primaryCpuAbi != null &&
7158                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7159                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7160                try {
7161                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7162                    for (int userId : userIds) {
7163                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7164                                nativeLibPath, userId) < 0) {
7165                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7166                                    "Failed linking native library dir (user=" + userId + ")");
7167                        }
7168                    }
7169                } finally {
7170                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7171                }
7172            }
7173        }
7174
7175        // This is a special case for the "system" package, where the ABI is
7176        // dictated by the zygote configuration (and init.rc). We should keep track
7177        // of this ABI so that we can deal with "normal" applications that run under
7178        // the same UID correctly.
7179        if (mPlatformPackage == pkg) {
7180            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7181                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7182        }
7183
7184        // If there's a mismatch between the abi-override in the package setting
7185        // and the abiOverride specified for the install. Warn about this because we
7186        // would've already compiled the app without taking the package setting into
7187        // account.
7188        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7189            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7190                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7191                        " for package: " + pkg.packageName);
7192            }
7193        }
7194
7195        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7196        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7197        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7198
7199        // Copy the derived override back to the parsed package, so that we can
7200        // update the package settings accordingly.
7201        pkg.cpuAbiOverride = cpuAbiOverride;
7202
7203        if (DEBUG_ABI_SELECTION) {
7204            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7205                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7206                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7207        }
7208
7209        // Push the derived path down into PackageSettings so we know what to
7210        // clean up at uninstall time.
7211        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7212
7213        if (DEBUG_ABI_SELECTION) {
7214            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7215                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7216                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7217        }
7218
7219        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7220            // We don't do this here during boot because we can do it all
7221            // at once after scanning all existing packages.
7222            //
7223            // We also do this *before* we perform dexopt on this package, so that
7224            // we can avoid redundant dexopts, and also to make sure we've got the
7225            // code and package path correct.
7226            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7227                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7228        }
7229
7230        if ((scanFlags & SCAN_NO_DEX) == 0) {
7231            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7232
7233            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7234                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7235                    (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7236
7237            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7238            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7239                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7240            }
7241        }
7242        if (mFactoryTest && pkg.requestedPermissions.contains(
7243                android.Manifest.permission.FACTORY_TEST)) {
7244            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7245        }
7246
7247        ArrayList<PackageParser.Package> clientLibPkgs = null;
7248
7249        // writer
7250        synchronized (mPackages) {
7251            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7252                // Only system apps can add new shared libraries.
7253                if (pkg.libraryNames != null) {
7254                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7255                        String name = pkg.libraryNames.get(i);
7256                        boolean allowed = false;
7257                        if (pkg.isUpdatedSystemApp()) {
7258                            // New library entries can only be added through the
7259                            // system image.  This is important to get rid of a lot
7260                            // of nasty edge cases: for example if we allowed a non-
7261                            // system update of the app to add a library, then uninstalling
7262                            // the update would make the library go away, and assumptions
7263                            // we made such as through app install filtering would now
7264                            // have allowed apps on the device which aren't compatible
7265                            // with it.  Better to just have the restriction here, be
7266                            // conservative, and create many fewer cases that can negatively
7267                            // impact the user experience.
7268                            final PackageSetting sysPs = mSettings
7269                                    .getDisabledSystemPkgLPr(pkg.packageName);
7270                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7271                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7272                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7273                                        allowed = true;
7274                                        break;
7275                                    }
7276                                }
7277                            }
7278                        } else {
7279                            allowed = true;
7280                        }
7281                        if (allowed) {
7282                            if (!mSharedLibraries.containsKey(name)) {
7283                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7284                            } else if (!name.equals(pkg.packageName)) {
7285                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7286                                        + name + " already exists; skipping");
7287                            }
7288                        } else {
7289                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7290                                    + name + " that is not declared on system image; skipping");
7291                        }
7292                    }
7293                    if ((scanFlags&SCAN_BOOTING) == 0) {
7294                        // If we are not booting, we need to update any applications
7295                        // that are clients of our shared library.  If we are booting,
7296                        // this will all be done once the scan is complete.
7297                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7298                    }
7299                }
7300            }
7301        }
7302
7303        // We also need to dexopt any apps that are dependent on this library.  Note that
7304        // if these fail, we should abort the install since installing the library will
7305        // result in some apps being broken.
7306        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7307        try {
7308            if (clientLibPkgs != null) {
7309                if ((scanFlags & SCAN_NO_DEX) == 0) {
7310                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7311                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7312                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7313                                null /* instruction sets */, forceDex,
7314                                (scanFlags & SCAN_DEFER_DEX) != 0, false,
7315                                (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7316                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7317                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7318                                    "scanPackageLI failed to dexopt clientLibPkgs");
7319                        }
7320                    }
7321                }
7322            }
7323        } finally {
7324            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7325        }
7326
7327        // Request the ActivityManager to kill the process(only for existing packages)
7328        // so that we do not end up in a confused state while the user is still using the older
7329        // version of the application while the new one gets installed.
7330        if ((scanFlags & SCAN_REPLACING) != 0) {
7331            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7332
7333            killApplication(pkg.applicationInfo.packageName,
7334                        pkg.applicationInfo.uid, "replace pkg");
7335
7336            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7337        }
7338
7339        // Also need to kill any apps that are dependent on the library.
7340        if (clientLibPkgs != null) {
7341            for (int i=0; i<clientLibPkgs.size(); i++) {
7342                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7343                killApplication(clientPkg.applicationInfo.packageName,
7344                        clientPkg.applicationInfo.uid, "update lib");
7345            }
7346        }
7347
7348        // Make sure we're not adding any bogus keyset info
7349        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7350        ksms.assertScannedPackageValid(pkg);
7351
7352        // writer
7353        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7354
7355        boolean createIdmapFailed = false;
7356        synchronized (mPackages) {
7357            // We don't expect installation to fail beyond this point
7358
7359            // Add the new setting to mSettings
7360            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7361            // Add the new setting to mPackages
7362            mPackages.put(pkg.applicationInfo.packageName, pkg);
7363            // Make sure we don't accidentally delete its data.
7364            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7365            while (iter.hasNext()) {
7366                PackageCleanItem item = iter.next();
7367                if (pkgName.equals(item.packageName)) {
7368                    iter.remove();
7369                }
7370            }
7371
7372            // Take care of first install / last update times.
7373            if (currentTime != 0) {
7374                if (pkgSetting.firstInstallTime == 0) {
7375                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7376                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7377                    pkgSetting.lastUpdateTime = currentTime;
7378                }
7379            } else if (pkgSetting.firstInstallTime == 0) {
7380                // We need *something*.  Take time time stamp of the file.
7381                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7382            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7383                if (scanFileTime != pkgSetting.timeStamp) {
7384                    // A package on the system image has changed; consider this
7385                    // to be an update.
7386                    pkgSetting.lastUpdateTime = scanFileTime;
7387                }
7388            }
7389
7390            // Add the package's KeySets to the global KeySetManagerService
7391            ksms.addScannedPackageLPw(pkg);
7392
7393            int N = pkg.providers.size();
7394            StringBuilder r = null;
7395            int i;
7396            for (i=0; i<N; i++) {
7397                PackageParser.Provider p = pkg.providers.get(i);
7398                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7399                        p.info.processName, pkg.applicationInfo.uid);
7400                mProviders.addProvider(p);
7401                p.syncable = p.info.isSyncable;
7402                if (p.info.authority != null) {
7403                    String names[] = p.info.authority.split(";");
7404                    p.info.authority = null;
7405                    for (int j = 0; j < names.length; j++) {
7406                        if (j == 1 && p.syncable) {
7407                            // We only want the first authority for a provider to possibly be
7408                            // syncable, so if we already added this provider using a different
7409                            // authority clear the syncable flag. We copy the provider before
7410                            // changing it because the mProviders object contains a reference
7411                            // to a provider that we don't want to change.
7412                            // Only do this for the second authority since the resulting provider
7413                            // object can be the same for all future authorities for this provider.
7414                            p = new PackageParser.Provider(p);
7415                            p.syncable = false;
7416                        }
7417                        if (!mProvidersByAuthority.containsKey(names[j])) {
7418                            mProvidersByAuthority.put(names[j], p);
7419                            if (p.info.authority == null) {
7420                                p.info.authority = names[j];
7421                            } else {
7422                                p.info.authority = p.info.authority + ";" + names[j];
7423                            }
7424                            if (DEBUG_PACKAGE_SCANNING) {
7425                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7426                                    Log.d(TAG, "Registered content provider: " + names[j]
7427                                            + ", className = " + p.info.name + ", isSyncable = "
7428                                            + p.info.isSyncable);
7429                            }
7430                        } else {
7431                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7432                            Slog.w(TAG, "Skipping provider name " + names[j] +
7433                                    " (in package " + pkg.applicationInfo.packageName +
7434                                    "): name already used by "
7435                                    + ((other != null && other.getComponentName() != null)
7436                                            ? other.getComponentName().getPackageName() : "?"));
7437                        }
7438                    }
7439                }
7440                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7441                    if (r == null) {
7442                        r = new StringBuilder(256);
7443                    } else {
7444                        r.append(' ');
7445                    }
7446                    r.append(p.info.name);
7447                }
7448            }
7449            if (r != null) {
7450                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7451            }
7452
7453            N = pkg.services.size();
7454            r = null;
7455            for (i=0; i<N; i++) {
7456                PackageParser.Service s = pkg.services.get(i);
7457                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7458                        s.info.processName, pkg.applicationInfo.uid);
7459                mServices.addService(s);
7460                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7461                    if (r == null) {
7462                        r = new StringBuilder(256);
7463                    } else {
7464                        r.append(' ');
7465                    }
7466                    r.append(s.info.name);
7467                }
7468            }
7469            if (r != null) {
7470                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7471            }
7472
7473            N = pkg.receivers.size();
7474            r = null;
7475            for (i=0; i<N; i++) {
7476                PackageParser.Activity a = pkg.receivers.get(i);
7477                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7478                        a.info.processName, pkg.applicationInfo.uid);
7479                mReceivers.addActivity(a, "receiver");
7480                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7481                    if (r == null) {
7482                        r = new StringBuilder(256);
7483                    } else {
7484                        r.append(' ');
7485                    }
7486                    r.append(a.info.name);
7487                }
7488            }
7489            if (r != null) {
7490                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7491            }
7492
7493            N = pkg.activities.size();
7494            r = null;
7495            for (i=0; i<N; i++) {
7496                PackageParser.Activity a = pkg.activities.get(i);
7497                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7498                        a.info.processName, pkg.applicationInfo.uid);
7499                mActivities.addActivity(a, "activity");
7500                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7501                    if (r == null) {
7502                        r = new StringBuilder(256);
7503                    } else {
7504                        r.append(' ');
7505                    }
7506                    r.append(a.info.name);
7507                }
7508            }
7509            if (r != null) {
7510                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7511            }
7512
7513            N = pkg.permissionGroups.size();
7514            r = null;
7515            for (i=0; i<N; i++) {
7516                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7517                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7518                if (cur == null) {
7519                    mPermissionGroups.put(pg.info.name, pg);
7520                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7521                        if (r == null) {
7522                            r = new StringBuilder(256);
7523                        } else {
7524                            r.append(' ');
7525                        }
7526                        r.append(pg.info.name);
7527                    }
7528                } else {
7529                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7530                            + pg.info.packageName + " ignored: original from "
7531                            + cur.info.packageName);
7532                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7533                        if (r == null) {
7534                            r = new StringBuilder(256);
7535                        } else {
7536                            r.append(' ');
7537                        }
7538                        r.append("DUP:");
7539                        r.append(pg.info.name);
7540                    }
7541                }
7542            }
7543            if (r != null) {
7544                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7545            }
7546
7547            N = pkg.permissions.size();
7548            r = null;
7549            for (i=0; i<N; i++) {
7550                PackageParser.Permission p = pkg.permissions.get(i);
7551
7552                // Assume by default that we did not install this permission into the system.
7553                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7554
7555                // Now that permission groups have a special meaning, we ignore permission
7556                // groups for legacy apps to prevent unexpected behavior. In particular,
7557                // permissions for one app being granted to someone just becuase they happen
7558                // to be in a group defined by another app (before this had no implications).
7559                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7560                    p.group = mPermissionGroups.get(p.info.group);
7561                    // Warn for a permission in an unknown group.
7562                    if (p.info.group != null && p.group == null) {
7563                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7564                                + p.info.packageName + " in an unknown group " + p.info.group);
7565                    }
7566                }
7567
7568                ArrayMap<String, BasePermission> permissionMap =
7569                        p.tree ? mSettings.mPermissionTrees
7570                                : mSettings.mPermissions;
7571                BasePermission bp = permissionMap.get(p.info.name);
7572
7573                // Allow system apps to redefine non-system permissions
7574                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7575                    final boolean currentOwnerIsSystem = (bp.perm != null
7576                            && isSystemApp(bp.perm.owner));
7577                    if (isSystemApp(p.owner)) {
7578                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7579                            // It's a built-in permission and no owner, take ownership now
7580                            bp.packageSetting = pkgSetting;
7581                            bp.perm = p;
7582                            bp.uid = pkg.applicationInfo.uid;
7583                            bp.sourcePackage = p.info.packageName;
7584                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7585                        } else if (!currentOwnerIsSystem) {
7586                            String msg = "New decl " + p.owner + " of permission  "
7587                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7588                            reportSettingsProblem(Log.WARN, msg);
7589                            bp = null;
7590                        }
7591                    }
7592                }
7593
7594                if (bp == null) {
7595                    bp = new BasePermission(p.info.name, p.info.packageName,
7596                            BasePermission.TYPE_NORMAL);
7597                    permissionMap.put(p.info.name, bp);
7598                }
7599
7600                if (bp.perm == null) {
7601                    if (bp.sourcePackage == null
7602                            || bp.sourcePackage.equals(p.info.packageName)) {
7603                        BasePermission tree = findPermissionTreeLP(p.info.name);
7604                        if (tree == null
7605                                || tree.sourcePackage.equals(p.info.packageName)) {
7606                            bp.packageSetting = pkgSetting;
7607                            bp.perm = p;
7608                            bp.uid = pkg.applicationInfo.uid;
7609                            bp.sourcePackage = p.info.packageName;
7610                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7611                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7612                                if (r == null) {
7613                                    r = new StringBuilder(256);
7614                                } else {
7615                                    r.append(' ');
7616                                }
7617                                r.append(p.info.name);
7618                            }
7619                        } else {
7620                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7621                                    + p.info.packageName + " ignored: base tree "
7622                                    + tree.name + " is from package "
7623                                    + tree.sourcePackage);
7624                        }
7625                    } else {
7626                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7627                                + p.info.packageName + " ignored: original from "
7628                                + bp.sourcePackage);
7629                    }
7630                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7631                    if (r == null) {
7632                        r = new StringBuilder(256);
7633                    } else {
7634                        r.append(' ');
7635                    }
7636                    r.append("DUP:");
7637                    r.append(p.info.name);
7638                }
7639                if (bp.perm == p) {
7640                    bp.protectionLevel = p.info.protectionLevel;
7641                }
7642            }
7643
7644            if (r != null) {
7645                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7646            }
7647
7648            N = pkg.instrumentation.size();
7649            r = null;
7650            for (i=0; i<N; i++) {
7651                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7652                a.info.packageName = pkg.applicationInfo.packageName;
7653                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7654                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7655                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7656                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7657                a.info.dataDir = pkg.applicationInfo.dataDir;
7658                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7659                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7660
7661                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7662                // need other information about the application, like the ABI and what not ?
7663                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7664                mInstrumentation.put(a.getComponentName(), a);
7665                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                    if (r == null) {
7667                        r = new StringBuilder(256);
7668                    } else {
7669                        r.append(' ');
7670                    }
7671                    r.append(a.info.name);
7672                }
7673            }
7674            if (r != null) {
7675                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7676            }
7677
7678            if (pkg.protectedBroadcasts != null) {
7679                N = pkg.protectedBroadcasts.size();
7680                for (i=0; i<N; i++) {
7681                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7682                }
7683            }
7684
7685            pkgSetting.setTimeStamp(scanFileTime);
7686
7687            // Create idmap files for pairs of (packages, overlay packages).
7688            // Note: "android", ie framework-res.apk, is handled by native layers.
7689            if (pkg.mOverlayTarget != null) {
7690                // This is an overlay package.
7691                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7692                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7693                        mOverlays.put(pkg.mOverlayTarget,
7694                                new ArrayMap<String, PackageParser.Package>());
7695                    }
7696                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7697                    map.put(pkg.packageName, pkg);
7698                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7699                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7700                        createIdmapFailed = true;
7701                    }
7702                }
7703            } else if (mOverlays.containsKey(pkg.packageName) &&
7704                    !pkg.packageName.equals("android")) {
7705                // This is a regular package, with one or more known overlay packages.
7706                createIdmapsForPackageLI(pkg);
7707            }
7708        }
7709
7710        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7711
7712        if (createIdmapFailed) {
7713            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7714                    "scanPackageLI failed to createIdmap");
7715        }
7716        return pkg;
7717    }
7718
7719    /**
7720     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7721     * is derived purely on the basis of the contents of {@code scanFile} and
7722     * {@code cpuAbiOverride}.
7723     *
7724     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7725     */
7726    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7727                                 String cpuAbiOverride, boolean extractLibs)
7728            throws PackageManagerException {
7729        // TODO: We can probably be smarter about this stuff. For installed apps,
7730        // we can calculate this information at install time once and for all. For
7731        // system apps, we can probably assume that this information doesn't change
7732        // after the first boot scan. As things stand, we do lots of unnecessary work.
7733
7734        // Give ourselves some initial paths; we'll come back for another
7735        // pass once we've determined ABI below.
7736        setNativeLibraryPaths(pkg);
7737
7738        // We would never need to extract libs for forward-locked and external packages,
7739        // since the container service will do it for us. We shouldn't attempt to
7740        // extract libs from system app when it was not updated.
7741        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7742                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7743            extractLibs = false;
7744        }
7745
7746        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7747        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7748
7749        NativeLibraryHelper.Handle handle = null;
7750        try {
7751            handle = NativeLibraryHelper.Handle.create(pkg);
7752            // TODO(multiArch): This can be null for apps that didn't go through the
7753            // usual installation process. We can calculate it again, like we
7754            // do during install time.
7755            //
7756            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7757            // unnecessary.
7758            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7759
7760            // Null out the abis so that they can be recalculated.
7761            pkg.applicationInfo.primaryCpuAbi = null;
7762            pkg.applicationInfo.secondaryCpuAbi = null;
7763            if (isMultiArch(pkg.applicationInfo)) {
7764                // Warn if we've set an abiOverride for multi-lib packages..
7765                // By definition, we need to copy both 32 and 64 bit libraries for
7766                // such packages.
7767                if (pkg.cpuAbiOverride != null
7768                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7769                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7770                }
7771
7772                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7773                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7774                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7775                    if (extractLibs) {
7776                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7777                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7778                                useIsaSpecificSubdirs);
7779                    } else {
7780                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7781                    }
7782                }
7783
7784                maybeThrowExceptionForMultiArchCopy(
7785                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7786
7787                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7788                    if (extractLibs) {
7789                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7790                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7791                                useIsaSpecificSubdirs);
7792                    } else {
7793                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7794                    }
7795                }
7796
7797                maybeThrowExceptionForMultiArchCopy(
7798                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7799
7800                if (abi64 >= 0) {
7801                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7802                }
7803
7804                if (abi32 >= 0) {
7805                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7806                    if (abi64 >= 0) {
7807                        pkg.applicationInfo.secondaryCpuAbi = abi;
7808                    } else {
7809                        pkg.applicationInfo.primaryCpuAbi = abi;
7810                    }
7811                }
7812            } else {
7813                String[] abiList = (cpuAbiOverride != null) ?
7814                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7815
7816                // Enable gross and lame hacks for apps that are built with old
7817                // SDK tools. We must scan their APKs for renderscript bitcode and
7818                // not launch them if it's present. Don't bother checking on devices
7819                // that don't have 64 bit support.
7820                boolean needsRenderScriptOverride = false;
7821                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7822                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7823                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7824                    needsRenderScriptOverride = true;
7825                }
7826
7827                final int copyRet;
7828                if (extractLibs) {
7829                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7830                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7831                } else {
7832                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7833                }
7834
7835                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7836                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7837                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7838                }
7839
7840                if (copyRet >= 0) {
7841                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7842                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7843                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7844                } else if (needsRenderScriptOverride) {
7845                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7846                }
7847            }
7848        } catch (IOException ioe) {
7849            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7850        } finally {
7851            IoUtils.closeQuietly(handle);
7852        }
7853
7854        // Now that we've calculated the ABIs and determined if it's an internal app,
7855        // we will go ahead and populate the nativeLibraryPath.
7856        setNativeLibraryPaths(pkg);
7857    }
7858
7859    /**
7860     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7861     * i.e, so that all packages can be run inside a single process if required.
7862     *
7863     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7864     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7865     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7866     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7867     * updating a package that belongs to a shared user.
7868     *
7869     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7870     * adds unnecessary complexity.
7871     */
7872    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7873            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7874            boolean bootComplete) {
7875        String requiredInstructionSet = null;
7876        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7877            requiredInstructionSet = VMRuntime.getInstructionSet(
7878                     scannedPackage.applicationInfo.primaryCpuAbi);
7879        }
7880
7881        PackageSetting requirer = null;
7882        for (PackageSetting ps : packagesForUser) {
7883            // If packagesForUser contains scannedPackage, we skip it. This will happen
7884            // when scannedPackage is an update of an existing package. Without this check,
7885            // we will never be able to change the ABI of any package belonging to a shared
7886            // user, even if it's compatible with other packages.
7887            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7888                if (ps.primaryCpuAbiString == null) {
7889                    continue;
7890                }
7891
7892                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7893                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7894                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7895                    // this but there's not much we can do.
7896                    String errorMessage = "Instruction set mismatch, "
7897                            + ((requirer == null) ? "[caller]" : requirer)
7898                            + " requires " + requiredInstructionSet + " whereas " + ps
7899                            + " requires " + instructionSet;
7900                    Slog.w(TAG, errorMessage);
7901                }
7902
7903                if (requiredInstructionSet == null) {
7904                    requiredInstructionSet = instructionSet;
7905                    requirer = ps;
7906                }
7907            }
7908        }
7909
7910        if (requiredInstructionSet != null) {
7911            String adjustedAbi;
7912            if (requirer != null) {
7913                // requirer != null implies that either scannedPackage was null or that scannedPackage
7914                // did not require an ABI, in which case we have to adjust scannedPackage to match
7915                // the ABI of the set (which is the same as requirer's ABI)
7916                adjustedAbi = requirer.primaryCpuAbiString;
7917                if (scannedPackage != null) {
7918                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7919                }
7920            } else {
7921                // requirer == null implies that we're updating all ABIs in the set to
7922                // match scannedPackage.
7923                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7924            }
7925
7926            for (PackageSetting ps : packagesForUser) {
7927                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7928                    if (ps.primaryCpuAbiString != null) {
7929                        continue;
7930                    }
7931
7932                    ps.primaryCpuAbiString = adjustedAbi;
7933                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7934                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7935                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7936
7937                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7938
7939                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7940                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7941                                bootComplete, false /*useJit*/);
7942
7943                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7944                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7945                            ps.primaryCpuAbiString = null;
7946                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7947                            return;
7948                        } else {
7949                            mInstaller.rmdex(ps.codePathString,
7950                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7951                        }
7952                    }
7953                }
7954            }
7955        }
7956    }
7957
7958    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7959        synchronized (mPackages) {
7960            mResolverReplaced = true;
7961            // Set up information for custom user intent resolution activity.
7962            mResolveActivity.applicationInfo = pkg.applicationInfo;
7963            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7964            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7965            mResolveActivity.processName = pkg.applicationInfo.packageName;
7966            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7967            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7968                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7969            mResolveActivity.theme = 0;
7970            mResolveActivity.exported = true;
7971            mResolveActivity.enabled = true;
7972            mResolveInfo.activityInfo = mResolveActivity;
7973            mResolveInfo.priority = 0;
7974            mResolveInfo.preferredOrder = 0;
7975            mResolveInfo.match = 0;
7976            mResolveComponentName = mCustomResolverComponentName;
7977            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7978                    mResolveComponentName);
7979        }
7980    }
7981
7982    private static String calculateBundledApkRoot(final String codePathString) {
7983        final File codePath = new File(codePathString);
7984        final File codeRoot;
7985        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7986            codeRoot = Environment.getRootDirectory();
7987        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7988            codeRoot = Environment.getOemDirectory();
7989        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7990            codeRoot = Environment.getVendorDirectory();
7991        } else {
7992            // Unrecognized code path; take its top real segment as the apk root:
7993            // e.g. /something/app/blah.apk => /something
7994            try {
7995                File f = codePath.getCanonicalFile();
7996                File parent = f.getParentFile();    // non-null because codePath is a file
7997                File tmp;
7998                while ((tmp = parent.getParentFile()) != null) {
7999                    f = parent;
8000                    parent = tmp;
8001                }
8002                codeRoot = f;
8003                Slog.w(TAG, "Unrecognized code path "
8004                        + codePath + " - using " + codeRoot);
8005            } catch (IOException e) {
8006                // Can't canonicalize the code path -- shenanigans?
8007                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8008                return Environment.getRootDirectory().getPath();
8009            }
8010        }
8011        return codeRoot.getPath();
8012    }
8013
8014    /**
8015     * Derive and set the location of native libraries for the given package,
8016     * which varies depending on where and how the package was installed.
8017     */
8018    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8019        final ApplicationInfo info = pkg.applicationInfo;
8020        final String codePath = pkg.codePath;
8021        final File codeFile = new File(codePath);
8022        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8023        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8024
8025        info.nativeLibraryRootDir = null;
8026        info.nativeLibraryRootRequiresIsa = false;
8027        info.nativeLibraryDir = null;
8028        info.secondaryNativeLibraryDir = null;
8029
8030        if (isApkFile(codeFile)) {
8031            // Monolithic install
8032            if (bundledApp) {
8033                // If "/system/lib64/apkname" exists, assume that is the per-package
8034                // native library directory to use; otherwise use "/system/lib/apkname".
8035                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8036                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8037                        getPrimaryInstructionSet(info));
8038
8039                // This is a bundled system app so choose the path based on the ABI.
8040                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8041                // is just the default path.
8042                final String apkName = deriveCodePathName(codePath);
8043                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8044                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8045                        apkName).getAbsolutePath();
8046
8047                if (info.secondaryCpuAbi != null) {
8048                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8049                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8050                            secondaryLibDir, apkName).getAbsolutePath();
8051                }
8052            } else if (asecApp) {
8053                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8054                        .getAbsolutePath();
8055            } else {
8056                final String apkName = deriveCodePathName(codePath);
8057                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8058                        .getAbsolutePath();
8059            }
8060
8061            info.nativeLibraryRootRequiresIsa = false;
8062            info.nativeLibraryDir = info.nativeLibraryRootDir;
8063        } else {
8064            // Cluster install
8065            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8066            info.nativeLibraryRootRequiresIsa = true;
8067
8068            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8069                    getPrimaryInstructionSet(info)).getAbsolutePath();
8070
8071            if (info.secondaryCpuAbi != null) {
8072                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8073                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8074            }
8075        }
8076    }
8077
8078    /**
8079     * Calculate the abis and roots for a bundled app. These can uniquely
8080     * be determined from the contents of the system partition, i.e whether
8081     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8082     * of this information, and instead assume that the system was built
8083     * sensibly.
8084     */
8085    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8086                                           PackageSetting pkgSetting) {
8087        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8088
8089        // If "/system/lib64/apkname" exists, assume that is the per-package
8090        // native library directory to use; otherwise use "/system/lib/apkname".
8091        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8092        setBundledAppAbi(pkg, apkRoot, apkName);
8093        // pkgSetting might be null during rescan following uninstall of updates
8094        // to a bundled app, so accommodate that possibility.  The settings in
8095        // that case will be established later from the parsed package.
8096        //
8097        // If the settings aren't null, sync them up with what we've just derived.
8098        // note that apkRoot isn't stored in the package settings.
8099        if (pkgSetting != null) {
8100            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8101            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8102        }
8103    }
8104
8105    /**
8106     * Deduces the ABI of a bundled app and sets the relevant fields on the
8107     * parsed pkg object.
8108     *
8109     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8110     *        under which system libraries are installed.
8111     * @param apkName the name of the installed package.
8112     */
8113    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8114        final File codeFile = new File(pkg.codePath);
8115
8116        final boolean has64BitLibs;
8117        final boolean has32BitLibs;
8118        if (isApkFile(codeFile)) {
8119            // Monolithic install
8120            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8121            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8122        } else {
8123            // Cluster install
8124            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8125            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8126                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8127                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8128                has64BitLibs = (new File(rootDir, isa)).exists();
8129            } else {
8130                has64BitLibs = false;
8131            }
8132            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8133                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8134                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8135                has32BitLibs = (new File(rootDir, isa)).exists();
8136            } else {
8137                has32BitLibs = false;
8138            }
8139        }
8140
8141        if (has64BitLibs && !has32BitLibs) {
8142            // The package has 64 bit libs, but not 32 bit libs. Its primary
8143            // ABI should be 64 bit. We can safely assume here that the bundled
8144            // native libraries correspond to the most preferred ABI in the list.
8145
8146            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8147            pkg.applicationInfo.secondaryCpuAbi = null;
8148        } else if (has32BitLibs && !has64BitLibs) {
8149            // The package has 32 bit libs but not 64 bit libs. Its primary
8150            // ABI should be 32 bit.
8151
8152            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8153            pkg.applicationInfo.secondaryCpuAbi = null;
8154        } else if (has32BitLibs && has64BitLibs) {
8155            // The application has both 64 and 32 bit bundled libraries. We check
8156            // here that the app declares multiArch support, and warn if it doesn't.
8157            //
8158            // We will be lenient here and record both ABIs. The primary will be the
8159            // ABI that's higher on the list, i.e, a device that's configured to prefer
8160            // 64 bit apps will see a 64 bit primary ABI,
8161
8162            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8163                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8164            }
8165
8166            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8167                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8168                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8169            } else {
8170                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8171                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8172            }
8173        } else {
8174            pkg.applicationInfo.primaryCpuAbi = null;
8175            pkg.applicationInfo.secondaryCpuAbi = null;
8176        }
8177    }
8178
8179    private void killApplication(String pkgName, int appId, String reason) {
8180        // Request the ActivityManager to kill the process(only for existing packages)
8181        // so that we do not end up in a confused state while the user is still using the older
8182        // version of the application while the new one gets installed.
8183        IActivityManager am = ActivityManagerNative.getDefault();
8184        if (am != null) {
8185            try {
8186                am.killApplicationWithAppId(pkgName, appId, reason);
8187            } catch (RemoteException e) {
8188            }
8189        }
8190    }
8191
8192    void removePackageLI(PackageSetting ps, boolean chatty) {
8193        if (DEBUG_INSTALL) {
8194            if (chatty)
8195                Log.d(TAG, "Removing package " + ps.name);
8196        }
8197
8198        // writer
8199        synchronized (mPackages) {
8200            mPackages.remove(ps.name);
8201            final PackageParser.Package pkg = ps.pkg;
8202            if (pkg != null) {
8203                cleanPackageDataStructuresLILPw(pkg, chatty);
8204            }
8205        }
8206    }
8207
8208    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8209        if (DEBUG_INSTALL) {
8210            if (chatty)
8211                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8212        }
8213
8214        // writer
8215        synchronized (mPackages) {
8216            mPackages.remove(pkg.applicationInfo.packageName);
8217            cleanPackageDataStructuresLILPw(pkg, chatty);
8218        }
8219    }
8220
8221    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8222        int N = pkg.providers.size();
8223        StringBuilder r = null;
8224        int i;
8225        for (i=0; i<N; i++) {
8226            PackageParser.Provider p = pkg.providers.get(i);
8227            mProviders.removeProvider(p);
8228            if (p.info.authority == null) {
8229
8230                /* There was another ContentProvider with this authority when
8231                 * this app was installed so this authority is null,
8232                 * Ignore it as we don't have to unregister the provider.
8233                 */
8234                continue;
8235            }
8236            String names[] = p.info.authority.split(";");
8237            for (int j = 0; j < names.length; j++) {
8238                if (mProvidersByAuthority.get(names[j]) == p) {
8239                    mProvidersByAuthority.remove(names[j]);
8240                    if (DEBUG_REMOVE) {
8241                        if (chatty)
8242                            Log.d(TAG, "Unregistered content provider: " + names[j]
8243                                    + ", className = " + p.info.name + ", isSyncable = "
8244                                    + p.info.isSyncable);
8245                    }
8246                }
8247            }
8248            if (DEBUG_REMOVE && chatty) {
8249                if (r == null) {
8250                    r = new StringBuilder(256);
8251                } else {
8252                    r.append(' ');
8253                }
8254                r.append(p.info.name);
8255            }
8256        }
8257        if (r != null) {
8258            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8259        }
8260
8261        N = pkg.services.size();
8262        r = null;
8263        for (i=0; i<N; i++) {
8264            PackageParser.Service s = pkg.services.get(i);
8265            mServices.removeService(s);
8266            if (chatty) {
8267                if (r == null) {
8268                    r = new StringBuilder(256);
8269                } else {
8270                    r.append(' ');
8271                }
8272                r.append(s.info.name);
8273            }
8274        }
8275        if (r != null) {
8276            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8277        }
8278
8279        N = pkg.receivers.size();
8280        r = null;
8281        for (i=0; i<N; i++) {
8282            PackageParser.Activity a = pkg.receivers.get(i);
8283            mReceivers.removeActivity(a, "receiver");
8284            if (DEBUG_REMOVE && chatty) {
8285                if (r == null) {
8286                    r = new StringBuilder(256);
8287                } else {
8288                    r.append(' ');
8289                }
8290                r.append(a.info.name);
8291            }
8292        }
8293        if (r != null) {
8294            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8295        }
8296
8297        N = pkg.activities.size();
8298        r = null;
8299        for (i=0; i<N; i++) {
8300            PackageParser.Activity a = pkg.activities.get(i);
8301            mActivities.removeActivity(a, "activity");
8302            if (DEBUG_REMOVE && chatty) {
8303                if (r == null) {
8304                    r = new StringBuilder(256);
8305                } else {
8306                    r.append(' ');
8307                }
8308                r.append(a.info.name);
8309            }
8310        }
8311        if (r != null) {
8312            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8313        }
8314
8315        N = pkg.permissions.size();
8316        r = null;
8317        for (i=0; i<N; i++) {
8318            PackageParser.Permission p = pkg.permissions.get(i);
8319            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8320            if (bp == null) {
8321                bp = mSettings.mPermissionTrees.get(p.info.name);
8322            }
8323            if (bp != null && bp.perm == p) {
8324                bp.perm = null;
8325                if (DEBUG_REMOVE && chatty) {
8326                    if (r == null) {
8327                        r = new StringBuilder(256);
8328                    } else {
8329                        r.append(' ');
8330                    }
8331                    r.append(p.info.name);
8332                }
8333            }
8334            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8335                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8336                if (appOpPerms != null) {
8337                    appOpPerms.remove(pkg.packageName);
8338                }
8339            }
8340        }
8341        if (r != null) {
8342            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8343        }
8344
8345        N = pkg.requestedPermissions.size();
8346        r = null;
8347        for (i=0; i<N; i++) {
8348            String perm = pkg.requestedPermissions.get(i);
8349            BasePermission bp = mSettings.mPermissions.get(perm);
8350            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8351                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8352                if (appOpPerms != null) {
8353                    appOpPerms.remove(pkg.packageName);
8354                    if (appOpPerms.isEmpty()) {
8355                        mAppOpPermissionPackages.remove(perm);
8356                    }
8357                }
8358            }
8359        }
8360        if (r != null) {
8361            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8362        }
8363
8364        N = pkg.instrumentation.size();
8365        r = null;
8366        for (i=0; i<N; i++) {
8367            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8368            mInstrumentation.remove(a.getComponentName());
8369            if (DEBUG_REMOVE && chatty) {
8370                if (r == null) {
8371                    r = new StringBuilder(256);
8372                } else {
8373                    r.append(' ');
8374                }
8375                r.append(a.info.name);
8376            }
8377        }
8378        if (r != null) {
8379            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8380        }
8381
8382        r = null;
8383        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8384            // Only system apps can hold shared libraries.
8385            if (pkg.libraryNames != null) {
8386                for (i=0; i<pkg.libraryNames.size(); i++) {
8387                    String name = pkg.libraryNames.get(i);
8388                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8389                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8390                        mSharedLibraries.remove(name);
8391                        if (DEBUG_REMOVE && chatty) {
8392                            if (r == null) {
8393                                r = new StringBuilder(256);
8394                            } else {
8395                                r.append(' ');
8396                            }
8397                            r.append(name);
8398                        }
8399                    }
8400                }
8401            }
8402        }
8403        if (r != null) {
8404            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8405        }
8406    }
8407
8408    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8409        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8410            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8411                return true;
8412            }
8413        }
8414        return false;
8415    }
8416
8417    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8418    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8419    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8420
8421    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8422            int flags) {
8423        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8424        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8425    }
8426
8427    private void updatePermissionsLPw(String changingPkg,
8428            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8429        // Make sure there are no dangling permission trees.
8430        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8431        while (it.hasNext()) {
8432            final BasePermission bp = it.next();
8433            if (bp.packageSetting == null) {
8434                // We may not yet have parsed the package, so just see if
8435                // we still know about its settings.
8436                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8437            }
8438            if (bp.packageSetting == null) {
8439                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8440                        + " from package " + bp.sourcePackage);
8441                it.remove();
8442            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8443                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8444                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8445                            + " from package " + bp.sourcePackage);
8446                    flags |= UPDATE_PERMISSIONS_ALL;
8447                    it.remove();
8448                }
8449            }
8450        }
8451
8452        // Make sure all dynamic permissions have been assigned to a package,
8453        // and make sure there are no dangling permissions.
8454        it = mSettings.mPermissions.values().iterator();
8455        while (it.hasNext()) {
8456            final BasePermission bp = it.next();
8457            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8458                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8459                        + bp.name + " pkg=" + bp.sourcePackage
8460                        + " info=" + bp.pendingInfo);
8461                if (bp.packageSetting == null && bp.pendingInfo != null) {
8462                    final BasePermission tree = findPermissionTreeLP(bp.name);
8463                    if (tree != null && tree.perm != null) {
8464                        bp.packageSetting = tree.packageSetting;
8465                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8466                                new PermissionInfo(bp.pendingInfo));
8467                        bp.perm.info.packageName = tree.perm.info.packageName;
8468                        bp.perm.info.name = bp.name;
8469                        bp.uid = tree.uid;
8470                    }
8471                }
8472            }
8473            if (bp.packageSetting == null) {
8474                // We may not yet have parsed the package, so just see if
8475                // we still know about its settings.
8476                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8477            }
8478            if (bp.packageSetting == null) {
8479                Slog.w(TAG, "Removing dangling permission: " + bp.name
8480                        + " from package " + bp.sourcePackage);
8481                it.remove();
8482            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8483                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8484                    Slog.i(TAG, "Removing old permission: " + bp.name
8485                            + " from package " + bp.sourcePackage);
8486                    flags |= UPDATE_PERMISSIONS_ALL;
8487                    it.remove();
8488                }
8489            }
8490        }
8491
8492        // Now update the permissions for all packages, in particular
8493        // replace the granted permissions of the system packages.
8494        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8495            for (PackageParser.Package pkg : mPackages.values()) {
8496                if (pkg != pkgInfo) {
8497                    // Only replace for packages on requested volume
8498                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8499                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8500                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8501                    grantPermissionsLPw(pkg, replace, changingPkg);
8502                }
8503            }
8504        }
8505
8506        if (pkgInfo != null) {
8507            // Only replace for packages on requested volume
8508            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8509            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8510                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8511            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8512        }
8513    }
8514
8515    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8516            String packageOfInterest) {
8517        // IMPORTANT: There are two types of permissions: install and runtime.
8518        // Install time permissions are granted when the app is installed to
8519        // all device users and users added in the future. Runtime permissions
8520        // are granted at runtime explicitly to specific users. Normal and signature
8521        // protected permissions are install time permissions. Dangerous permissions
8522        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8523        // otherwise they are runtime permissions. This function does not manage
8524        // runtime permissions except for the case an app targeting Lollipop MR1
8525        // being upgraded to target a newer SDK, in which case dangerous permissions
8526        // are transformed from install time to runtime ones.
8527
8528        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8529        if (ps == null) {
8530            return;
8531        }
8532
8533        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8534
8535        PermissionsState permissionsState = ps.getPermissionsState();
8536        PermissionsState origPermissions = permissionsState;
8537
8538        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8539
8540        boolean runtimePermissionsRevoked = false;
8541        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8542
8543        boolean changedInstallPermission = false;
8544
8545        if (replace) {
8546            ps.installPermissionsFixed = false;
8547            if (!ps.isSharedUser()) {
8548                origPermissions = new PermissionsState(permissionsState);
8549                permissionsState.reset();
8550            } else {
8551                // We need to know only about runtime permission changes since the
8552                // calling code always writes the install permissions state but
8553                // the runtime ones are written only if changed. The only cases of
8554                // changed runtime permissions here are promotion of an install to
8555                // runtime and revocation of a runtime from a shared user.
8556                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8557                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8558                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8559                    runtimePermissionsRevoked = true;
8560                }
8561            }
8562        }
8563
8564        permissionsState.setGlobalGids(mGlobalGids);
8565
8566        final int N = pkg.requestedPermissions.size();
8567        for (int i=0; i<N; i++) {
8568            final String name = pkg.requestedPermissions.get(i);
8569            final BasePermission bp = mSettings.mPermissions.get(name);
8570
8571            if (DEBUG_INSTALL) {
8572                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8573            }
8574
8575            if (bp == null || bp.packageSetting == null) {
8576                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8577                    Slog.w(TAG, "Unknown permission " + name
8578                            + " in package " + pkg.packageName);
8579                }
8580                continue;
8581            }
8582
8583            final String perm = bp.name;
8584            boolean allowedSig = false;
8585            int grant = GRANT_DENIED;
8586
8587            // Keep track of app op permissions.
8588            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8589                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8590                if (pkgs == null) {
8591                    pkgs = new ArraySet<>();
8592                    mAppOpPermissionPackages.put(bp.name, pkgs);
8593                }
8594                pkgs.add(pkg.packageName);
8595            }
8596
8597            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8598            switch (level) {
8599                case PermissionInfo.PROTECTION_NORMAL: {
8600                    // For all apps normal permissions are install time ones.
8601                    grant = GRANT_INSTALL;
8602                } break;
8603
8604                case PermissionInfo.PROTECTION_DANGEROUS: {
8605                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8606                        // For legacy apps dangerous permissions are install time ones.
8607                        grant = GRANT_INSTALL_LEGACY;
8608                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8609                        // For legacy apps that became modern, install becomes runtime.
8610                        grant = GRANT_UPGRADE;
8611                    } else if (mPromoteSystemApps
8612                            && isSystemApp(ps)
8613                            && mExistingSystemPackages.contains(ps.name)) {
8614                        // For legacy system apps, install becomes runtime.
8615                        // We cannot check hasInstallPermission() for system apps since those
8616                        // permissions were granted implicitly and not persisted pre-M.
8617                        grant = GRANT_UPGRADE;
8618                    } else {
8619                        // For modern apps keep runtime permissions unchanged.
8620                        grant = GRANT_RUNTIME;
8621                    }
8622                } break;
8623
8624                case PermissionInfo.PROTECTION_SIGNATURE: {
8625                    // For all apps signature permissions are install time ones.
8626                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8627                    if (allowedSig) {
8628                        grant = GRANT_INSTALL;
8629                    }
8630                } break;
8631            }
8632
8633            if (DEBUG_INSTALL) {
8634                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8635            }
8636
8637            if (grant != GRANT_DENIED) {
8638                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8639                    // If this is an existing, non-system package, then
8640                    // we can't add any new permissions to it.
8641                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8642                        // Except...  if this is a permission that was added
8643                        // to the platform (note: need to only do this when
8644                        // updating the platform).
8645                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8646                            grant = GRANT_DENIED;
8647                        }
8648                    }
8649                }
8650
8651                switch (grant) {
8652                    case GRANT_INSTALL: {
8653                        // Revoke this as runtime permission to handle the case of
8654                        // a runtime permission being downgraded to an install one.
8655                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8656                            if (origPermissions.getRuntimePermissionState(
8657                                    bp.name, userId) != null) {
8658                                // Revoke the runtime permission and clear the flags.
8659                                origPermissions.revokeRuntimePermission(bp, userId);
8660                                origPermissions.updatePermissionFlags(bp, userId,
8661                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8662                                // If we revoked a permission permission, we have to write.
8663                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8664                                        changedRuntimePermissionUserIds, userId);
8665                            }
8666                        }
8667                        // Grant an install permission.
8668                        if (permissionsState.grantInstallPermission(bp) !=
8669                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8670                            changedInstallPermission = true;
8671                        }
8672                    } break;
8673
8674                    case GRANT_INSTALL_LEGACY: {
8675                        // Grant an install permission.
8676                        if (permissionsState.grantInstallPermission(bp) !=
8677                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8678                            changedInstallPermission = true;
8679                        }
8680                    } break;
8681
8682                    case GRANT_RUNTIME: {
8683                        // Grant previously granted runtime permissions.
8684                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8685                            PermissionState permissionState = origPermissions
8686                                    .getRuntimePermissionState(bp.name, userId);
8687                            final int flags = permissionState != null
8688                                    ? permissionState.getFlags() : 0;
8689                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8690                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8691                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8692                                    // If we cannot put the permission as it was, we have to write.
8693                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8694                                            changedRuntimePermissionUserIds, userId);
8695                                }
8696                            }
8697                            // Propagate the permission flags.
8698                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8699                        }
8700                    } break;
8701
8702                    case GRANT_UPGRADE: {
8703                        // Grant runtime permissions for a previously held install permission.
8704                        PermissionState permissionState = origPermissions
8705                                .getInstallPermissionState(bp.name);
8706                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8707
8708                        if (origPermissions.revokeInstallPermission(bp)
8709                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8710                            // We will be transferring the permission flags, so clear them.
8711                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8712                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8713                            changedInstallPermission = true;
8714                        }
8715
8716                        // If the permission is not to be promoted to runtime we ignore it and
8717                        // also its other flags as they are not applicable to install permissions.
8718                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8719                            for (int userId : currentUserIds) {
8720                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8721                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8722                                    // Transfer the permission flags.
8723                                    permissionsState.updatePermissionFlags(bp, userId,
8724                                            flags, flags);
8725                                    // If we granted the permission, we have to write.
8726                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8727                                            changedRuntimePermissionUserIds, userId);
8728                                }
8729                            }
8730                        }
8731                    } break;
8732
8733                    default: {
8734                        if (packageOfInterest == null
8735                                || packageOfInterest.equals(pkg.packageName)) {
8736                            Slog.w(TAG, "Not granting permission " + perm
8737                                    + " to package " + pkg.packageName
8738                                    + " because it was previously installed without");
8739                        }
8740                    } break;
8741                }
8742            } else {
8743                if (permissionsState.revokeInstallPermission(bp) !=
8744                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8745                    // Also drop the permission flags.
8746                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8747                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8748                    changedInstallPermission = true;
8749                    Slog.i(TAG, "Un-granting permission " + perm
8750                            + " from package " + pkg.packageName
8751                            + " (protectionLevel=" + bp.protectionLevel
8752                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8753                            + ")");
8754                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8755                    // Don't print warning for app op permissions, since it is fine for them
8756                    // not to be granted, there is a UI for the user to decide.
8757                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8758                        Slog.w(TAG, "Not granting permission " + perm
8759                                + " to package " + pkg.packageName
8760                                + " (protectionLevel=" + bp.protectionLevel
8761                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8762                                + ")");
8763                    }
8764                }
8765            }
8766        }
8767
8768        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8769                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8770            // This is the first that we have heard about this package, so the
8771            // permissions we have now selected are fixed until explicitly
8772            // changed.
8773            ps.installPermissionsFixed = true;
8774        }
8775
8776        // Persist the runtime permissions state for users with changes. If permissions
8777        // were revoked because no app in the shared user declares them we have to
8778        // write synchronously to avoid losing runtime permissions state.
8779        for (int userId : changedRuntimePermissionUserIds) {
8780            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8781        }
8782
8783        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8784    }
8785
8786    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8787        boolean allowed = false;
8788        final int NP = PackageParser.NEW_PERMISSIONS.length;
8789        for (int ip=0; ip<NP; ip++) {
8790            final PackageParser.NewPermissionInfo npi
8791                    = PackageParser.NEW_PERMISSIONS[ip];
8792            if (npi.name.equals(perm)
8793                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8794                allowed = true;
8795                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8796                        + pkg.packageName);
8797                break;
8798            }
8799        }
8800        return allowed;
8801    }
8802
8803    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8804            BasePermission bp, PermissionsState origPermissions) {
8805        boolean allowed;
8806        allowed = (compareSignatures(
8807                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8808                        == PackageManager.SIGNATURE_MATCH)
8809                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8810                        == PackageManager.SIGNATURE_MATCH);
8811        if (!allowed && (bp.protectionLevel
8812                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8813            if (isSystemApp(pkg)) {
8814                // For updated system applications, a system permission
8815                // is granted only if it had been defined by the original application.
8816                if (pkg.isUpdatedSystemApp()) {
8817                    final PackageSetting sysPs = mSettings
8818                            .getDisabledSystemPkgLPr(pkg.packageName);
8819                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8820                        // If the original was granted this permission, we take
8821                        // that grant decision as read and propagate it to the
8822                        // update.
8823                        if (sysPs.isPrivileged()) {
8824                            allowed = true;
8825                        }
8826                    } else {
8827                        // The system apk may have been updated with an older
8828                        // version of the one on the data partition, but which
8829                        // granted a new system permission that it didn't have
8830                        // before.  In this case we do want to allow the app to
8831                        // now get the new permission if the ancestral apk is
8832                        // privileged to get it.
8833                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8834                            for (int j=0;
8835                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8836                                if (perm.equals(
8837                                        sysPs.pkg.requestedPermissions.get(j))) {
8838                                    allowed = true;
8839                                    break;
8840                                }
8841                            }
8842                        }
8843                    }
8844                } else {
8845                    allowed = isPrivilegedApp(pkg);
8846                }
8847            }
8848        }
8849        if (!allowed) {
8850            if (!allowed && (bp.protectionLevel
8851                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8852                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8853                // If this was a previously normal/dangerous permission that got moved
8854                // to a system permission as part of the runtime permission redesign, then
8855                // we still want to blindly grant it to old apps.
8856                allowed = true;
8857            }
8858            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8859                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8860                // If this permission is to be granted to the system installer and
8861                // this app is an installer, then it gets the permission.
8862                allowed = true;
8863            }
8864            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8865                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8866                // If this permission is to be granted to the system verifier and
8867                // this app is a verifier, then it gets the permission.
8868                allowed = true;
8869            }
8870            if (!allowed && (bp.protectionLevel
8871                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8872                    && isSystemApp(pkg)) {
8873                // Any pre-installed system app is allowed to get this permission.
8874                allowed = true;
8875            }
8876            if (!allowed && (bp.protectionLevel
8877                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8878                // For development permissions, a development permission
8879                // is granted only if it was already granted.
8880                allowed = origPermissions.hasInstallPermission(perm);
8881            }
8882        }
8883        return allowed;
8884    }
8885
8886    final class ActivityIntentResolver
8887            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8888        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8889                boolean defaultOnly, int userId) {
8890            if (!sUserManager.exists(userId)) return null;
8891            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8892            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8893        }
8894
8895        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8896                int userId) {
8897            if (!sUserManager.exists(userId)) return null;
8898            mFlags = flags;
8899            return super.queryIntent(intent, resolvedType,
8900                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8901        }
8902
8903        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8904                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8905            if (!sUserManager.exists(userId)) return null;
8906            if (packageActivities == null) {
8907                return null;
8908            }
8909            mFlags = flags;
8910            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8911            final int N = packageActivities.size();
8912            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8913                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8914
8915            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8916            for (int i = 0; i < N; ++i) {
8917                intentFilters = packageActivities.get(i).intents;
8918                if (intentFilters != null && intentFilters.size() > 0) {
8919                    PackageParser.ActivityIntentInfo[] array =
8920                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8921                    intentFilters.toArray(array);
8922                    listCut.add(array);
8923                }
8924            }
8925            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8926        }
8927
8928        public final void addActivity(PackageParser.Activity a, String type) {
8929            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8930            mActivities.put(a.getComponentName(), a);
8931            if (DEBUG_SHOW_INFO)
8932                Log.v(
8933                TAG, "  " + type + " " +
8934                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8935            if (DEBUG_SHOW_INFO)
8936                Log.v(TAG, "    Class=" + a.info.name);
8937            final int NI = a.intents.size();
8938            for (int j=0; j<NI; j++) {
8939                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8940                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8941                    intent.setPriority(0);
8942                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8943                            + a.className + " with priority > 0, forcing to 0");
8944                }
8945                if (DEBUG_SHOW_INFO) {
8946                    Log.v(TAG, "    IntentFilter:");
8947                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8948                }
8949                if (!intent.debugCheck()) {
8950                    Log.w(TAG, "==> For Activity " + a.info.name);
8951                }
8952                addFilter(intent);
8953            }
8954        }
8955
8956        public final void removeActivity(PackageParser.Activity a, String type) {
8957            mActivities.remove(a.getComponentName());
8958            if (DEBUG_SHOW_INFO) {
8959                Log.v(TAG, "  " + type + " "
8960                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8961                                : a.info.name) + ":");
8962                Log.v(TAG, "    Class=" + a.info.name);
8963            }
8964            final int NI = a.intents.size();
8965            for (int j=0; j<NI; j++) {
8966                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8967                if (DEBUG_SHOW_INFO) {
8968                    Log.v(TAG, "    IntentFilter:");
8969                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8970                }
8971                removeFilter(intent);
8972            }
8973        }
8974
8975        @Override
8976        protected boolean allowFilterResult(
8977                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8978            ActivityInfo filterAi = filter.activity.info;
8979            for (int i=dest.size()-1; i>=0; i--) {
8980                ActivityInfo destAi = dest.get(i).activityInfo;
8981                if (destAi.name == filterAi.name
8982                        && destAi.packageName == filterAi.packageName) {
8983                    return false;
8984                }
8985            }
8986            return true;
8987        }
8988
8989        @Override
8990        protected ActivityIntentInfo[] newArray(int size) {
8991            return new ActivityIntentInfo[size];
8992        }
8993
8994        @Override
8995        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8996            if (!sUserManager.exists(userId)) return true;
8997            PackageParser.Package p = filter.activity.owner;
8998            if (p != null) {
8999                PackageSetting ps = (PackageSetting)p.mExtras;
9000                if (ps != null) {
9001                    // System apps are never considered stopped for purposes of
9002                    // filtering, because there may be no way for the user to
9003                    // actually re-launch them.
9004                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9005                            && ps.getStopped(userId);
9006                }
9007            }
9008            return false;
9009        }
9010
9011        @Override
9012        protected boolean isPackageForFilter(String packageName,
9013                PackageParser.ActivityIntentInfo info) {
9014            return packageName.equals(info.activity.owner.packageName);
9015        }
9016
9017        @Override
9018        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9019                int match, int userId) {
9020            if (!sUserManager.exists(userId)) return null;
9021            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9022                return null;
9023            }
9024            final PackageParser.Activity activity = info.activity;
9025            if (mSafeMode && (activity.info.applicationInfo.flags
9026                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9027                return null;
9028            }
9029            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9030            if (ps == null) {
9031                return null;
9032            }
9033            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9034                    ps.readUserState(userId), userId);
9035            if (ai == null) {
9036                return null;
9037            }
9038            final ResolveInfo res = new ResolveInfo();
9039            res.activityInfo = ai;
9040            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9041                res.filter = info;
9042            }
9043            if (info != null) {
9044                res.handleAllWebDataURI = info.handleAllWebDataURI();
9045            }
9046            res.priority = info.getPriority();
9047            res.preferredOrder = activity.owner.mPreferredOrder;
9048            //System.out.println("Result: " + res.activityInfo.className +
9049            //                   " = " + res.priority);
9050            res.match = match;
9051            res.isDefault = info.hasDefault;
9052            res.labelRes = info.labelRes;
9053            res.nonLocalizedLabel = info.nonLocalizedLabel;
9054            if (userNeedsBadging(userId)) {
9055                res.noResourceId = true;
9056            } else {
9057                res.icon = info.icon;
9058            }
9059            res.iconResourceId = info.icon;
9060            res.system = res.activityInfo.applicationInfo.isSystemApp();
9061            return res;
9062        }
9063
9064        @Override
9065        protected void sortResults(List<ResolveInfo> results) {
9066            Collections.sort(results, mResolvePrioritySorter);
9067        }
9068
9069        @Override
9070        protected void dumpFilter(PrintWriter out, String prefix,
9071                PackageParser.ActivityIntentInfo filter) {
9072            out.print(prefix); out.print(
9073                    Integer.toHexString(System.identityHashCode(filter.activity)));
9074                    out.print(' ');
9075                    filter.activity.printComponentShortName(out);
9076                    out.print(" filter ");
9077                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9078        }
9079
9080        @Override
9081        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9082            return filter.activity;
9083        }
9084
9085        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9086            PackageParser.Activity activity = (PackageParser.Activity)label;
9087            out.print(prefix); out.print(
9088                    Integer.toHexString(System.identityHashCode(activity)));
9089                    out.print(' ');
9090                    activity.printComponentShortName(out);
9091            if (count > 1) {
9092                out.print(" ("); out.print(count); out.print(" filters)");
9093            }
9094            out.println();
9095        }
9096
9097//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9098//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9099//            final List<ResolveInfo> retList = Lists.newArrayList();
9100//            while (i.hasNext()) {
9101//                final ResolveInfo resolveInfo = i.next();
9102//                if (isEnabledLP(resolveInfo.activityInfo)) {
9103//                    retList.add(resolveInfo);
9104//                }
9105//            }
9106//            return retList;
9107//        }
9108
9109        // Keys are String (activity class name), values are Activity.
9110        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9111                = new ArrayMap<ComponentName, PackageParser.Activity>();
9112        private int mFlags;
9113    }
9114
9115    private final class ServiceIntentResolver
9116            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9117        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9118                boolean defaultOnly, int userId) {
9119            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9120            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9121        }
9122
9123        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9124                int userId) {
9125            if (!sUserManager.exists(userId)) return null;
9126            mFlags = flags;
9127            return super.queryIntent(intent, resolvedType,
9128                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9129        }
9130
9131        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9132                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9133            if (!sUserManager.exists(userId)) return null;
9134            if (packageServices == null) {
9135                return null;
9136            }
9137            mFlags = flags;
9138            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9139            final int N = packageServices.size();
9140            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9141                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9142
9143            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9144            for (int i = 0; i < N; ++i) {
9145                intentFilters = packageServices.get(i).intents;
9146                if (intentFilters != null && intentFilters.size() > 0) {
9147                    PackageParser.ServiceIntentInfo[] array =
9148                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9149                    intentFilters.toArray(array);
9150                    listCut.add(array);
9151                }
9152            }
9153            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9154        }
9155
9156        public final void addService(PackageParser.Service s) {
9157            mServices.put(s.getComponentName(), s);
9158            if (DEBUG_SHOW_INFO) {
9159                Log.v(TAG, "  "
9160                        + (s.info.nonLocalizedLabel != null
9161                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9162                Log.v(TAG, "    Class=" + s.info.name);
9163            }
9164            final int NI = s.intents.size();
9165            int j;
9166            for (j=0; j<NI; j++) {
9167                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9168                if (DEBUG_SHOW_INFO) {
9169                    Log.v(TAG, "    IntentFilter:");
9170                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9171                }
9172                if (!intent.debugCheck()) {
9173                    Log.w(TAG, "==> For Service " + s.info.name);
9174                }
9175                addFilter(intent);
9176            }
9177        }
9178
9179        public final void removeService(PackageParser.Service s) {
9180            mServices.remove(s.getComponentName());
9181            if (DEBUG_SHOW_INFO) {
9182                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9183                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9184                Log.v(TAG, "    Class=" + s.info.name);
9185            }
9186            final int NI = s.intents.size();
9187            int j;
9188            for (j=0; j<NI; j++) {
9189                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9190                if (DEBUG_SHOW_INFO) {
9191                    Log.v(TAG, "    IntentFilter:");
9192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9193                }
9194                removeFilter(intent);
9195            }
9196        }
9197
9198        @Override
9199        protected boolean allowFilterResult(
9200                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9201            ServiceInfo filterSi = filter.service.info;
9202            for (int i=dest.size()-1; i>=0; i--) {
9203                ServiceInfo destAi = dest.get(i).serviceInfo;
9204                if (destAi.name == filterSi.name
9205                        && destAi.packageName == filterSi.packageName) {
9206                    return false;
9207                }
9208            }
9209            return true;
9210        }
9211
9212        @Override
9213        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9214            return new PackageParser.ServiceIntentInfo[size];
9215        }
9216
9217        @Override
9218        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9219            if (!sUserManager.exists(userId)) return true;
9220            PackageParser.Package p = filter.service.owner;
9221            if (p != null) {
9222                PackageSetting ps = (PackageSetting)p.mExtras;
9223                if (ps != null) {
9224                    // System apps are never considered stopped for purposes of
9225                    // filtering, because there may be no way for the user to
9226                    // actually re-launch them.
9227                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9228                            && ps.getStopped(userId);
9229                }
9230            }
9231            return false;
9232        }
9233
9234        @Override
9235        protected boolean isPackageForFilter(String packageName,
9236                PackageParser.ServiceIntentInfo info) {
9237            return packageName.equals(info.service.owner.packageName);
9238        }
9239
9240        @Override
9241        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9242                int match, int userId) {
9243            if (!sUserManager.exists(userId)) return null;
9244            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9245            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9246                return null;
9247            }
9248            final PackageParser.Service service = info.service;
9249            if (mSafeMode && (service.info.applicationInfo.flags
9250                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9251                return null;
9252            }
9253            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9254            if (ps == null) {
9255                return null;
9256            }
9257            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9258                    ps.readUserState(userId), userId);
9259            if (si == null) {
9260                return null;
9261            }
9262            final ResolveInfo res = new ResolveInfo();
9263            res.serviceInfo = si;
9264            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9265                res.filter = filter;
9266            }
9267            res.priority = info.getPriority();
9268            res.preferredOrder = service.owner.mPreferredOrder;
9269            res.match = match;
9270            res.isDefault = info.hasDefault;
9271            res.labelRes = info.labelRes;
9272            res.nonLocalizedLabel = info.nonLocalizedLabel;
9273            res.icon = info.icon;
9274            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9275            return res;
9276        }
9277
9278        @Override
9279        protected void sortResults(List<ResolveInfo> results) {
9280            Collections.sort(results, mResolvePrioritySorter);
9281        }
9282
9283        @Override
9284        protected void dumpFilter(PrintWriter out, String prefix,
9285                PackageParser.ServiceIntentInfo filter) {
9286            out.print(prefix); out.print(
9287                    Integer.toHexString(System.identityHashCode(filter.service)));
9288                    out.print(' ');
9289                    filter.service.printComponentShortName(out);
9290                    out.print(" filter ");
9291                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9292        }
9293
9294        @Override
9295        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9296            return filter.service;
9297        }
9298
9299        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9300            PackageParser.Service service = (PackageParser.Service)label;
9301            out.print(prefix); out.print(
9302                    Integer.toHexString(System.identityHashCode(service)));
9303                    out.print(' ');
9304                    service.printComponentShortName(out);
9305            if (count > 1) {
9306                out.print(" ("); out.print(count); out.print(" filters)");
9307            }
9308            out.println();
9309        }
9310
9311//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9312//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9313//            final List<ResolveInfo> retList = Lists.newArrayList();
9314//            while (i.hasNext()) {
9315//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9316//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9317//                    retList.add(resolveInfo);
9318//                }
9319//            }
9320//            return retList;
9321//        }
9322
9323        // Keys are String (activity class name), values are Activity.
9324        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9325                = new ArrayMap<ComponentName, PackageParser.Service>();
9326        private int mFlags;
9327    };
9328
9329    private final class ProviderIntentResolver
9330            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9331        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9332                boolean defaultOnly, int userId) {
9333            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9334            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9335        }
9336
9337        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9338                int userId) {
9339            if (!sUserManager.exists(userId))
9340                return null;
9341            mFlags = flags;
9342            return super.queryIntent(intent, resolvedType,
9343                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9344        }
9345
9346        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9347                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9348            if (!sUserManager.exists(userId))
9349                return null;
9350            if (packageProviders == null) {
9351                return null;
9352            }
9353            mFlags = flags;
9354            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9355            final int N = packageProviders.size();
9356            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9357                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9358
9359            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9360            for (int i = 0; i < N; ++i) {
9361                intentFilters = packageProviders.get(i).intents;
9362                if (intentFilters != null && intentFilters.size() > 0) {
9363                    PackageParser.ProviderIntentInfo[] array =
9364                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9365                    intentFilters.toArray(array);
9366                    listCut.add(array);
9367                }
9368            }
9369            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9370        }
9371
9372        public final void addProvider(PackageParser.Provider p) {
9373            if (mProviders.containsKey(p.getComponentName())) {
9374                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9375                return;
9376            }
9377
9378            mProviders.put(p.getComponentName(), p);
9379            if (DEBUG_SHOW_INFO) {
9380                Log.v(TAG, "  "
9381                        + (p.info.nonLocalizedLabel != null
9382                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9383                Log.v(TAG, "    Class=" + p.info.name);
9384            }
9385            final int NI = p.intents.size();
9386            int j;
9387            for (j = 0; j < NI; j++) {
9388                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9389                if (DEBUG_SHOW_INFO) {
9390                    Log.v(TAG, "    IntentFilter:");
9391                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9392                }
9393                if (!intent.debugCheck()) {
9394                    Log.w(TAG, "==> For Provider " + p.info.name);
9395                }
9396                addFilter(intent);
9397            }
9398        }
9399
9400        public final void removeProvider(PackageParser.Provider p) {
9401            mProviders.remove(p.getComponentName());
9402            if (DEBUG_SHOW_INFO) {
9403                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9404                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9405                Log.v(TAG, "    Class=" + p.info.name);
9406            }
9407            final int NI = p.intents.size();
9408            int j;
9409            for (j = 0; j < NI; j++) {
9410                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9411                if (DEBUG_SHOW_INFO) {
9412                    Log.v(TAG, "    IntentFilter:");
9413                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9414                }
9415                removeFilter(intent);
9416            }
9417        }
9418
9419        @Override
9420        protected boolean allowFilterResult(
9421                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9422            ProviderInfo filterPi = filter.provider.info;
9423            for (int i = dest.size() - 1; i >= 0; i--) {
9424                ProviderInfo destPi = dest.get(i).providerInfo;
9425                if (destPi.name == filterPi.name
9426                        && destPi.packageName == filterPi.packageName) {
9427                    return false;
9428                }
9429            }
9430            return true;
9431        }
9432
9433        @Override
9434        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9435            return new PackageParser.ProviderIntentInfo[size];
9436        }
9437
9438        @Override
9439        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9440            if (!sUserManager.exists(userId))
9441                return true;
9442            PackageParser.Package p = filter.provider.owner;
9443            if (p != null) {
9444                PackageSetting ps = (PackageSetting) p.mExtras;
9445                if (ps != null) {
9446                    // System apps are never considered stopped for purposes of
9447                    // filtering, because there may be no way for the user to
9448                    // actually re-launch them.
9449                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9450                            && ps.getStopped(userId);
9451                }
9452            }
9453            return false;
9454        }
9455
9456        @Override
9457        protected boolean isPackageForFilter(String packageName,
9458                PackageParser.ProviderIntentInfo info) {
9459            return packageName.equals(info.provider.owner.packageName);
9460        }
9461
9462        @Override
9463        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9464                int match, int userId) {
9465            if (!sUserManager.exists(userId))
9466                return null;
9467            final PackageParser.ProviderIntentInfo info = filter;
9468            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9469                return null;
9470            }
9471            final PackageParser.Provider provider = info.provider;
9472            if (mSafeMode && (provider.info.applicationInfo.flags
9473                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9474                return null;
9475            }
9476            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9477            if (ps == null) {
9478                return null;
9479            }
9480            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9481                    ps.readUserState(userId), userId);
9482            if (pi == null) {
9483                return null;
9484            }
9485            final ResolveInfo res = new ResolveInfo();
9486            res.providerInfo = pi;
9487            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9488                res.filter = filter;
9489            }
9490            res.priority = info.getPriority();
9491            res.preferredOrder = provider.owner.mPreferredOrder;
9492            res.match = match;
9493            res.isDefault = info.hasDefault;
9494            res.labelRes = info.labelRes;
9495            res.nonLocalizedLabel = info.nonLocalizedLabel;
9496            res.icon = info.icon;
9497            res.system = res.providerInfo.applicationInfo.isSystemApp();
9498            return res;
9499        }
9500
9501        @Override
9502        protected void sortResults(List<ResolveInfo> results) {
9503            Collections.sort(results, mResolvePrioritySorter);
9504        }
9505
9506        @Override
9507        protected void dumpFilter(PrintWriter out, String prefix,
9508                PackageParser.ProviderIntentInfo filter) {
9509            out.print(prefix);
9510            out.print(
9511                    Integer.toHexString(System.identityHashCode(filter.provider)));
9512            out.print(' ');
9513            filter.provider.printComponentShortName(out);
9514            out.print(" filter ");
9515            out.println(Integer.toHexString(System.identityHashCode(filter)));
9516        }
9517
9518        @Override
9519        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9520            return filter.provider;
9521        }
9522
9523        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9524            PackageParser.Provider provider = (PackageParser.Provider)label;
9525            out.print(prefix); out.print(
9526                    Integer.toHexString(System.identityHashCode(provider)));
9527                    out.print(' ');
9528                    provider.printComponentShortName(out);
9529            if (count > 1) {
9530                out.print(" ("); out.print(count); out.print(" filters)");
9531            }
9532            out.println();
9533        }
9534
9535        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9536                = new ArrayMap<ComponentName, PackageParser.Provider>();
9537        private int mFlags;
9538    };
9539
9540    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9541            new Comparator<ResolveInfo>() {
9542        public int compare(ResolveInfo r1, ResolveInfo r2) {
9543            int v1 = r1.priority;
9544            int v2 = r2.priority;
9545            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9546            if (v1 != v2) {
9547                return (v1 > v2) ? -1 : 1;
9548            }
9549            v1 = r1.preferredOrder;
9550            v2 = r2.preferredOrder;
9551            if (v1 != v2) {
9552                return (v1 > v2) ? -1 : 1;
9553            }
9554            if (r1.isDefault != r2.isDefault) {
9555                return r1.isDefault ? -1 : 1;
9556            }
9557            v1 = r1.match;
9558            v2 = r2.match;
9559            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9560            if (v1 != v2) {
9561                return (v1 > v2) ? -1 : 1;
9562            }
9563            if (r1.system != r2.system) {
9564                return r1.system ? -1 : 1;
9565            }
9566            return 0;
9567        }
9568    };
9569
9570    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9571            new Comparator<ProviderInfo>() {
9572        public int compare(ProviderInfo p1, ProviderInfo p2) {
9573            final int v1 = p1.initOrder;
9574            final int v2 = p2.initOrder;
9575            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9576        }
9577    };
9578
9579    final void sendPackageBroadcast(final String action, final String pkg,
9580            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9581            final int[] userIds) {
9582        mHandler.post(new Runnable() {
9583            @Override
9584            public void run() {
9585                try {
9586                    final IActivityManager am = ActivityManagerNative.getDefault();
9587                    if (am == null) return;
9588                    final int[] resolvedUserIds;
9589                    if (userIds == null) {
9590                        resolvedUserIds = am.getRunningUserIds();
9591                    } else {
9592                        resolvedUserIds = userIds;
9593                    }
9594                    for (int id : resolvedUserIds) {
9595                        final Intent intent = new Intent(action,
9596                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9597                        if (extras != null) {
9598                            intent.putExtras(extras);
9599                        }
9600                        if (targetPkg != null) {
9601                            intent.setPackage(targetPkg);
9602                        }
9603                        // Modify the UID when posting to other users
9604                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9605                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9606                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9607                            intent.putExtra(Intent.EXTRA_UID, uid);
9608                        }
9609                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9610                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9611                        if (DEBUG_BROADCASTS) {
9612                            RuntimeException here = new RuntimeException("here");
9613                            here.fillInStackTrace();
9614                            Slog.d(TAG, "Sending to user " + id + ": "
9615                                    + intent.toShortString(false, true, false, false)
9616                                    + " " + intent.getExtras(), here);
9617                        }
9618                        am.broadcastIntent(null, intent, null, finishedReceiver,
9619                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9620                                null, finishedReceiver != null, false, id);
9621                    }
9622                } catch (RemoteException ex) {
9623                }
9624            }
9625        });
9626    }
9627
9628    /**
9629     * Check if the external storage media is available. This is true if there
9630     * is a mounted external storage medium or if the external storage is
9631     * emulated.
9632     */
9633    private boolean isExternalMediaAvailable() {
9634        return mMediaMounted || Environment.isExternalStorageEmulated();
9635    }
9636
9637    @Override
9638    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9639        // writer
9640        synchronized (mPackages) {
9641            if (!isExternalMediaAvailable()) {
9642                // If the external storage is no longer mounted at this point,
9643                // the caller may not have been able to delete all of this
9644                // packages files and can not delete any more.  Bail.
9645                return null;
9646            }
9647            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9648            if (lastPackage != null) {
9649                pkgs.remove(lastPackage);
9650            }
9651            if (pkgs.size() > 0) {
9652                return pkgs.get(0);
9653            }
9654        }
9655        return null;
9656    }
9657
9658    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9659        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9660                userId, andCode ? 1 : 0, packageName);
9661        if (mSystemReady) {
9662            msg.sendToTarget();
9663        } else {
9664            if (mPostSystemReadyMessages == null) {
9665                mPostSystemReadyMessages = new ArrayList<>();
9666            }
9667            mPostSystemReadyMessages.add(msg);
9668        }
9669    }
9670
9671    void startCleaningPackages() {
9672        // reader
9673        synchronized (mPackages) {
9674            if (!isExternalMediaAvailable()) {
9675                return;
9676            }
9677            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9678                return;
9679            }
9680        }
9681        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9682        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9683        IActivityManager am = ActivityManagerNative.getDefault();
9684        if (am != null) {
9685            try {
9686                am.startService(null, intent, null, mContext.getOpPackageName(),
9687                        UserHandle.USER_SYSTEM);
9688            } catch (RemoteException e) {
9689            }
9690        }
9691    }
9692
9693    @Override
9694    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9695            int installFlags, String installerPackageName, VerificationParams verificationParams,
9696            String packageAbiOverride) {
9697        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9698                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9699    }
9700
9701    @Override
9702    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9703            int installFlags, String installerPackageName, VerificationParams verificationParams,
9704            String packageAbiOverride, int userId) {
9705        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9706
9707        final int callingUid = Binder.getCallingUid();
9708        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9709
9710        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9711            try {
9712                if (observer != null) {
9713                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9714                }
9715            } catch (RemoteException re) {
9716            }
9717            return;
9718        }
9719
9720        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9721            installFlags |= PackageManager.INSTALL_FROM_ADB;
9722
9723        } else {
9724            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9725            // about installerPackageName.
9726
9727            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9728            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9729        }
9730
9731        UserHandle user;
9732        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9733            user = UserHandle.ALL;
9734        } else {
9735            user = new UserHandle(userId);
9736        }
9737
9738        // Only system components can circumvent runtime permissions when installing.
9739        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9740                && mContext.checkCallingOrSelfPermission(Manifest.permission
9741                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9742            throw new SecurityException("You need the "
9743                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9744                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9745        }
9746
9747        verificationParams.setInstallerUid(callingUid);
9748
9749        final File originFile = new File(originPath);
9750        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9751
9752        final Message msg = mHandler.obtainMessage(INIT_COPY);
9753        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9754                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9755        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9756        msg.obj = params;
9757
9758        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9759                System.identityHashCode(msg.obj));
9760        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9761                System.identityHashCode(msg.obj));
9762
9763        mHandler.sendMessage(msg);
9764    }
9765
9766    void installStage(String packageName, File stagedDir, String stagedCid,
9767            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9768            String installerPackageName, int installerUid, UserHandle user) {
9769        final VerificationParams verifParams = new VerificationParams(
9770                null, sessionParams.originatingUri, sessionParams.referrerUri,
9771                sessionParams.originatingUid, null);
9772        verifParams.setInstallerUid(installerUid);
9773
9774        final OriginInfo origin;
9775        if (stagedDir != null) {
9776            origin = OriginInfo.fromStagedFile(stagedDir);
9777        } else {
9778            origin = OriginInfo.fromStagedContainer(stagedCid);
9779        }
9780
9781        final Message msg = mHandler.obtainMessage(INIT_COPY);
9782        final InstallParams params = new InstallParams(origin, null, observer,
9783                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9784                verifParams, user, sessionParams.abiOverride,
9785                sessionParams.grantedRuntimePermissions);
9786        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9787        msg.obj = params;
9788
9789        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9790                System.identityHashCode(msg.obj));
9791        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9792                System.identityHashCode(msg.obj));
9793
9794        mHandler.sendMessage(msg);
9795    }
9796
9797    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9798        Bundle extras = new Bundle(1);
9799        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9800
9801        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9802                packageName, extras, null, null, new int[] {userId});
9803        try {
9804            IActivityManager am = ActivityManagerNative.getDefault();
9805            final boolean isSystem =
9806                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9807            if (isSystem && am.isUserRunning(userId, 0)) {
9808                // The just-installed/enabled app is bundled on the system, so presumed
9809                // to be able to run automatically without needing an explicit launch.
9810                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9811                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9812                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9813                        .setPackage(packageName);
9814                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9815                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9816            }
9817        } catch (RemoteException e) {
9818            // shouldn't happen
9819            Slog.w(TAG, "Unable to bootstrap installed package", e);
9820        }
9821    }
9822
9823    @Override
9824    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9825            int userId) {
9826        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9827        PackageSetting pkgSetting;
9828        final int uid = Binder.getCallingUid();
9829        enforceCrossUserPermission(uid, userId, true, true,
9830                "setApplicationHiddenSetting for user " + userId);
9831
9832        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9833            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9834            return false;
9835        }
9836
9837        long callingId = Binder.clearCallingIdentity();
9838        try {
9839            boolean sendAdded = false;
9840            boolean sendRemoved = false;
9841            // writer
9842            synchronized (mPackages) {
9843                pkgSetting = mSettings.mPackages.get(packageName);
9844                if (pkgSetting == null) {
9845                    return false;
9846                }
9847                if (pkgSetting.getHidden(userId) != hidden) {
9848                    pkgSetting.setHidden(hidden, userId);
9849                    mSettings.writePackageRestrictionsLPr(userId);
9850                    if (hidden) {
9851                        sendRemoved = true;
9852                    } else {
9853                        sendAdded = true;
9854                    }
9855                }
9856            }
9857            if (sendAdded) {
9858                sendPackageAddedForUser(packageName, pkgSetting, userId);
9859                return true;
9860            }
9861            if (sendRemoved) {
9862                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9863                        "hiding pkg");
9864                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9865                return true;
9866            }
9867        } finally {
9868            Binder.restoreCallingIdentity(callingId);
9869        }
9870        return false;
9871    }
9872
9873    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9874            int userId) {
9875        final PackageRemovedInfo info = new PackageRemovedInfo();
9876        info.removedPackage = packageName;
9877        info.removedUsers = new int[] {userId};
9878        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9879        info.sendBroadcast(false, false, false);
9880    }
9881
9882    /**
9883     * Returns true if application is not found or there was an error. Otherwise it returns
9884     * the hidden state of the package for the given user.
9885     */
9886    @Override
9887    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9888        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9889        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9890                false, "getApplicationHidden for user " + userId);
9891        PackageSetting pkgSetting;
9892        long callingId = Binder.clearCallingIdentity();
9893        try {
9894            // writer
9895            synchronized (mPackages) {
9896                pkgSetting = mSettings.mPackages.get(packageName);
9897                if (pkgSetting == null) {
9898                    return true;
9899                }
9900                return pkgSetting.getHidden(userId);
9901            }
9902        } finally {
9903            Binder.restoreCallingIdentity(callingId);
9904        }
9905    }
9906
9907    /**
9908     * @hide
9909     */
9910    @Override
9911    public int installExistingPackageAsUser(String packageName, int userId) {
9912        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9913                null);
9914        PackageSetting pkgSetting;
9915        final int uid = Binder.getCallingUid();
9916        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9917                + userId);
9918        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9919            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9920        }
9921
9922        long callingId = Binder.clearCallingIdentity();
9923        try {
9924            boolean sendAdded = false;
9925
9926            // writer
9927            synchronized (mPackages) {
9928                pkgSetting = mSettings.mPackages.get(packageName);
9929                if (pkgSetting == null) {
9930                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9931                }
9932                if (!pkgSetting.getInstalled(userId)) {
9933                    pkgSetting.setInstalled(true, userId);
9934                    pkgSetting.setHidden(false, userId);
9935                    mSettings.writePackageRestrictionsLPr(userId);
9936                    sendAdded = true;
9937                }
9938            }
9939
9940            if (sendAdded) {
9941                sendPackageAddedForUser(packageName, pkgSetting, userId);
9942            }
9943        } finally {
9944            Binder.restoreCallingIdentity(callingId);
9945        }
9946
9947        return PackageManager.INSTALL_SUCCEEDED;
9948    }
9949
9950    boolean isUserRestricted(int userId, String restrictionKey) {
9951        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9952        if (restrictions.getBoolean(restrictionKey, false)) {
9953            Log.w(TAG, "User is restricted: " + restrictionKey);
9954            return true;
9955        }
9956        return false;
9957    }
9958
9959    @Override
9960    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9961        mContext.enforceCallingOrSelfPermission(
9962                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9963                "Only package verification agents can verify applications");
9964
9965        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9966        final PackageVerificationResponse response = new PackageVerificationResponse(
9967                verificationCode, Binder.getCallingUid());
9968        msg.arg1 = id;
9969        msg.obj = response;
9970        mHandler.sendMessage(msg);
9971    }
9972
9973    @Override
9974    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9975            long millisecondsToDelay) {
9976        mContext.enforceCallingOrSelfPermission(
9977                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9978                "Only package verification agents can extend verification timeouts");
9979
9980        final PackageVerificationState state = mPendingVerification.get(id);
9981        final PackageVerificationResponse response = new PackageVerificationResponse(
9982                verificationCodeAtTimeout, Binder.getCallingUid());
9983
9984        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9985            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9986        }
9987        if (millisecondsToDelay < 0) {
9988            millisecondsToDelay = 0;
9989        }
9990        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9991                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9992            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9993        }
9994
9995        if ((state != null) && !state.timeoutExtended()) {
9996            state.extendTimeout();
9997
9998            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9999            msg.arg1 = id;
10000            msg.obj = response;
10001            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10002        }
10003    }
10004
10005    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10006            int verificationCode, UserHandle user) {
10007        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10008        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10009        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10010        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10011        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10012
10013        mContext.sendBroadcastAsUser(intent, user,
10014                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10015    }
10016
10017    private ComponentName matchComponentForVerifier(String packageName,
10018            List<ResolveInfo> receivers) {
10019        ActivityInfo targetReceiver = null;
10020
10021        final int NR = receivers.size();
10022        for (int i = 0; i < NR; i++) {
10023            final ResolveInfo info = receivers.get(i);
10024            if (info.activityInfo == null) {
10025                continue;
10026            }
10027
10028            if (packageName.equals(info.activityInfo.packageName)) {
10029                targetReceiver = info.activityInfo;
10030                break;
10031            }
10032        }
10033
10034        if (targetReceiver == null) {
10035            return null;
10036        }
10037
10038        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10039    }
10040
10041    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10042            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10043        if (pkgInfo.verifiers.length == 0) {
10044            return null;
10045        }
10046
10047        final int N = pkgInfo.verifiers.length;
10048        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10049        for (int i = 0; i < N; i++) {
10050            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10051
10052            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10053                    receivers);
10054            if (comp == null) {
10055                continue;
10056            }
10057
10058            final int verifierUid = getUidForVerifier(verifierInfo);
10059            if (verifierUid == -1) {
10060                continue;
10061            }
10062
10063            if (DEBUG_VERIFY) {
10064                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10065                        + " with the correct signature");
10066            }
10067            sufficientVerifiers.add(comp);
10068            verificationState.addSufficientVerifier(verifierUid);
10069        }
10070
10071        return sufficientVerifiers;
10072    }
10073
10074    private int getUidForVerifier(VerifierInfo verifierInfo) {
10075        synchronized (mPackages) {
10076            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10077            if (pkg == null) {
10078                return -1;
10079            } else if (pkg.mSignatures.length != 1) {
10080                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10081                        + " has more than one signature; ignoring");
10082                return -1;
10083            }
10084
10085            /*
10086             * If the public key of the package's signature does not match
10087             * our expected public key, then this is a different package and
10088             * we should skip.
10089             */
10090
10091            final byte[] expectedPublicKey;
10092            try {
10093                final Signature verifierSig = pkg.mSignatures[0];
10094                final PublicKey publicKey = verifierSig.getPublicKey();
10095                expectedPublicKey = publicKey.getEncoded();
10096            } catch (CertificateException e) {
10097                return -1;
10098            }
10099
10100            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10101
10102            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10103                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10104                        + " does not have the expected public key; ignoring");
10105                return -1;
10106            }
10107
10108            return pkg.applicationInfo.uid;
10109        }
10110    }
10111
10112    @Override
10113    public void finishPackageInstall(int token) {
10114        enforceSystemOrRoot("Only the system is allowed to finish installs");
10115
10116        if (DEBUG_INSTALL) {
10117            Slog.v(TAG, "BM finishing package install for " + token);
10118        }
10119        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10120
10121        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10122        mHandler.sendMessage(msg);
10123    }
10124
10125    /**
10126     * Get the verification agent timeout.
10127     *
10128     * @return verification timeout in milliseconds
10129     */
10130    private long getVerificationTimeout() {
10131        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10132                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10133                DEFAULT_VERIFICATION_TIMEOUT);
10134    }
10135
10136    /**
10137     * Get the default verification agent response code.
10138     *
10139     * @return default verification response code
10140     */
10141    private int getDefaultVerificationResponse() {
10142        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10143                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10144                DEFAULT_VERIFICATION_RESPONSE);
10145    }
10146
10147    /**
10148     * Check whether or not package verification has been enabled.
10149     *
10150     * @return true if verification should be performed
10151     */
10152    private boolean isVerificationEnabled(int userId, int installFlags) {
10153        if (!DEFAULT_VERIFY_ENABLE) {
10154            return false;
10155        }
10156        // TODO: fix b/25118622; don't bypass verification
10157        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10158            return false;
10159        }
10160
10161        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10162
10163        // Check if installing from ADB
10164        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10165            // Do not run verification in a test harness environment
10166            if (ActivityManager.isRunningInTestHarness()) {
10167                return false;
10168            }
10169            if (ensureVerifyAppsEnabled) {
10170                return true;
10171            }
10172            // Check if the developer does not want package verification for ADB installs
10173            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10174                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10175                return false;
10176            }
10177        }
10178
10179        if (ensureVerifyAppsEnabled) {
10180            return true;
10181        }
10182
10183        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10184                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10185    }
10186
10187    @Override
10188    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10189            throws RemoteException {
10190        mContext.enforceCallingOrSelfPermission(
10191                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10192                "Only intentfilter verification agents can verify applications");
10193
10194        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10195        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10196                Binder.getCallingUid(), verificationCode, failedDomains);
10197        msg.arg1 = id;
10198        msg.obj = response;
10199        mHandler.sendMessage(msg);
10200    }
10201
10202    @Override
10203    public int getIntentVerificationStatus(String packageName, int userId) {
10204        synchronized (mPackages) {
10205            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10206        }
10207    }
10208
10209    @Override
10210    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10211        mContext.enforceCallingOrSelfPermission(
10212                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10213
10214        boolean result = false;
10215        synchronized (mPackages) {
10216            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10217        }
10218        if (result) {
10219            scheduleWritePackageRestrictionsLocked(userId);
10220        }
10221        return result;
10222    }
10223
10224    @Override
10225    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10226        synchronized (mPackages) {
10227            return mSettings.getIntentFilterVerificationsLPr(packageName);
10228        }
10229    }
10230
10231    @Override
10232    public List<IntentFilter> getAllIntentFilters(String packageName) {
10233        if (TextUtils.isEmpty(packageName)) {
10234            return Collections.<IntentFilter>emptyList();
10235        }
10236        synchronized (mPackages) {
10237            PackageParser.Package pkg = mPackages.get(packageName);
10238            if (pkg == null || pkg.activities == null) {
10239                return Collections.<IntentFilter>emptyList();
10240            }
10241            final int count = pkg.activities.size();
10242            ArrayList<IntentFilter> result = new ArrayList<>();
10243            for (int n=0; n<count; n++) {
10244                PackageParser.Activity activity = pkg.activities.get(n);
10245                if (activity.intents != null || activity.intents.size() > 0) {
10246                    result.addAll(activity.intents);
10247                }
10248            }
10249            return result;
10250        }
10251    }
10252
10253    @Override
10254    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10255        mContext.enforceCallingOrSelfPermission(
10256                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10257
10258        synchronized (mPackages) {
10259            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10260            if (packageName != null) {
10261                result |= updateIntentVerificationStatus(packageName,
10262                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10263                        userId);
10264                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10265                        packageName, userId);
10266            }
10267            return result;
10268        }
10269    }
10270
10271    @Override
10272    public String getDefaultBrowserPackageName(int userId) {
10273        synchronized (mPackages) {
10274            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10275        }
10276    }
10277
10278    /**
10279     * Get the "allow unknown sources" setting.
10280     *
10281     * @return the current "allow unknown sources" setting
10282     */
10283    private int getUnknownSourcesSettings() {
10284        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10285                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10286                -1);
10287    }
10288
10289    @Override
10290    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10291        final int uid = Binder.getCallingUid();
10292        // writer
10293        synchronized (mPackages) {
10294            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10295            if (targetPackageSetting == null) {
10296                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10297            }
10298
10299            PackageSetting installerPackageSetting;
10300            if (installerPackageName != null) {
10301                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10302                if (installerPackageSetting == null) {
10303                    throw new IllegalArgumentException("Unknown installer package: "
10304                            + installerPackageName);
10305                }
10306            } else {
10307                installerPackageSetting = null;
10308            }
10309
10310            Signature[] callerSignature;
10311            Object obj = mSettings.getUserIdLPr(uid);
10312            if (obj != null) {
10313                if (obj instanceof SharedUserSetting) {
10314                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10315                } else if (obj instanceof PackageSetting) {
10316                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10317                } else {
10318                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10319                }
10320            } else {
10321                throw new SecurityException("Unknown calling uid " + uid);
10322            }
10323
10324            // Verify: can't set installerPackageName to a package that is
10325            // not signed with the same cert as the caller.
10326            if (installerPackageSetting != null) {
10327                if (compareSignatures(callerSignature,
10328                        installerPackageSetting.signatures.mSignatures)
10329                        != PackageManager.SIGNATURE_MATCH) {
10330                    throw new SecurityException(
10331                            "Caller does not have same cert as new installer package "
10332                            + installerPackageName);
10333                }
10334            }
10335
10336            // Verify: if target already has an installer package, it must
10337            // be signed with the same cert as the caller.
10338            if (targetPackageSetting.installerPackageName != null) {
10339                PackageSetting setting = mSettings.mPackages.get(
10340                        targetPackageSetting.installerPackageName);
10341                // If the currently set package isn't valid, then it's always
10342                // okay to change it.
10343                if (setting != null) {
10344                    if (compareSignatures(callerSignature,
10345                            setting.signatures.mSignatures)
10346                            != PackageManager.SIGNATURE_MATCH) {
10347                        throw new SecurityException(
10348                                "Caller does not have same cert as old installer package "
10349                                + targetPackageSetting.installerPackageName);
10350                    }
10351                }
10352            }
10353
10354            // Okay!
10355            targetPackageSetting.installerPackageName = installerPackageName;
10356            scheduleWriteSettingsLocked();
10357        }
10358    }
10359
10360    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10361        // Queue up an async operation since the package installation may take a little while.
10362        mHandler.post(new Runnable() {
10363            public void run() {
10364                mHandler.removeCallbacks(this);
10365                 // Result object to be returned
10366                PackageInstalledInfo res = new PackageInstalledInfo();
10367                res.returnCode = currentStatus;
10368                res.uid = -1;
10369                res.pkg = null;
10370                res.removedInfo = new PackageRemovedInfo();
10371                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10372                    args.doPreInstall(res.returnCode);
10373                    synchronized (mInstallLock) {
10374                        installPackageTracedLI(args, res);
10375                    }
10376                    args.doPostInstall(res.returnCode, res.uid);
10377                }
10378
10379                // A restore should be performed at this point if (a) the install
10380                // succeeded, (b) the operation is not an update, and (c) the new
10381                // package has not opted out of backup participation.
10382                final boolean update = res.removedInfo.removedPackage != null;
10383                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10384                boolean doRestore = !update
10385                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10386
10387                // Set up the post-install work request bookkeeping.  This will be used
10388                // and cleaned up by the post-install event handling regardless of whether
10389                // there's a restore pass performed.  Token values are >= 1.
10390                int token;
10391                if (mNextInstallToken < 0) mNextInstallToken = 1;
10392                token = mNextInstallToken++;
10393
10394                PostInstallData data = new PostInstallData(args, res);
10395                mRunningInstalls.put(token, data);
10396                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10397
10398                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10399                    // Pass responsibility to the Backup Manager.  It will perform a
10400                    // restore if appropriate, then pass responsibility back to the
10401                    // Package Manager to run the post-install observer callbacks
10402                    // and broadcasts.
10403                    IBackupManager bm = IBackupManager.Stub.asInterface(
10404                            ServiceManager.getService(Context.BACKUP_SERVICE));
10405                    if (bm != null) {
10406                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10407                                + " to BM for possible restore");
10408                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10409                        try {
10410                            // TODO: http://b/22388012
10411                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10412                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10413                            } else {
10414                                doRestore = false;
10415                            }
10416                        } catch (RemoteException e) {
10417                            // can't happen; the backup manager is local
10418                        } catch (Exception e) {
10419                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10420                            doRestore = false;
10421                        }
10422                    } else {
10423                        Slog.e(TAG, "Backup Manager not found!");
10424                        doRestore = false;
10425                    }
10426                }
10427
10428                if (!doRestore) {
10429                    // No restore possible, or the Backup Manager was mysteriously not
10430                    // available -- just fire the post-install work request directly.
10431                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10432
10433                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10434
10435                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10436                    mHandler.sendMessage(msg);
10437                }
10438            }
10439        });
10440    }
10441
10442    private abstract class HandlerParams {
10443        private static final int MAX_RETRIES = 4;
10444
10445        /**
10446         * Number of times startCopy() has been attempted and had a non-fatal
10447         * error.
10448         */
10449        private int mRetries = 0;
10450
10451        /** User handle for the user requesting the information or installation. */
10452        private final UserHandle mUser;
10453        String traceMethod;
10454        int traceCookie;
10455
10456        HandlerParams(UserHandle user) {
10457            mUser = user;
10458        }
10459
10460        UserHandle getUser() {
10461            return mUser;
10462        }
10463
10464        HandlerParams setTraceMethod(String traceMethod) {
10465            this.traceMethod = traceMethod;
10466            return this;
10467        }
10468
10469        HandlerParams setTraceCookie(int traceCookie) {
10470            this.traceCookie = traceCookie;
10471            return this;
10472        }
10473
10474        final boolean startCopy() {
10475            boolean res;
10476            try {
10477                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10478
10479                if (++mRetries > MAX_RETRIES) {
10480                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10481                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10482                    handleServiceError();
10483                    return false;
10484                } else {
10485                    handleStartCopy();
10486                    res = true;
10487                }
10488            } catch (RemoteException e) {
10489                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10490                mHandler.sendEmptyMessage(MCS_RECONNECT);
10491                res = false;
10492            }
10493            handleReturnCode();
10494            return res;
10495        }
10496
10497        final void serviceError() {
10498            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10499            handleServiceError();
10500            handleReturnCode();
10501        }
10502
10503        abstract void handleStartCopy() throws RemoteException;
10504        abstract void handleServiceError();
10505        abstract void handleReturnCode();
10506    }
10507
10508    class MeasureParams extends HandlerParams {
10509        private final PackageStats mStats;
10510        private boolean mSuccess;
10511
10512        private final IPackageStatsObserver mObserver;
10513
10514        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10515            super(new UserHandle(stats.userHandle));
10516            mObserver = observer;
10517            mStats = stats;
10518        }
10519
10520        @Override
10521        public String toString() {
10522            return "MeasureParams{"
10523                + Integer.toHexString(System.identityHashCode(this))
10524                + " " + mStats.packageName + "}";
10525        }
10526
10527        @Override
10528        void handleStartCopy() throws RemoteException {
10529            synchronized (mInstallLock) {
10530                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10531            }
10532
10533            if (mSuccess) {
10534                final boolean mounted;
10535                if (Environment.isExternalStorageEmulated()) {
10536                    mounted = true;
10537                } else {
10538                    final String status = Environment.getExternalStorageState();
10539                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10540                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10541                }
10542
10543                if (mounted) {
10544                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10545
10546                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10547                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10548
10549                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10550                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10551
10552                    // Always subtract cache size, since it's a subdirectory
10553                    mStats.externalDataSize -= mStats.externalCacheSize;
10554
10555                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10556                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10557
10558                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10559                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10560                }
10561            }
10562        }
10563
10564        @Override
10565        void handleReturnCode() {
10566            if (mObserver != null) {
10567                try {
10568                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10569                } catch (RemoteException e) {
10570                    Slog.i(TAG, "Observer no longer exists.");
10571                }
10572            }
10573        }
10574
10575        @Override
10576        void handleServiceError() {
10577            Slog.e(TAG, "Could not measure application " + mStats.packageName
10578                            + " external storage");
10579        }
10580    }
10581
10582    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10583            throws RemoteException {
10584        long result = 0;
10585        for (File path : paths) {
10586            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10587        }
10588        return result;
10589    }
10590
10591    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10592        for (File path : paths) {
10593            try {
10594                mcs.clearDirectory(path.getAbsolutePath());
10595            } catch (RemoteException e) {
10596            }
10597        }
10598    }
10599
10600    static class OriginInfo {
10601        /**
10602         * Location where install is coming from, before it has been
10603         * copied/renamed into place. This could be a single monolithic APK
10604         * file, or a cluster directory. This location may be untrusted.
10605         */
10606        final File file;
10607        final String cid;
10608
10609        /**
10610         * Flag indicating that {@link #file} or {@link #cid} has already been
10611         * staged, meaning downstream users don't need to defensively copy the
10612         * contents.
10613         */
10614        final boolean staged;
10615
10616        /**
10617         * Flag indicating that {@link #file} or {@link #cid} is an already
10618         * installed app that is being moved.
10619         */
10620        final boolean existing;
10621
10622        final String resolvedPath;
10623        final File resolvedFile;
10624
10625        static OriginInfo fromNothing() {
10626            return new OriginInfo(null, null, false, false);
10627        }
10628
10629        static OriginInfo fromUntrustedFile(File file) {
10630            return new OriginInfo(file, null, false, false);
10631        }
10632
10633        static OriginInfo fromExistingFile(File file) {
10634            return new OriginInfo(file, null, false, true);
10635        }
10636
10637        static OriginInfo fromStagedFile(File file) {
10638            return new OriginInfo(file, null, true, false);
10639        }
10640
10641        static OriginInfo fromStagedContainer(String cid) {
10642            return new OriginInfo(null, cid, true, false);
10643        }
10644
10645        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10646            this.file = file;
10647            this.cid = cid;
10648            this.staged = staged;
10649            this.existing = existing;
10650
10651            if (cid != null) {
10652                resolvedPath = PackageHelper.getSdDir(cid);
10653                resolvedFile = new File(resolvedPath);
10654            } else if (file != null) {
10655                resolvedPath = file.getAbsolutePath();
10656                resolvedFile = file;
10657            } else {
10658                resolvedPath = null;
10659                resolvedFile = null;
10660            }
10661        }
10662    }
10663
10664    class MoveInfo {
10665        final int moveId;
10666        final String fromUuid;
10667        final String toUuid;
10668        final String packageName;
10669        final String dataAppName;
10670        final int appId;
10671        final String seinfo;
10672
10673        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10674                String dataAppName, int appId, String seinfo) {
10675            this.moveId = moveId;
10676            this.fromUuid = fromUuid;
10677            this.toUuid = toUuid;
10678            this.packageName = packageName;
10679            this.dataAppName = dataAppName;
10680            this.appId = appId;
10681            this.seinfo = seinfo;
10682        }
10683    }
10684
10685    class InstallParams extends HandlerParams {
10686        final OriginInfo origin;
10687        final MoveInfo move;
10688        final IPackageInstallObserver2 observer;
10689        int installFlags;
10690        final String installerPackageName;
10691        final String volumeUuid;
10692        final VerificationParams verificationParams;
10693        private InstallArgs mArgs;
10694        private int mRet;
10695        final String packageAbiOverride;
10696        final String[] grantedRuntimePermissions;
10697
10698        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10699                int installFlags, String installerPackageName, String volumeUuid,
10700                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10701                String[] grantedPermissions) {
10702            super(user);
10703            this.origin = origin;
10704            this.move = move;
10705            this.observer = observer;
10706            this.installFlags = installFlags;
10707            this.installerPackageName = installerPackageName;
10708            this.volumeUuid = volumeUuid;
10709            this.verificationParams = verificationParams;
10710            this.packageAbiOverride = packageAbiOverride;
10711            this.grantedRuntimePermissions = grantedPermissions;
10712        }
10713
10714        @Override
10715        public String toString() {
10716            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10717                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10718        }
10719
10720        public ManifestDigest getManifestDigest() {
10721            if (verificationParams == null) {
10722                return null;
10723            }
10724            return verificationParams.getManifestDigest();
10725        }
10726
10727        private int installLocationPolicy(PackageInfoLite pkgLite) {
10728            String packageName = pkgLite.packageName;
10729            int installLocation = pkgLite.installLocation;
10730            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10731            // reader
10732            synchronized (mPackages) {
10733                PackageParser.Package pkg = mPackages.get(packageName);
10734                if (pkg != null) {
10735                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10736                        // Check for downgrading.
10737                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10738                            try {
10739                                checkDowngrade(pkg, pkgLite);
10740                            } catch (PackageManagerException e) {
10741                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10742                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10743                            }
10744                        }
10745                        // Check for updated system application.
10746                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10747                            if (onSd) {
10748                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10749                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10750                            }
10751                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10752                        } else {
10753                            if (onSd) {
10754                                // Install flag overrides everything.
10755                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10756                            }
10757                            // If current upgrade specifies particular preference
10758                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10759                                // Application explicitly specified internal.
10760                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10761                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10762                                // App explictly prefers external. Let policy decide
10763                            } else {
10764                                // Prefer previous location
10765                                if (isExternal(pkg)) {
10766                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10767                                }
10768                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10769                            }
10770                        }
10771                    } else {
10772                        // Invalid install. Return error code
10773                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10774                    }
10775                }
10776            }
10777            // All the special cases have been taken care of.
10778            // Return result based on recommended install location.
10779            if (onSd) {
10780                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10781            }
10782            return pkgLite.recommendedInstallLocation;
10783        }
10784
10785        /*
10786         * Invoke remote method to get package information and install
10787         * location values. Override install location based on default
10788         * policy if needed and then create install arguments based
10789         * on the install location.
10790         */
10791        public void handleStartCopy() throws RemoteException {
10792            int ret = PackageManager.INSTALL_SUCCEEDED;
10793
10794            // If we're already staged, we've firmly committed to an install location
10795            if (origin.staged) {
10796                if (origin.file != null) {
10797                    installFlags |= PackageManager.INSTALL_INTERNAL;
10798                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10799                } else if (origin.cid != null) {
10800                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10801                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10802                } else {
10803                    throw new IllegalStateException("Invalid stage location");
10804                }
10805            }
10806
10807            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10808            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10809            PackageInfoLite pkgLite = null;
10810
10811            if (onInt && onSd) {
10812                // Check if both bits are set.
10813                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10814                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10815            } else {
10816                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10817                        packageAbiOverride);
10818
10819                /*
10820                 * If we have too little free space, try to free cache
10821                 * before giving up.
10822                 */
10823                if (!origin.staged && pkgLite.recommendedInstallLocation
10824                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10825                    // TODO: focus freeing disk space on the target device
10826                    final StorageManager storage = StorageManager.from(mContext);
10827                    final long lowThreshold = storage.getStorageLowBytes(
10828                            Environment.getDataDirectory());
10829
10830                    final long sizeBytes = mContainerService.calculateInstalledSize(
10831                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10832
10833                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10834                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10835                                installFlags, packageAbiOverride);
10836                    }
10837
10838                    /*
10839                     * The cache free must have deleted the file we
10840                     * downloaded to install.
10841                     *
10842                     * TODO: fix the "freeCache" call to not delete
10843                     *       the file we care about.
10844                     */
10845                    if (pkgLite.recommendedInstallLocation
10846                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10847                        pkgLite.recommendedInstallLocation
10848                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10849                    }
10850                }
10851            }
10852
10853            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10854                int loc = pkgLite.recommendedInstallLocation;
10855                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10856                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10857                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10858                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10859                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10860                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10861                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10862                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10863                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10864                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10865                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10866                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10867                } else {
10868                    // Override with defaults if needed.
10869                    loc = installLocationPolicy(pkgLite);
10870                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10871                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10872                    } else if (!onSd && !onInt) {
10873                        // Override install location with flags
10874                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10875                            // Set the flag to install on external media.
10876                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10877                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10878                        } else {
10879                            // Make sure the flag for installing on external
10880                            // media is unset
10881                            installFlags |= PackageManager.INSTALL_INTERNAL;
10882                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10883                        }
10884                    }
10885                }
10886            }
10887
10888            final InstallArgs args = createInstallArgs(this);
10889            mArgs = args;
10890
10891            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10892                // TODO: http://b/22976637
10893                // Apps installed for "all" users use the device owner to verify the app
10894                UserHandle verifierUser = getUser();
10895                if (verifierUser == UserHandle.ALL) {
10896                    verifierUser = UserHandle.SYSTEM;
10897                }
10898
10899                /*
10900                 * Determine if we have any installed package verifiers. If we
10901                 * do, then we'll defer to them to verify the packages.
10902                 */
10903                final int requiredUid = mRequiredVerifierPackage == null ? -1
10904                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10905                if (!origin.existing && requiredUid != -1
10906                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10907                    final Intent verification = new Intent(
10908                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10909                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10910                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10911                            PACKAGE_MIME_TYPE);
10912                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10913
10914                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10915                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10916                            verifierUser.getIdentifier());
10917
10918                    if (DEBUG_VERIFY) {
10919                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10920                                + verification.toString() + " with " + pkgLite.verifiers.length
10921                                + " optional verifiers");
10922                    }
10923
10924                    final int verificationId = mPendingVerificationToken++;
10925
10926                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10927
10928                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10929                            installerPackageName);
10930
10931                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10932                            installFlags);
10933
10934                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10935                            pkgLite.packageName);
10936
10937                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10938                            pkgLite.versionCode);
10939
10940                    if (verificationParams != null) {
10941                        if (verificationParams.getVerificationURI() != null) {
10942                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10943                                 verificationParams.getVerificationURI());
10944                        }
10945                        if (verificationParams.getOriginatingURI() != null) {
10946                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10947                                  verificationParams.getOriginatingURI());
10948                        }
10949                        if (verificationParams.getReferrer() != null) {
10950                            verification.putExtra(Intent.EXTRA_REFERRER,
10951                                  verificationParams.getReferrer());
10952                        }
10953                        if (verificationParams.getOriginatingUid() >= 0) {
10954                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10955                                  verificationParams.getOriginatingUid());
10956                        }
10957                        if (verificationParams.getInstallerUid() >= 0) {
10958                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10959                                  verificationParams.getInstallerUid());
10960                        }
10961                    }
10962
10963                    final PackageVerificationState verificationState = new PackageVerificationState(
10964                            requiredUid, args);
10965
10966                    mPendingVerification.append(verificationId, verificationState);
10967
10968                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10969                            receivers, verificationState);
10970
10971                    /*
10972                     * If any sufficient verifiers were listed in the package
10973                     * manifest, attempt to ask them.
10974                     */
10975                    if (sufficientVerifiers != null) {
10976                        final int N = sufficientVerifiers.size();
10977                        if (N == 0) {
10978                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10979                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10980                        } else {
10981                            for (int i = 0; i < N; i++) {
10982                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10983
10984                                final Intent sufficientIntent = new Intent(verification);
10985                                sufficientIntent.setComponent(verifierComponent);
10986                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10987                            }
10988                        }
10989                    }
10990
10991                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10992                            mRequiredVerifierPackage, receivers);
10993                    if (ret == PackageManager.INSTALL_SUCCEEDED
10994                            && mRequiredVerifierPackage != null) {
10995                        Trace.asyncTraceBegin(
10996                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10997                        /*
10998                         * Send the intent to the required verification agent,
10999                         * but only start the verification timeout after the
11000                         * target BroadcastReceivers have run.
11001                         */
11002                        verification.setComponent(requiredVerifierComponent);
11003                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11004                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11005                                new BroadcastReceiver() {
11006                                    @Override
11007                                    public void onReceive(Context context, Intent intent) {
11008                                        final Message msg = mHandler
11009                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11010                                        msg.arg1 = verificationId;
11011                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11012                                    }
11013                                }, null, 0, null, null);
11014
11015                        /*
11016                         * We don't want the copy to proceed until verification
11017                         * succeeds, so null out this field.
11018                         */
11019                        mArgs = null;
11020                    }
11021                } else {
11022                    /*
11023                     * No package verification is enabled, so immediately start
11024                     * the remote call to initiate copy using temporary file.
11025                     */
11026                    ret = args.copyApk(mContainerService, true);
11027                }
11028            }
11029
11030            mRet = ret;
11031        }
11032
11033        @Override
11034        void handleReturnCode() {
11035            // If mArgs is null, then MCS couldn't be reached. When it
11036            // reconnects, it will try again to install. At that point, this
11037            // will succeed.
11038            if (mArgs != null) {
11039                processPendingInstall(mArgs, mRet);
11040            }
11041        }
11042
11043        @Override
11044        void handleServiceError() {
11045            mArgs = createInstallArgs(this);
11046            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11047        }
11048
11049        public boolean isForwardLocked() {
11050            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11051        }
11052    }
11053
11054    /**
11055     * Used during creation of InstallArgs
11056     *
11057     * @param installFlags package installation flags
11058     * @return true if should be installed on external storage
11059     */
11060    private static boolean installOnExternalAsec(int installFlags) {
11061        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11062            return false;
11063        }
11064        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11065            return true;
11066        }
11067        return false;
11068    }
11069
11070    /**
11071     * Used during creation of InstallArgs
11072     *
11073     * @param installFlags package installation flags
11074     * @return true if should be installed as forward locked
11075     */
11076    private static boolean installForwardLocked(int installFlags) {
11077        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11078    }
11079
11080    private InstallArgs createInstallArgs(InstallParams params) {
11081        if (params.move != null) {
11082            return new MoveInstallArgs(params);
11083        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11084            return new AsecInstallArgs(params);
11085        } else {
11086            return new FileInstallArgs(params);
11087        }
11088    }
11089
11090    /**
11091     * Create args that describe an existing installed package. Typically used
11092     * when cleaning up old installs, or used as a move source.
11093     */
11094    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11095            String resourcePath, String[] instructionSets) {
11096        final boolean isInAsec;
11097        if (installOnExternalAsec(installFlags)) {
11098            /* Apps on SD card are always in ASEC containers. */
11099            isInAsec = true;
11100        } else if (installForwardLocked(installFlags)
11101                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11102            /*
11103             * Forward-locked apps are only in ASEC containers if they're the
11104             * new style
11105             */
11106            isInAsec = true;
11107        } else {
11108            isInAsec = false;
11109        }
11110
11111        if (isInAsec) {
11112            return new AsecInstallArgs(codePath, instructionSets,
11113                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11114        } else {
11115            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11116        }
11117    }
11118
11119    static abstract class InstallArgs {
11120        /** @see InstallParams#origin */
11121        final OriginInfo origin;
11122        /** @see InstallParams#move */
11123        final MoveInfo move;
11124
11125        final IPackageInstallObserver2 observer;
11126        // Always refers to PackageManager flags only
11127        final int installFlags;
11128        final String installerPackageName;
11129        final String volumeUuid;
11130        final ManifestDigest manifestDigest;
11131        final UserHandle user;
11132        final String abiOverride;
11133        final String[] installGrantPermissions;
11134        /** If non-null, drop an async trace when the install completes */
11135        final String traceMethod;
11136        final int traceCookie;
11137
11138        // The list of instruction sets supported by this app. This is currently
11139        // only used during the rmdex() phase to clean up resources. We can get rid of this
11140        // if we move dex files under the common app path.
11141        /* nullable */ String[] instructionSets;
11142
11143        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11144                int installFlags, String installerPackageName, String volumeUuid,
11145                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11146                String abiOverride, String[] installGrantPermissions,
11147                String traceMethod, int traceCookie) {
11148            this.origin = origin;
11149            this.move = move;
11150            this.installFlags = installFlags;
11151            this.observer = observer;
11152            this.installerPackageName = installerPackageName;
11153            this.volumeUuid = volumeUuid;
11154            this.manifestDigest = manifestDigest;
11155            this.user = user;
11156            this.instructionSets = instructionSets;
11157            this.abiOverride = abiOverride;
11158            this.installGrantPermissions = installGrantPermissions;
11159            this.traceMethod = traceMethod;
11160            this.traceCookie = traceCookie;
11161        }
11162
11163        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11164        abstract int doPreInstall(int status);
11165
11166        /**
11167         * Rename package into final resting place. All paths on the given
11168         * scanned package should be updated to reflect the rename.
11169         */
11170        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11171        abstract int doPostInstall(int status, int uid);
11172
11173        /** @see PackageSettingBase#codePathString */
11174        abstract String getCodePath();
11175        /** @see PackageSettingBase#resourcePathString */
11176        abstract String getResourcePath();
11177
11178        // Need installer lock especially for dex file removal.
11179        abstract void cleanUpResourcesLI();
11180        abstract boolean doPostDeleteLI(boolean delete);
11181
11182        /**
11183         * Called before the source arguments are copied. This is used mostly
11184         * for MoveParams when it needs to read the source file to put it in the
11185         * destination.
11186         */
11187        int doPreCopy() {
11188            return PackageManager.INSTALL_SUCCEEDED;
11189        }
11190
11191        /**
11192         * Called after the source arguments are copied. This is used mostly for
11193         * MoveParams when it needs to read the source file to put it in the
11194         * destination.
11195         *
11196         * @return
11197         */
11198        int doPostCopy(int uid) {
11199            return PackageManager.INSTALL_SUCCEEDED;
11200        }
11201
11202        protected boolean isFwdLocked() {
11203            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11204        }
11205
11206        protected boolean isExternalAsec() {
11207            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11208        }
11209
11210        UserHandle getUser() {
11211            return user;
11212        }
11213    }
11214
11215    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11216        if (!allCodePaths.isEmpty()) {
11217            if (instructionSets == null) {
11218                throw new IllegalStateException("instructionSet == null");
11219            }
11220            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11221            for (String codePath : allCodePaths) {
11222                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11223                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11224                    if (retCode < 0) {
11225                        Slog.w(TAG, "Couldn't remove dex file for package: "
11226                                + " at location " + codePath + ", retcode=" + retCode);
11227                        // we don't consider this to be a failure of the core package deletion
11228                    }
11229                }
11230            }
11231        }
11232    }
11233
11234    /**
11235     * Logic to handle installation of non-ASEC applications, including copying
11236     * and renaming logic.
11237     */
11238    class FileInstallArgs extends InstallArgs {
11239        private File codeFile;
11240        private File resourceFile;
11241
11242        // Example topology:
11243        // /data/app/com.example/base.apk
11244        // /data/app/com.example/split_foo.apk
11245        // /data/app/com.example/lib/arm/libfoo.so
11246        // /data/app/com.example/lib/arm64/libfoo.so
11247        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11248
11249        /** New install */
11250        FileInstallArgs(InstallParams params) {
11251            super(params.origin, params.move, params.observer, params.installFlags,
11252                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11253                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11254                    params.grantedRuntimePermissions,
11255                    params.traceMethod, params.traceCookie);
11256            if (isFwdLocked()) {
11257                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11258            }
11259        }
11260
11261        /** Existing install */
11262        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11263            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11264                    null, null, null, 0);
11265            this.codeFile = (codePath != null) ? new File(codePath) : null;
11266            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11267        }
11268
11269        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11270            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11271            try {
11272                return doCopyApk(imcs, temp);
11273            } finally {
11274                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11275            }
11276        }
11277
11278        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11279            if (origin.staged) {
11280                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11281                codeFile = origin.file;
11282                resourceFile = origin.file;
11283                return PackageManager.INSTALL_SUCCEEDED;
11284            }
11285
11286            try {
11287                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11288                codeFile = tempDir;
11289                resourceFile = tempDir;
11290            } catch (IOException e) {
11291                Slog.w(TAG, "Failed to create copy file: " + e);
11292                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11293            }
11294
11295            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11296                @Override
11297                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11298                    if (!FileUtils.isValidExtFilename(name)) {
11299                        throw new IllegalArgumentException("Invalid filename: " + name);
11300                    }
11301                    try {
11302                        final File file = new File(codeFile, name);
11303                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11304                                O_RDWR | O_CREAT, 0644);
11305                        Os.chmod(file.getAbsolutePath(), 0644);
11306                        return new ParcelFileDescriptor(fd);
11307                    } catch (ErrnoException e) {
11308                        throw new RemoteException("Failed to open: " + e.getMessage());
11309                    }
11310                }
11311            };
11312
11313            int ret = PackageManager.INSTALL_SUCCEEDED;
11314            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11315            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11316                Slog.e(TAG, "Failed to copy package");
11317                return ret;
11318            }
11319
11320            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11321            NativeLibraryHelper.Handle handle = null;
11322            try {
11323                handle = NativeLibraryHelper.Handle.create(codeFile);
11324                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11325                        abiOverride);
11326            } catch (IOException e) {
11327                Slog.e(TAG, "Copying native libraries failed", e);
11328                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11329            } finally {
11330                IoUtils.closeQuietly(handle);
11331            }
11332
11333            return ret;
11334        }
11335
11336        int doPreInstall(int status) {
11337            if (status != PackageManager.INSTALL_SUCCEEDED) {
11338                cleanUp();
11339            }
11340            return status;
11341        }
11342
11343        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11344            if (status != PackageManager.INSTALL_SUCCEEDED) {
11345                cleanUp();
11346                return false;
11347            }
11348
11349            final File targetDir = codeFile.getParentFile();
11350            final File beforeCodeFile = codeFile;
11351            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11352
11353            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11354            try {
11355                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11356            } catch (ErrnoException e) {
11357                Slog.w(TAG, "Failed to rename", e);
11358                return false;
11359            }
11360
11361            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11362                Slog.w(TAG, "Failed to restorecon");
11363                return false;
11364            }
11365
11366            // Reflect the rename internally
11367            codeFile = afterCodeFile;
11368            resourceFile = afterCodeFile;
11369
11370            // Reflect the rename in scanned details
11371            pkg.codePath = afterCodeFile.getAbsolutePath();
11372            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11373                    pkg.baseCodePath);
11374            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11375                    pkg.splitCodePaths);
11376
11377            // Reflect the rename in app info
11378            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11379            pkg.applicationInfo.setCodePath(pkg.codePath);
11380            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11381            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11382            pkg.applicationInfo.setResourcePath(pkg.codePath);
11383            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11384            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11385
11386            return true;
11387        }
11388
11389        int doPostInstall(int status, int uid) {
11390            if (status != PackageManager.INSTALL_SUCCEEDED) {
11391                cleanUp();
11392            }
11393            return status;
11394        }
11395
11396        @Override
11397        String getCodePath() {
11398            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11399        }
11400
11401        @Override
11402        String getResourcePath() {
11403            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11404        }
11405
11406        private boolean cleanUp() {
11407            if (codeFile == null || !codeFile.exists()) {
11408                return false;
11409            }
11410
11411            if (codeFile.isDirectory()) {
11412                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11413            } else {
11414                codeFile.delete();
11415            }
11416
11417            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11418                resourceFile.delete();
11419            }
11420
11421            return true;
11422        }
11423
11424        void cleanUpResourcesLI() {
11425            // Try enumerating all code paths before deleting
11426            List<String> allCodePaths = Collections.EMPTY_LIST;
11427            if (codeFile != null && codeFile.exists()) {
11428                try {
11429                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11430                    allCodePaths = pkg.getAllCodePaths();
11431                } catch (PackageParserException e) {
11432                    // Ignored; we tried our best
11433                }
11434            }
11435
11436            cleanUp();
11437            removeDexFiles(allCodePaths, instructionSets);
11438        }
11439
11440        boolean doPostDeleteLI(boolean delete) {
11441            // XXX err, shouldn't we respect the delete flag?
11442            cleanUpResourcesLI();
11443            return true;
11444        }
11445    }
11446
11447    private boolean isAsecExternal(String cid) {
11448        final String asecPath = PackageHelper.getSdFilesystem(cid);
11449        return !asecPath.startsWith(mAsecInternalPath);
11450    }
11451
11452    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11453            PackageManagerException {
11454        if (copyRet < 0) {
11455            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11456                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11457                throw new PackageManagerException(copyRet, message);
11458            }
11459        }
11460    }
11461
11462    /**
11463     * Extract the MountService "container ID" from the full code path of an
11464     * .apk.
11465     */
11466    static String cidFromCodePath(String fullCodePath) {
11467        int eidx = fullCodePath.lastIndexOf("/");
11468        String subStr1 = fullCodePath.substring(0, eidx);
11469        int sidx = subStr1.lastIndexOf("/");
11470        return subStr1.substring(sidx+1, eidx);
11471    }
11472
11473    /**
11474     * Logic to handle installation of ASEC applications, including copying and
11475     * renaming logic.
11476     */
11477    class AsecInstallArgs extends InstallArgs {
11478        static final String RES_FILE_NAME = "pkg.apk";
11479        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11480
11481        String cid;
11482        String packagePath;
11483        String resourcePath;
11484
11485        /** New install */
11486        AsecInstallArgs(InstallParams params) {
11487            super(params.origin, params.move, params.observer, params.installFlags,
11488                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11489                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11490                    params.grantedRuntimePermissions,
11491                    params.traceMethod, params.traceCookie);
11492        }
11493
11494        /** Existing install */
11495        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11496                        boolean isExternal, boolean isForwardLocked) {
11497            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11498                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11499                    instructionSets, null, null, null, 0);
11500            // Hackily pretend we're still looking at a full code path
11501            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11502                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11503            }
11504
11505            // Extract cid from fullCodePath
11506            int eidx = fullCodePath.lastIndexOf("/");
11507            String subStr1 = fullCodePath.substring(0, eidx);
11508            int sidx = subStr1.lastIndexOf("/");
11509            cid = subStr1.substring(sidx+1, eidx);
11510            setMountPath(subStr1);
11511        }
11512
11513        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11514            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11515                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11516                    instructionSets, null, null, null, 0);
11517            this.cid = cid;
11518            setMountPath(PackageHelper.getSdDir(cid));
11519        }
11520
11521        void createCopyFile() {
11522            cid = mInstallerService.allocateExternalStageCidLegacy();
11523        }
11524
11525        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11526            if (origin.staged) {
11527                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11528                cid = origin.cid;
11529                setMountPath(PackageHelper.getSdDir(cid));
11530                return PackageManager.INSTALL_SUCCEEDED;
11531            }
11532
11533            if (temp) {
11534                createCopyFile();
11535            } else {
11536                /*
11537                 * Pre-emptively destroy the container since it's destroyed if
11538                 * copying fails due to it existing anyway.
11539                 */
11540                PackageHelper.destroySdDir(cid);
11541            }
11542
11543            final String newMountPath = imcs.copyPackageToContainer(
11544                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11545                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11546
11547            if (newMountPath != null) {
11548                setMountPath(newMountPath);
11549                return PackageManager.INSTALL_SUCCEEDED;
11550            } else {
11551                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11552            }
11553        }
11554
11555        @Override
11556        String getCodePath() {
11557            return packagePath;
11558        }
11559
11560        @Override
11561        String getResourcePath() {
11562            return resourcePath;
11563        }
11564
11565        int doPreInstall(int status) {
11566            if (status != PackageManager.INSTALL_SUCCEEDED) {
11567                // Destroy container
11568                PackageHelper.destroySdDir(cid);
11569            } else {
11570                boolean mounted = PackageHelper.isContainerMounted(cid);
11571                if (!mounted) {
11572                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11573                            Process.SYSTEM_UID);
11574                    if (newMountPath != null) {
11575                        setMountPath(newMountPath);
11576                    } else {
11577                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11578                    }
11579                }
11580            }
11581            return status;
11582        }
11583
11584        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11585            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11586            String newMountPath = null;
11587            if (PackageHelper.isContainerMounted(cid)) {
11588                // Unmount the container
11589                if (!PackageHelper.unMountSdDir(cid)) {
11590                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11591                    return false;
11592                }
11593            }
11594            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11595                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11596                        " which might be stale. Will try to clean up.");
11597                // Clean up the stale container and proceed to recreate.
11598                if (!PackageHelper.destroySdDir(newCacheId)) {
11599                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11600                    return false;
11601                }
11602                // Successfully cleaned up stale container. Try to rename again.
11603                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11604                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11605                            + " inspite of cleaning it up.");
11606                    return false;
11607                }
11608            }
11609            if (!PackageHelper.isContainerMounted(newCacheId)) {
11610                Slog.w(TAG, "Mounting container " + newCacheId);
11611                newMountPath = PackageHelper.mountSdDir(newCacheId,
11612                        getEncryptKey(), Process.SYSTEM_UID);
11613            } else {
11614                newMountPath = PackageHelper.getSdDir(newCacheId);
11615            }
11616            if (newMountPath == null) {
11617                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11618                return false;
11619            }
11620            Log.i(TAG, "Succesfully renamed " + cid +
11621                    " to " + newCacheId +
11622                    " at new path: " + newMountPath);
11623            cid = newCacheId;
11624
11625            final File beforeCodeFile = new File(packagePath);
11626            setMountPath(newMountPath);
11627            final File afterCodeFile = new File(packagePath);
11628
11629            // Reflect the rename in scanned details
11630            pkg.codePath = afterCodeFile.getAbsolutePath();
11631            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11632                    pkg.baseCodePath);
11633            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11634                    pkg.splitCodePaths);
11635
11636            // Reflect the rename in app info
11637            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11638            pkg.applicationInfo.setCodePath(pkg.codePath);
11639            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11640            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11641            pkg.applicationInfo.setResourcePath(pkg.codePath);
11642            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11643            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11644
11645            return true;
11646        }
11647
11648        private void setMountPath(String mountPath) {
11649            final File mountFile = new File(mountPath);
11650
11651            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11652            if (monolithicFile.exists()) {
11653                packagePath = monolithicFile.getAbsolutePath();
11654                if (isFwdLocked()) {
11655                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11656                } else {
11657                    resourcePath = packagePath;
11658                }
11659            } else {
11660                packagePath = mountFile.getAbsolutePath();
11661                resourcePath = packagePath;
11662            }
11663        }
11664
11665        int doPostInstall(int status, int uid) {
11666            if (status != PackageManager.INSTALL_SUCCEEDED) {
11667                cleanUp();
11668            } else {
11669                final int groupOwner;
11670                final String protectedFile;
11671                if (isFwdLocked()) {
11672                    groupOwner = UserHandle.getSharedAppGid(uid);
11673                    protectedFile = RES_FILE_NAME;
11674                } else {
11675                    groupOwner = -1;
11676                    protectedFile = null;
11677                }
11678
11679                if (uid < Process.FIRST_APPLICATION_UID
11680                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11681                    Slog.e(TAG, "Failed to finalize " + cid);
11682                    PackageHelper.destroySdDir(cid);
11683                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11684                }
11685
11686                boolean mounted = PackageHelper.isContainerMounted(cid);
11687                if (!mounted) {
11688                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11689                }
11690            }
11691            return status;
11692        }
11693
11694        private void cleanUp() {
11695            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11696
11697            // Destroy secure container
11698            PackageHelper.destroySdDir(cid);
11699        }
11700
11701        private List<String> getAllCodePaths() {
11702            final File codeFile = new File(getCodePath());
11703            if (codeFile != null && codeFile.exists()) {
11704                try {
11705                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11706                    return pkg.getAllCodePaths();
11707                } catch (PackageParserException e) {
11708                    // Ignored; we tried our best
11709                }
11710            }
11711            return Collections.EMPTY_LIST;
11712        }
11713
11714        void cleanUpResourcesLI() {
11715            // Enumerate all code paths before deleting
11716            cleanUpResourcesLI(getAllCodePaths());
11717        }
11718
11719        private void cleanUpResourcesLI(List<String> allCodePaths) {
11720            cleanUp();
11721            removeDexFiles(allCodePaths, instructionSets);
11722        }
11723
11724        String getPackageName() {
11725            return getAsecPackageName(cid);
11726        }
11727
11728        boolean doPostDeleteLI(boolean delete) {
11729            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11730            final List<String> allCodePaths = getAllCodePaths();
11731            boolean mounted = PackageHelper.isContainerMounted(cid);
11732            if (mounted) {
11733                // Unmount first
11734                if (PackageHelper.unMountSdDir(cid)) {
11735                    mounted = false;
11736                }
11737            }
11738            if (!mounted && delete) {
11739                cleanUpResourcesLI(allCodePaths);
11740            }
11741            return !mounted;
11742        }
11743
11744        @Override
11745        int doPreCopy() {
11746            if (isFwdLocked()) {
11747                if (!PackageHelper.fixSdPermissions(cid,
11748                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11749                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11750                }
11751            }
11752
11753            return PackageManager.INSTALL_SUCCEEDED;
11754        }
11755
11756        @Override
11757        int doPostCopy(int uid) {
11758            if (isFwdLocked()) {
11759                if (uid < Process.FIRST_APPLICATION_UID
11760                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11761                                RES_FILE_NAME)) {
11762                    Slog.e(TAG, "Failed to finalize " + cid);
11763                    PackageHelper.destroySdDir(cid);
11764                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11765                }
11766            }
11767
11768            return PackageManager.INSTALL_SUCCEEDED;
11769        }
11770    }
11771
11772    /**
11773     * Logic to handle movement of existing installed applications.
11774     */
11775    class MoveInstallArgs extends InstallArgs {
11776        private File codeFile;
11777        private File resourceFile;
11778
11779        /** New install */
11780        MoveInstallArgs(InstallParams params) {
11781            super(params.origin, params.move, params.observer, params.installFlags,
11782                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11783                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11784                    params.grantedRuntimePermissions,
11785                    params.traceMethod, params.traceCookie);
11786        }
11787
11788        int copyApk(IMediaContainerService imcs, boolean temp) {
11789            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11790                    + move.fromUuid + " to " + move.toUuid);
11791            synchronized (mInstaller) {
11792                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11793                        move.dataAppName, move.appId, move.seinfo) != 0) {
11794                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11795                }
11796            }
11797
11798            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11799            resourceFile = codeFile;
11800            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11801
11802            return PackageManager.INSTALL_SUCCEEDED;
11803        }
11804
11805        int doPreInstall(int status) {
11806            if (status != PackageManager.INSTALL_SUCCEEDED) {
11807                cleanUp(move.toUuid);
11808            }
11809            return status;
11810        }
11811
11812        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11813            if (status != PackageManager.INSTALL_SUCCEEDED) {
11814                cleanUp(move.toUuid);
11815                return false;
11816            }
11817
11818            // Reflect the move in app info
11819            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11820            pkg.applicationInfo.setCodePath(pkg.codePath);
11821            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11822            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11823            pkg.applicationInfo.setResourcePath(pkg.codePath);
11824            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11825            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11826
11827            return true;
11828        }
11829
11830        int doPostInstall(int status, int uid) {
11831            if (status == PackageManager.INSTALL_SUCCEEDED) {
11832                cleanUp(move.fromUuid);
11833            } else {
11834                cleanUp(move.toUuid);
11835            }
11836            return status;
11837        }
11838
11839        @Override
11840        String getCodePath() {
11841            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11842        }
11843
11844        @Override
11845        String getResourcePath() {
11846            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11847        }
11848
11849        private boolean cleanUp(String volumeUuid) {
11850            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11851                    move.dataAppName);
11852            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11853            synchronized (mInstallLock) {
11854                // Clean up both app data and code
11855                removeDataDirsLI(volumeUuid, move.packageName);
11856                if (codeFile.isDirectory()) {
11857                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11858                } else {
11859                    codeFile.delete();
11860                }
11861            }
11862            return true;
11863        }
11864
11865        void cleanUpResourcesLI() {
11866            throw new UnsupportedOperationException();
11867        }
11868
11869        boolean doPostDeleteLI(boolean delete) {
11870            throw new UnsupportedOperationException();
11871        }
11872    }
11873
11874    static String getAsecPackageName(String packageCid) {
11875        int idx = packageCid.lastIndexOf("-");
11876        if (idx == -1) {
11877            return packageCid;
11878        }
11879        return packageCid.substring(0, idx);
11880    }
11881
11882    // Utility method used to create code paths based on package name and available index.
11883    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11884        String idxStr = "";
11885        int idx = 1;
11886        // Fall back to default value of idx=1 if prefix is not
11887        // part of oldCodePath
11888        if (oldCodePath != null) {
11889            String subStr = oldCodePath;
11890            // Drop the suffix right away
11891            if (suffix != null && subStr.endsWith(suffix)) {
11892                subStr = subStr.substring(0, subStr.length() - suffix.length());
11893            }
11894            // If oldCodePath already contains prefix find out the
11895            // ending index to either increment or decrement.
11896            int sidx = subStr.lastIndexOf(prefix);
11897            if (sidx != -1) {
11898                subStr = subStr.substring(sidx + prefix.length());
11899                if (subStr != null) {
11900                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11901                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11902                    }
11903                    try {
11904                        idx = Integer.parseInt(subStr);
11905                        if (idx <= 1) {
11906                            idx++;
11907                        } else {
11908                            idx--;
11909                        }
11910                    } catch(NumberFormatException e) {
11911                    }
11912                }
11913            }
11914        }
11915        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11916        return prefix + idxStr;
11917    }
11918
11919    private File getNextCodePath(File targetDir, String packageName) {
11920        int suffix = 1;
11921        File result;
11922        do {
11923            result = new File(targetDir, packageName + "-" + suffix);
11924            suffix++;
11925        } while (result.exists());
11926        return result;
11927    }
11928
11929    // Utility method that returns the relative package path with respect
11930    // to the installation directory. Like say for /data/data/com.test-1.apk
11931    // string com.test-1 is returned.
11932    static String deriveCodePathName(String codePath) {
11933        if (codePath == null) {
11934            return null;
11935        }
11936        final File codeFile = new File(codePath);
11937        final String name = codeFile.getName();
11938        if (codeFile.isDirectory()) {
11939            return name;
11940        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11941            final int lastDot = name.lastIndexOf('.');
11942            return name.substring(0, lastDot);
11943        } else {
11944            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11945            return null;
11946        }
11947    }
11948
11949    class PackageInstalledInfo {
11950        String name;
11951        int uid;
11952        // The set of users that originally had this package installed.
11953        int[] origUsers;
11954        // The set of users that now have this package installed.
11955        int[] newUsers;
11956        PackageParser.Package pkg;
11957        int returnCode;
11958        String returnMsg;
11959        PackageRemovedInfo removedInfo;
11960
11961        public void setError(int code, String msg) {
11962            returnCode = code;
11963            returnMsg = msg;
11964            Slog.w(TAG, msg);
11965        }
11966
11967        public void setError(String msg, PackageParserException e) {
11968            returnCode = e.error;
11969            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11970            Slog.w(TAG, msg, e);
11971        }
11972
11973        public void setError(String msg, PackageManagerException e) {
11974            returnCode = e.error;
11975            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11976            Slog.w(TAG, msg, e);
11977        }
11978
11979        // In some error cases we want to convey more info back to the observer
11980        String origPackage;
11981        String origPermission;
11982    }
11983
11984    /*
11985     * Install a non-existing package.
11986     */
11987    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11988            UserHandle user, String installerPackageName, String volumeUuid,
11989            PackageInstalledInfo res) {
11990        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11991
11992        // Remember this for later, in case we need to rollback this install
11993        String pkgName = pkg.packageName;
11994
11995        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11996        // TODO: b/23350563
11997        final boolean dataDirExists = Environment
11998                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11999
12000        synchronized(mPackages) {
12001            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12002                // A package with the same name is already installed, though
12003                // it has been renamed to an older name.  The package we
12004                // are trying to install should be installed as an update to
12005                // the existing one, but that has not been requested, so bail.
12006                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12007                        + " without first uninstalling package running as "
12008                        + mSettings.mRenamedPackages.get(pkgName));
12009                return;
12010            }
12011            if (mPackages.containsKey(pkgName)) {
12012                // Don't allow installation over an existing package with the same name.
12013                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12014                        + " without first uninstalling.");
12015                return;
12016            }
12017        }
12018
12019        try {
12020            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12021                    System.currentTimeMillis(), user);
12022
12023            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12024            // delete the partially installed application. the data directory will have to be
12025            // restored if it was already existing
12026            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12027                // remove package from internal structures.  Note that we want deletePackageX to
12028                // delete the package data and cache directories that it created in
12029                // scanPackageLocked, unless those directories existed before we even tried to
12030                // install.
12031                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12032                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12033                                res.removedInfo, true);
12034            }
12035
12036        } catch (PackageManagerException e) {
12037            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12038        }
12039
12040        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12041    }
12042
12043    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12044        // Can't rotate keys during boot or if sharedUser.
12045        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12046                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12047            return false;
12048        }
12049        // app is using upgradeKeySets; make sure all are valid
12050        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12051        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12052        for (int i = 0; i < upgradeKeySets.length; i++) {
12053            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12054                Slog.wtf(TAG, "Package "
12055                         + (oldPs.name != null ? oldPs.name : "<null>")
12056                         + " contains upgrade-key-set reference to unknown key-set: "
12057                         + upgradeKeySets[i]
12058                         + " reverting to signatures check.");
12059                return false;
12060            }
12061        }
12062        return true;
12063    }
12064
12065    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12066        // Upgrade keysets are being used.  Determine if new package has a superset of the
12067        // required keys.
12068        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12069        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12070        for (int i = 0; i < upgradeKeySets.length; i++) {
12071            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12072            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12073                return true;
12074            }
12075        }
12076        return false;
12077    }
12078
12079    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12080            UserHandle user, String installerPackageName, String volumeUuid,
12081            PackageInstalledInfo res) {
12082        final PackageParser.Package oldPackage;
12083        final String pkgName = pkg.packageName;
12084        final int[] allUsers;
12085        final boolean[] perUserInstalled;
12086
12087        // First find the old package info and check signatures
12088        synchronized(mPackages) {
12089            oldPackage = mPackages.get(pkgName);
12090            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12091            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12092            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12093                if(!checkUpgradeKeySetLP(ps, pkg)) {
12094                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12095                            "New package not signed by keys specified by upgrade-keysets: "
12096                            + pkgName);
12097                    return;
12098                }
12099            } else {
12100                // default to original signature matching
12101                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12102                    != PackageManager.SIGNATURE_MATCH) {
12103                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12104                            "New package has a different signature: " + pkgName);
12105                    return;
12106                }
12107            }
12108
12109            // In case of rollback, remember per-user/profile install state
12110            allUsers = sUserManager.getUserIds();
12111            perUserInstalled = new boolean[allUsers.length];
12112            for (int i = 0; i < allUsers.length; i++) {
12113                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12114            }
12115        }
12116
12117        boolean sysPkg = (isSystemApp(oldPackage));
12118        if (sysPkg) {
12119            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12120                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12121        } else {
12122            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12123                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12124        }
12125    }
12126
12127    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12128            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12129            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12130            String volumeUuid, PackageInstalledInfo res) {
12131        String pkgName = deletedPackage.packageName;
12132        boolean deletedPkg = true;
12133        boolean updatedSettings = false;
12134
12135        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12136                + deletedPackage);
12137        long origUpdateTime;
12138        if (pkg.mExtras != null) {
12139            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12140        } else {
12141            origUpdateTime = 0;
12142        }
12143
12144        // First delete the existing package while retaining the data directory
12145        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12146                res.removedInfo, true)) {
12147            // If the existing package wasn't successfully deleted
12148            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12149            deletedPkg = false;
12150        } else {
12151            // Successfully deleted the old package; proceed with replace.
12152
12153            // If deleted package lived in a container, give users a chance to
12154            // relinquish resources before killing.
12155            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12156                if (DEBUG_INSTALL) {
12157                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12158                }
12159                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12160                final ArrayList<String> pkgList = new ArrayList<String>(1);
12161                pkgList.add(deletedPackage.applicationInfo.packageName);
12162                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12163            }
12164
12165            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12166            try {
12167                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12168                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12169                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12170                        perUserInstalled, res, user);
12171                updatedSettings = true;
12172            } catch (PackageManagerException e) {
12173                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12174            }
12175        }
12176
12177        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12178            // remove package from internal structures.  Note that we want deletePackageX to
12179            // delete the package data and cache directories that it created in
12180            // scanPackageLocked, unless those directories existed before we even tried to
12181            // install.
12182            if(updatedSettings) {
12183                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12184                deletePackageLI(
12185                        pkgName, null, true, allUsers, perUserInstalled,
12186                        PackageManager.DELETE_KEEP_DATA,
12187                                res.removedInfo, true);
12188            }
12189            // Since we failed to install the new package we need to restore the old
12190            // package that we deleted.
12191            if (deletedPkg) {
12192                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12193                File restoreFile = new File(deletedPackage.codePath);
12194                // Parse old package
12195                boolean oldExternal = isExternal(deletedPackage);
12196                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12197                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12198                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12199                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12200                try {
12201                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12202                            null);
12203                } catch (PackageManagerException e) {
12204                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12205                            + e.getMessage());
12206                    return;
12207                }
12208                // Restore of old package succeeded. Update permissions.
12209                // writer
12210                synchronized (mPackages) {
12211                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12212                            UPDATE_PERMISSIONS_ALL);
12213                    // can downgrade to reader
12214                    mSettings.writeLPr();
12215                }
12216                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12217            }
12218        }
12219    }
12220
12221    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12222            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12223            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12224            String volumeUuid, PackageInstalledInfo res) {
12225        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12226                + ", old=" + deletedPackage);
12227        boolean disabledSystem = false;
12228        boolean updatedSettings = false;
12229        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12230        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12231                != 0) {
12232            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12233        }
12234        String packageName = deletedPackage.packageName;
12235        if (packageName == null) {
12236            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12237                    "Attempt to delete null packageName.");
12238            return;
12239        }
12240        PackageParser.Package oldPkg;
12241        PackageSetting oldPkgSetting;
12242        // reader
12243        synchronized (mPackages) {
12244            oldPkg = mPackages.get(packageName);
12245            oldPkgSetting = mSettings.mPackages.get(packageName);
12246            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12247                    (oldPkgSetting == null)) {
12248                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12249                        "Couldn't find package:" + packageName + " information");
12250                return;
12251            }
12252        }
12253
12254        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12255
12256        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12257        res.removedInfo.removedPackage = packageName;
12258        // Remove existing system package
12259        removePackageLI(oldPkgSetting, true);
12260        // writer
12261        synchronized (mPackages) {
12262            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12263            if (!disabledSystem && deletedPackage != null) {
12264                // We didn't need to disable the .apk as a current system package,
12265                // which means we are replacing another update that is already
12266                // installed.  We need to make sure to delete the older one's .apk.
12267                res.removedInfo.args = createInstallArgsForExisting(0,
12268                        deletedPackage.applicationInfo.getCodePath(),
12269                        deletedPackage.applicationInfo.getResourcePath(),
12270                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12271            } else {
12272                res.removedInfo.args = null;
12273            }
12274        }
12275
12276        // Successfully disabled the old package. Now proceed with re-installation
12277        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12278
12279        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12280        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12281
12282        PackageParser.Package newPackage = null;
12283        try {
12284            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12285            if (newPackage.mExtras != null) {
12286                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12287                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12288                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12289
12290                // is the update attempting to change shared user? that isn't going to work...
12291                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12292                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12293                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12294                            + " to " + newPkgSetting.sharedUser);
12295                    updatedSettings = true;
12296                }
12297            }
12298
12299            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12300                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12301                        perUserInstalled, res, user);
12302                updatedSettings = true;
12303            }
12304
12305        } catch (PackageManagerException e) {
12306            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12307        }
12308
12309        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12310            // Re installation failed. Restore old information
12311            // Remove new pkg information
12312            if (newPackage != null) {
12313                removeInstalledPackageLI(newPackage, true);
12314            }
12315            // Add back the old system package
12316            try {
12317                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12318            } catch (PackageManagerException e) {
12319                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12320            }
12321            // Restore the old system information in Settings
12322            synchronized (mPackages) {
12323                if (disabledSystem) {
12324                    mSettings.enableSystemPackageLPw(packageName);
12325                }
12326                if (updatedSettings) {
12327                    mSettings.setInstallerPackageName(packageName,
12328                            oldPkgSetting.installerPackageName);
12329                }
12330                mSettings.writeLPr();
12331            }
12332        }
12333    }
12334
12335    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12336        // Collect all used permissions in the UID
12337        ArraySet<String> usedPermissions = new ArraySet<>();
12338        final int packageCount = su.packages.size();
12339        for (int i = 0; i < packageCount; i++) {
12340            PackageSetting ps = su.packages.valueAt(i);
12341            if (ps.pkg == null) {
12342                continue;
12343            }
12344            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12345            for (int j = 0; j < requestedPermCount; j++) {
12346                String permission = ps.pkg.requestedPermissions.get(j);
12347                BasePermission bp = mSettings.mPermissions.get(permission);
12348                if (bp != null) {
12349                    usedPermissions.add(permission);
12350                }
12351            }
12352        }
12353
12354        PermissionsState permissionsState = su.getPermissionsState();
12355        // Prune install permissions
12356        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12357        final int installPermCount = installPermStates.size();
12358        for (int i = installPermCount - 1; i >= 0;  i--) {
12359            PermissionState permissionState = installPermStates.get(i);
12360            if (!usedPermissions.contains(permissionState.getName())) {
12361                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12362                if (bp != null) {
12363                    permissionsState.revokeInstallPermission(bp);
12364                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12365                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12366                }
12367            }
12368        }
12369
12370        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12371
12372        // Prune runtime permissions
12373        for (int userId : allUserIds) {
12374            List<PermissionState> runtimePermStates = permissionsState
12375                    .getRuntimePermissionStates(userId);
12376            final int runtimePermCount = runtimePermStates.size();
12377            for (int i = runtimePermCount - 1; i >= 0; i--) {
12378                PermissionState permissionState = runtimePermStates.get(i);
12379                if (!usedPermissions.contains(permissionState.getName())) {
12380                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12381                    if (bp != null) {
12382                        permissionsState.revokeRuntimePermission(bp, userId);
12383                        permissionsState.updatePermissionFlags(bp, userId,
12384                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12385                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12386                                runtimePermissionChangedUserIds, userId);
12387                    }
12388                }
12389            }
12390        }
12391
12392        return runtimePermissionChangedUserIds;
12393    }
12394
12395    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12396            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12397            UserHandle user) {
12398        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12399
12400        String pkgName = newPackage.packageName;
12401        synchronized (mPackages) {
12402            //write settings. the installStatus will be incomplete at this stage.
12403            //note that the new package setting would have already been
12404            //added to mPackages. It hasn't been persisted yet.
12405            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12406            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12407            mSettings.writeLPr();
12408            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12409        }
12410
12411        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12412        synchronized (mPackages) {
12413            updatePermissionsLPw(newPackage.packageName, newPackage,
12414                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12415                            ? UPDATE_PERMISSIONS_ALL : 0));
12416            // For system-bundled packages, we assume that installing an upgraded version
12417            // of the package implies that the user actually wants to run that new code,
12418            // so we enable the package.
12419            PackageSetting ps = mSettings.mPackages.get(pkgName);
12420            if (ps != null) {
12421                if (isSystemApp(newPackage)) {
12422                    // NB: implicit assumption that system package upgrades apply to all users
12423                    if (DEBUG_INSTALL) {
12424                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12425                    }
12426                    if (res.origUsers != null) {
12427                        for (int userHandle : res.origUsers) {
12428                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12429                                    userHandle, installerPackageName);
12430                        }
12431                    }
12432                    // Also convey the prior install/uninstall state
12433                    if (allUsers != null && perUserInstalled != null) {
12434                        for (int i = 0; i < allUsers.length; i++) {
12435                            if (DEBUG_INSTALL) {
12436                                Slog.d(TAG, "    user " + allUsers[i]
12437                                        + " => " + perUserInstalled[i]);
12438                            }
12439                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12440                        }
12441                        // these install state changes will be persisted in the
12442                        // upcoming call to mSettings.writeLPr().
12443                    }
12444                }
12445                // It's implied that when a user requests installation, they want the app to be
12446                // installed and enabled.
12447                int userId = user.getIdentifier();
12448                if (userId != UserHandle.USER_ALL) {
12449                    ps.setInstalled(true, userId);
12450                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12451                }
12452            }
12453            res.name = pkgName;
12454            res.uid = newPackage.applicationInfo.uid;
12455            res.pkg = newPackage;
12456            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12457            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12458            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12459            //to update install status
12460            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12461            mSettings.writeLPr();
12462            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12463        }
12464
12465        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12466    }
12467
12468    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12469        try {
12470            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12471            installPackageLI(args, res);
12472        } finally {
12473            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12474        }
12475    }
12476
12477    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12478        final int installFlags = args.installFlags;
12479        final String installerPackageName = args.installerPackageName;
12480        final String volumeUuid = args.volumeUuid;
12481        final File tmpPackageFile = new File(args.getCodePath());
12482        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12483        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12484                || (args.volumeUuid != null));
12485        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12486        boolean replace = false;
12487        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12488        if (args.move != null) {
12489            // moving a complete application; perfom an initial scan on the new install location
12490            scanFlags |= SCAN_INITIAL;
12491        }
12492        // Result object to be returned
12493        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12494
12495        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12496
12497        // Retrieve PackageSettings and parse package
12498        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12499                | PackageParser.PARSE_ENFORCE_CODE
12500                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12501                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12502                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12503        PackageParser pp = new PackageParser();
12504        pp.setSeparateProcesses(mSeparateProcesses);
12505        pp.setDisplayMetrics(mMetrics);
12506
12507        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12508        final PackageParser.Package pkg;
12509        try {
12510            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12511        } catch (PackageParserException e) {
12512            res.setError("Failed parse during installPackageLI", e);
12513            return;
12514        } finally {
12515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12516        }
12517
12518        // Mark that we have an install time CPU ABI override.
12519        pkg.cpuAbiOverride = args.abiOverride;
12520
12521        String pkgName = res.name = pkg.packageName;
12522        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12523            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12524                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12525                return;
12526            }
12527        }
12528
12529        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12530        try {
12531            pp.collectCertificates(pkg, parseFlags);
12532        } catch (PackageParserException e) {
12533            res.setError("Failed collect during installPackageLI", e);
12534            return;
12535        } finally {
12536            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12537        }
12538
12539        /* If the installer passed in a manifest digest, compare it now. */
12540        if (args.manifestDigest != null) {
12541            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12542            try {
12543                pp.collectManifestDigest(pkg);
12544            } catch (PackageParserException e) {
12545                res.setError("Failed collect during installPackageLI", e);
12546                return;
12547            } finally {
12548                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12549            }
12550
12551            if (DEBUG_INSTALL) {
12552                final String parsedManifest = pkg.manifestDigest == null ? "null"
12553                        : pkg.manifestDigest.toString();
12554                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12555                        + parsedManifest);
12556            }
12557
12558            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12559                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12560                return;
12561            }
12562        } else if (DEBUG_INSTALL) {
12563            final String parsedManifest = pkg.manifestDigest == null
12564                    ? "null" : pkg.manifestDigest.toString();
12565            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12566        }
12567
12568        // Get rid of all references to package scan path via parser.
12569        pp = null;
12570        String oldCodePath = null;
12571        boolean systemApp = false;
12572        synchronized (mPackages) {
12573            // Check if installing already existing package
12574            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12575                String oldName = mSettings.mRenamedPackages.get(pkgName);
12576                if (pkg.mOriginalPackages != null
12577                        && pkg.mOriginalPackages.contains(oldName)
12578                        && mPackages.containsKey(oldName)) {
12579                    // This package is derived from an original package,
12580                    // and this device has been updating from that original
12581                    // name.  We must continue using the original name, so
12582                    // rename the new package here.
12583                    pkg.setPackageName(oldName);
12584                    pkgName = pkg.packageName;
12585                    replace = true;
12586                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12587                            + oldName + " pkgName=" + pkgName);
12588                } else if (mPackages.containsKey(pkgName)) {
12589                    // This package, under its official name, already exists
12590                    // on the device; we should replace it.
12591                    replace = true;
12592                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12593                }
12594
12595                // Prevent apps opting out from runtime permissions
12596                if (replace) {
12597                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12598                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12599                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12600                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12601                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12602                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12603                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12604                                        + " doesn't support runtime permissions but the old"
12605                                        + " target SDK " + oldTargetSdk + " does.");
12606                        return;
12607                    }
12608                }
12609            }
12610
12611            PackageSetting ps = mSettings.mPackages.get(pkgName);
12612            if (ps != null) {
12613                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12614
12615                // Quick sanity check that we're signed correctly if updating;
12616                // we'll check this again later when scanning, but we want to
12617                // bail early here before tripping over redefined permissions.
12618                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12619                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12620                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12621                                + pkg.packageName + " upgrade keys do not match the "
12622                                + "previously installed version");
12623                        return;
12624                    }
12625                } else {
12626                    try {
12627                        verifySignaturesLP(ps, pkg);
12628                    } catch (PackageManagerException e) {
12629                        res.setError(e.error, e.getMessage());
12630                        return;
12631                    }
12632                }
12633
12634                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12635                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12636                    systemApp = (ps.pkg.applicationInfo.flags &
12637                            ApplicationInfo.FLAG_SYSTEM) != 0;
12638                }
12639                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12640            }
12641
12642            // Check whether the newly-scanned package wants to define an already-defined perm
12643            int N = pkg.permissions.size();
12644            for (int i = N-1; i >= 0; i--) {
12645                PackageParser.Permission perm = pkg.permissions.get(i);
12646                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12647                if (bp != null) {
12648                    // If the defining package is signed with our cert, it's okay.  This
12649                    // also includes the "updating the same package" case, of course.
12650                    // "updating same package" could also involve key-rotation.
12651                    final boolean sigsOk;
12652                    if (bp.sourcePackage.equals(pkg.packageName)
12653                            && (bp.packageSetting instanceof PackageSetting)
12654                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12655                                    scanFlags))) {
12656                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12657                    } else {
12658                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12659                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12660                    }
12661                    if (!sigsOk) {
12662                        // If the owning package is the system itself, we log but allow
12663                        // install to proceed; we fail the install on all other permission
12664                        // redefinitions.
12665                        if (!bp.sourcePackage.equals("android")) {
12666                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12667                                    + pkg.packageName + " attempting to redeclare permission "
12668                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12669                            res.origPermission = perm.info.name;
12670                            res.origPackage = bp.sourcePackage;
12671                            return;
12672                        } else {
12673                            Slog.w(TAG, "Package " + pkg.packageName
12674                                    + " attempting to redeclare system permission "
12675                                    + perm.info.name + "; ignoring new declaration");
12676                            pkg.permissions.remove(i);
12677                        }
12678                    }
12679                }
12680            }
12681
12682        }
12683
12684        if (systemApp && onExternal) {
12685            // Disable updates to system apps on sdcard
12686            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12687                    "Cannot install updates to system apps on sdcard");
12688            return;
12689        }
12690
12691        if (args.move != null) {
12692            // We did an in-place move, so dex is ready to roll
12693            scanFlags |= SCAN_NO_DEX;
12694            scanFlags |= SCAN_MOVE;
12695
12696            synchronized (mPackages) {
12697                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12698                if (ps == null) {
12699                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12700                            "Missing settings for moved package " + pkgName);
12701                }
12702
12703                // We moved the entire application as-is, so bring over the
12704                // previously derived ABI information.
12705                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12706                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12707            }
12708
12709        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12710            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12711            scanFlags |= SCAN_NO_DEX;
12712
12713            try {
12714                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12715                        true /* extract libs */);
12716            } catch (PackageManagerException pme) {
12717                Slog.e(TAG, "Error deriving application ABI", pme);
12718                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12719                return;
12720            }
12721
12722            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12723            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12724
12725            int result = mPackageDexOptimizer
12726                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12727                            false /* defer */, false /* inclDependencies */,
12728                            true /*bootComplete*/, quickInstall /*useJit*/);
12729            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12730            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12731                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12732                return;
12733            }
12734        }
12735
12736        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12737            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12738            return;
12739        }
12740
12741        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12742
12743        if (replace) {
12744            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12745                    installerPackageName, volumeUuid, res);
12746        } else {
12747            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12748                    args.user, installerPackageName, volumeUuid, res);
12749        }
12750        synchronized (mPackages) {
12751            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12752            if (ps != null) {
12753                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12754            }
12755        }
12756    }
12757
12758    private void startIntentFilterVerifications(int userId, boolean replacing,
12759            PackageParser.Package pkg) {
12760        if (mIntentFilterVerifierComponent == null) {
12761            Slog.w(TAG, "No IntentFilter verification will not be done as "
12762                    + "there is no IntentFilterVerifier available!");
12763            return;
12764        }
12765
12766        final int verifierUid = getPackageUid(
12767                mIntentFilterVerifierComponent.getPackageName(),
12768                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12769
12770        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12771        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12772        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12773        mHandler.sendMessage(msg);
12774    }
12775
12776    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12777            PackageParser.Package pkg) {
12778        int size = pkg.activities.size();
12779        if (size == 0) {
12780            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12781                    "No activity, so no need to verify any IntentFilter!");
12782            return;
12783        }
12784
12785        final boolean hasDomainURLs = hasDomainURLs(pkg);
12786        if (!hasDomainURLs) {
12787            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12788                    "No domain URLs, so no need to verify any IntentFilter!");
12789            return;
12790        }
12791
12792        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12793                + " if any IntentFilter from the " + size
12794                + " Activities needs verification ...");
12795
12796        int count = 0;
12797        final String packageName = pkg.packageName;
12798
12799        synchronized (mPackages) {
12800            // If this is a new install and we see that we've already run verification for this
12801            // package, we have nothing to do: it means the state was restored from backup.
12802            if (!replacing) {
12803                IntentFilterVerificationInfo ivi =
12804                        mSettings.getIntentFilterVerificationLPr(packageName);
12805                if (ivi != null) {
12806                    if (DEBUG_DOMAIN_VERIFICATION) {
12807                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12808                                + ivi.getStatusString());
12809                    }
12810                    return;
12811                }
12812            }
12813
12814            // If any filters need to be verified, then all need to be.
12815            boolean needToVerify = false;
12816            for (PackageParser.Activity a : pkg.activities) {
12817                for (ActivityIntentInfo filter : a.intents) {
12818                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12819                        if (DEBUG_DOMAIN_VERIFICATION) {
12820                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12821                        }
12822                        needToVerify = true;
12823                        break;
12824                    }
12825                }
12826            }
12827
12828            if (needToVerify) {
12829                final int verificationId = mIntentFilterVerificationToken++;
12830                for (PackageParser.Activity a : pkg.activities) {
12831                    for (ActivityIntentInfo filter : a.intents) {
12832                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12833                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12834                                    "Verification needed for IntentFilter:" + filter.toString());
12835                            mIntentFilterVerifier.addOneIntentFilterVerification(
12836                                    verifierUid, userId, verificationId, filter, packageName);
12837                            count++;
12838                        }
12839                    }
12840                }
12841            }
12842        }
12843
12844        if (count > 0) {
12845            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12846                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12847                    +  " for userId:" + userId);
12848            mIntentFilterVerifier.startVerifications(userId);
12849        } else {
12850            if (DEBUG_DOMAIN_VERIFICATION) {
12851                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12852            }
12853        }
12854    }
12855
12856    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12857        final ComponentName cn  = filter.activity.getComponentName();
12858        final String packageName = cn.getPackageName();
12859
12860        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12861                packageName);
12862        if (ivi == null) {
12863            return true;
12864        }
12865        int status = ivi.getStatus();
12866        switch (status) {
12867            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12868            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12869                return true;
12870
12871            default:
12872                // Nothing to do
12873                return false;
12874        }
12875    }
12876
12877    private static boolean isMultiArch(PackageSetting ps) {
12878        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12879    }
12880
12881    private static boolean isMultiArch(ApplicationInfo info) {
12882        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12883    }
12884
12885    private static boolean isExternal(PackageParser.Package pkg) {
12886        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12887    }
12888
12889    private static boolean isExternal(PackageSetting ps) {
12890        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12891    }
12892
12893    private static boolean isExternal(ApplicationInfo info) {
12894        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12895    }
12896
12897    private static boolean isSystemApp(PackageParser.Package pkg) {
12898        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12899    }
12900
12901    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12902        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12903    }
12904
12905    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12906        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12907    }
12908
12909    private static boolean isSystemApp(PackageSetting ps) {
12910        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12911    }
12912
12913    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12914        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12915    }
12916
12917    private int packageFlagsToInstallFlags(PackageSetting ps) {
12918        int installFlags = 0;
12919        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12920            // This existing package was an external ASEC install when we have
12921            // the external flag without a UUID
12922            installFlags |= PackageManager.INSTALL_EXTERNAL;
12923        }
12924        if (ps.isForwardLocked()) {
12925            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12926        }
12927        return installFlags;
12928    }
12929
12930    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12931        if (isExternal(pkg)) {
12932            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12933                return StorageManager.UUID_PRIMARY_PHYSICAL;
12934            } else {
12935                return pkg.volumeUuid;
12936            }
12937        } else {
12938            return StorageManager.UUID_PRIVATE_INTERNAL;
12939        }
12940    }
12941
12942    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12943        if (isExternal(pkg)) {
12944            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12945                return mSettings.getExternalVersion();
12946            } else {
12947                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12948            }
12949        } else {
12950            return mSettings.getInternalVersion();
12951        }
12952    }
12953
12954    private void deleteTempPackageFiles() {
12955        final FilenameFilter filter = new FilenameFilter() {
12956            public boolean accept(File dir, String name) {
12957                return name.startsWith("vmdl") && name.endsWith(".tmp");
12958            }
12959        };
12960        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12961            file.delete();
12962        }
12963    }
12964
12965    @Override
12966    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12967            int flags) {
12968        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12969                flags);
12970    }
12971
12972    @Override
12973    public void deletePackage(final String packageName,
12974            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12975        mContext.enforceCallingOrSelfPermission(
12976                android.Manifest.permission.DELETE_PACKAGES, null);
12977        Preconditions.checkNotNull(packageName);
12978        Preconditions.checkNotNull(observer);
12979        final int uid = Binder.getCallingUid();
12980        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
12981        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
12982        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
12983            mContext.enforceCallingPermission(
12984                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12985                    "deletePackage for user " + userId);
12986        }
12987
12988        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12989            try {
12990                observer.onPackageDeleted(packageName,
12991                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12992            } catch (RemoteException re) {
12993            }
12994            return;
12995        }
12996
12997        for (int currentUserId : users) {
12998            if (getBlockUninstallForUser(packageName, currentUserId)) {
12999                try {
13000                    observer.onPackageDeleted(packageName,
13001                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13002                } catch (RemoteException re) {
13003                }
13004                return;
13005            }
13006        }
13007
13008        if (DEBUG_REMOVE) {
13009            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13010        }
13011        // Queue up an async operation since the package deletion may take a little while.
13012        mHandler.post(new Runnable() {
13013            public void run() {
13014                mHandler.removeCallbacks(this);
13015                final int returnCode = deletePackageX(packageName, userId, flags);
13016                try {
13017                    observer.onPackageDeleted(packageName, returnCode, null);
13018                } catch (RemoteException e) {
13019                    Log.i(TAG, "Observer no longer exists.");
13020                } //end catch
13021            } //end run
13022        });
13023    }
13024
13025    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13026        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13027                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13028        try {
13029            if (dpm != null) {
13030                // Does the package contains the device owner?
13031                if (dpm.isDeviceOwnerPackage(packageName)) {
13032                    return true;
13033                }
13034                // Does it contain a device admin for any user?
13035                int[] users;
13036                if (userId == UserHandle.USER_ALL) {
13037                    users = sUserManager.getUserIds();
13038                } else {
13039                    users = new int[]{userId};
13040                }
13041                for (int i = 0; i < users.length; ++i) {
13042                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13043                        return true;
13044                    }
13045                }
13046            }
13047        } catch (RemoteException e) {
13048        }
13049        return false;
13050    }
13051
13052    /**
13053     *  This method is an internal method that could be get invoked either
13054     *  to delete an installed package or to clean up a failed installation.
13055     *  After deleting an installed package, a broadcast is sent to notify any
13056     *  listeners that the package has been installed. For cleaning up a failed
13057     *  installation, the broadcast is not necessary since the package's
13058     *  installation wouldn't have sent the initial broadcast either
13059     *  The key steps in deleting a package are
13060     *  deleting the package information in internal structures like mPackages,
13061     *  deleting the packages base directories through installd
13062     *  updating mSettings to reflect current status
13063     *  persisting settings for later use
13064     *  sending a broadcast if necessary
13065     */
13066    private int deletePackageX(String packageName, int userId, int flags) {
13067        final PackageRemovedInfo info = new PackageRemovedInfo();
13068        final boolean res;
13069
13070        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13071                ? UserHandle.ALL : new UserHandle(userId);
13072
13073        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13074            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13075            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13076        }
13077
13078        boolean removedForAllUsers = false;
13079        boolean systemUpdate = false;
13080
13081        // for the uninstall-updates case and restricted profiles, remember the per-
13082        // userhandle installed state
13083        int[] allUsers;
13084        boolean[] perUserInstalled;
13085        synchronized (mPackages) {
13086            PackageSetting ps = mSettings.mPackages.get(packageName);
13087            allUsers = sUserManager.getUserIds();
13088            perUserInstalled = new boolean[allUsers.length];
13089            for (int i = 0; i < allUsers.length; i++) {
13090                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13091            }
13092        }
13093
13094        synchronized (mInstallLock) {
13095            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13096            res = deletePackageLI(packageName, removeForUser,
13097                    true, allUsers, perUserInstalled,
13098                    flags | REMOVE_CHATTY, info, true);
13099            systemUpdate = info.isRemovedPackageSystemUpdate;
13100            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13101                removedForAllUsers = true;
13102            }
13103            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13104                    + " removedForAllUsers=" + removedForAllUsers);
13105        }
13106
13107        if (res) {
13108            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13109
13110            // If the removed package was a system update, the old system package
13111            // was re-enabled; we need to broadcast this information
13112            if (systemUpdate) {
13113                Bundle extras = new Bundle(1);
13114                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13115                        ? info.removedAppId : info.uid);
13116                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13117
13118                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13119                        extras, null, null, null);
13120                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13121                        extras, null, null, null);
13122                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13123                        null, packageName, null, null);
13124            }
13125        }
13126        // Force a gc here.
13127        Runtime.getRuntime().gc();
13128        // Delete the resources here after sending the broadcast to let
13129        // other processes clean up before deleting resources.
13130        if (info.args != null) {
13131            synchronized (mInstallLock) {
13132                info.args.doPostDeleteLI(true);
13133            }
13134        }
13135
13136        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13137    }
13138
13139    class PackageRemovedInfo {
13140        String removedPackage;
13141        int uid = -1;
13142        int removedAppId = -1;
13143        int[] removedUsers = null;
13144        boolean isRemovedPackageSystemUpdate = false;
13145        // Clean up resources deleted packages.
13146        InstallArgs args = null;
13147
13148        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13149            Bundle extras = new Bundle(1);
13150            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13151            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13152            if (replacing) {
13153                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13154            }
13155            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13156            if (removedPackage != null) {
13157                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13158                        extras, null, null, removedUsers);
13159                if (fullRemove && !replacing) {
13160                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13161                            extras, null, null, removedUsers);
13162                }
13163            }
13164            if (removedAppId >= 0) {
13165                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13166                        removedUsers);
13167            }
13168        }
13169    }
13170
13171    /*
13172     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13173     * flag is not set, the data directory is removed as well.
13174     * make sure this flag is set for partially installed apps. If not its meaningless to
13175     * delete a partially installed application.
13176     */
13177    private void removePackageDataLI(PackageSetting ps,
13178            int[] allUserHandles, boolean[] perUserInstalled,
13179            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13180        String packageName = ps.name;
13181        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13182        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13183        // Retrieve object to delete permissions for shared user later on
13184        final PackageSetting deletedPs;
13185        // reader
13186        synchronized (mPackages) {
13187            deletedPs = mSettings.mPackages.get(packageName);
13188            if (outInfo != null) {
13189                outInfo.removedPackage = packageName;
13190                outInfo.removedUsers = deletedPs != null
13191                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13192                        : null;
13193            }
13194        }
13195        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13196            removeDataDirsLI(ps.volumeUuid, packageName);
13197            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13198        }
13199        // writer
13200        synchronized (mPackages) {
13201            if (deletedPs != null) {
13202                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13203                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13204                    clearDefaultBrowserIfNeeded(packageName);
13205                    if (outInfo != null) {
13206                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13207                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13208                    }
13209                    updatePermissionsLPw(deletedPs.name, null, 0);
13210                    if (deletedPs.sharedUser != null) {
13211                        // Remove permissions associated with package. Since runtime
13212                        // permissions are per user we have to kill the removed package
13213                        // or packages running under the shared user of the removed
13214                        // package if revoking the permissions requested only by the removed
13215                        // package is successful and this causes a change in gids.
13216                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13217                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13218                                    userId);
13219                            if (userIdToKill == UserHandle.USER_ALL
13220                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13221                                // If gids changed for this user, kill all affected packages.
13222                                mHandler.post(new Runnable() {
13223                                    @Override
13224                                    public void run() {
13225                                        // This has to happen with no lock held.
13226                                        killApplication(deletedPs.name, deletedPs.appId,
13227                                                KILL_APP_REASON_GIDS_CHANGED);
13228                                    }
13229                                });
13230                                break;
13231                            }
13232                        }
13233                    }
13234                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13235                }
13236                // make sure to preserve per-user disabled state if this removal was just
13237                // a downgrade of a system app to the factory package
13238                if (allUserHandles != null && perUserInstalled != null) {
13239                    if (DEBUG_REMOVE) {
13240                        Slog.d(TAG, "Propagating install state across downgrade");
13241                    }
13242                    for (int i = 0; i < allUserHandles.length; i++) {
13243                        if (DEBUG_REMOVE) {
13244                            Slog.d(TAG, "    user " + allUserHandles[i]
13245                                    + " => " + perUserInstalled[i]);
13246                        }
13247                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13248                    }
13249                }
13250            }
13251            // can downgrade to reader
13252            if (writeSettings) {
13253                // Save settings now
13254                mSettings.writeLPr();
13255            }
13256        }
13257        if (outInfo != null) {
13258            // A user ID was deleted here. Go through all users and remove it
13259            // from KeyStore.
13260            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13261        }
13262    }
13263
13264    static boolean locationIsPrivileged(File path) {
13265        try {
13266            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13267                    .getCanonicalPath();
13268            return path.getCanonicalPath().startsWith(privilegedAppDir);
13269        } catch (IOException e) {
13270            Slog.e(TAG, "Unable to access code path " + path);
13271        }
13272        return false;
13273    }
13274
13275    /*
13276     * Tries to delete system package.
13277     */
13278    private boolean deleteSystemPackageLI(PackageSetting newPs,
13279            int[] allUserHandles, boolean[] perUserInstalled,
13280            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13281        final boolean applyUserRestrictions
13282                = (allUserHandles != null) && (perUserInstalled != null);
13283        PackageSetting disabledPs = null;
13284        // Confirm if the system package has been updated
13285        // An updated system app can be deleted. This will also have to restore
13286        // the system pkg from system partition
13287        // reader
13288        synchronized (mPackages) {
13289            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13290        }
13291        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13292                + " disabledPs=" + disabledPs);
13293        if (disabledPs == null) {
13294            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13295            return false;
13296        } else if (DEBUG_REMOVE) {
13297            Slog.d(TAG, "Deleting system pkg from data partition");
13298        }
13299        if (DEBUG_REMOVE) {
13300            if (applyUserRestrictions) {
13301                Slog.d(TAG, "Remembering install states:");
13302                for (int i = 0; i < allUserHandles.length; i++) {
13303                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13304                }
13305            }
13306        }
13307        // Delete the updated package
13308        outInfo.isRemovedPackageSystemUpdate = true;
13309        if (disabledPs.versionCode < newPs.versionCode) {
13310            // Delete data for downgrades
13311            flags &= ~PackageManager.DELETE_KEEP_DATA;
13312        } else {
13313            // Preserve data by setting flag
13314            flags |= PackageManager.DELETE_KEEP_DATA;
13315        }
13316        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13317                allUserHandles, perUserInstalled, outInfo, writeSettings);
13318        if (!ret) {
13319            return false;
13320        }
13321        // writer
13322        synchronized (mPackages) {
13323            // Reinstate the old system package
13324            mSettings.enableSystemPackageLPw(newPs.name);
13325            // Remove any native libraries from the upgraded package.
13326            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13327        }
13328        // Install the system package
13329        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13330        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13331        if (locationIsPrivileged(disabledPs.codePath)) {
13332            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13333        }
13334
13335        final PackageParser.Package newPkg;
13336        try {
13337            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13338        } catch (PackageManagerException e) {
13339            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13340            return false;
13341        }
13342
13343        // writer
13344        synchronized (mPackages) {
13345            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13346
13347            // Propagate the permissions state as we do not want to drop on the floor
13348            // runtime permissions. The update permissions method below will take
13349            // care of removing obsolete permissions and grant install permissions.
13350            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13351            updatePermissionsLPw(newPkg.packageName, newPkg,
13352                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13353
13354            if (applyUserRestrictions) {
13355                if (DEBUG_REMOVE) {
13356                    Slog.d(TAG, "Propagating install state across reinstall");
13357                }
13358                for (int i = 0; i < allUserHandles.length; i++) {
13359                    if (DEBUG_REMOVE) {
13360                        Slog.d(TAG, "    user " + allUserHandles[i]
13361                                + " => " + perUserInstalled[i]);
13362                    }
13363                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13364
13365                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13366                }
13367                // Regardless of writeSettings we need to ensure that this restriction
13368                // state propagation is persisted
13369                mSettings.writeAllUsersPackageRestrictionsLPr();
13370            }
13371            // can downgrade to reader here
13372            if (writeSettings) {
13373                mSettings.writeLPr();
13374            }
13375        }
13376        return true;
13377    }
13378
13379    private boolean deleteInstalledPackageLI(PackageSetting ps,
13380            boolean deleteCodeAndResources, int flags,
13381            int[] allUserHandles, boolean[] perUserInstalled,
13382            PackageRemovedInfo outInfo, boolean writeSettings) {
13383        if (outInfo != null) {
13384            outInfo.uid = ps.appId;
13385        }
13386
13387        // Delete package data from internal structures and also remove data if flag is set
13388        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13389
13390        // Delete application code and resources
13391        if (deleteCodeAndResources && (outInfo != null)) {
13392            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13393                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13394            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13395        }
13396        return true;
13397    }
13398
13399    @Override
13400    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13401            int userId) {
13402        mContext.enforceCallingOrSelfPermission(
13403                android.Manifest.permission.DELETE_PACKAGES, null);
13404        synchronized (mPackages) {
13405            PackageSetting ps = mSettings.mPackages.get(packageName);
13406            if (ps == null) {
13407                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13408                return false;
13409            }
13410            if (!ps.getInstalled(userId)) {
13411                // Can't block uninstall for an app that is not installed or enabled.
13412                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13413                return false;
13414            }
13415            ps.setBlockUninstall(blockUninstall, userId);
13416            mSettings.writePackageRestrictionsLPr(userId);
13417        }
13418        return true;
13419    }
13420
13421    @Override
13422    public boolean getBlockUninstallForUser(String packageName, int userId) {
13423        synchronized (mPackages) {
13424            PackageSetting ps = mSettings.mPackages.get(packageName);
13425            if (ps == null) {
13426                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13427                return false;
13428            }
13429            return ps.getBlockUninstall(userId);
13430        }
13431    }
13432
13433    /*
13434     * This method handles package deletion in general
13435     */
13436    private boolean deletePackageLI(String packageName, UserHandle user,
13437            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13438            int flags, PackageRemovedInfo outInfo,
13439            boolean writeSettings) {
13440        if (packageName == null) {
13441            Slog.w(TAG, "Attempt to delete null packageName.");
13442            return false;
13443        }
13444        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13445        PackageSetting ps;
13446        boolean dataOnly = false;
13447        int removeUser = -1;
13448        int appId = -1;
13449        synchronized (mPackages) {
13450            ps = mSettings.mPackages.get(packageName);
13451            if (ps == null) {
13452                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13453                return false;
13454            }
13455            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13456                    && user.getIdentifier() != UserHandle.USER_ALL) {
13457                // The caller is asking that the package only be deleted for a single
13458                // user.  To do this, we just mark its uninstalled state and delete
13459                // its data.  If this is a system app, we only allow this to happen if
13460                // they have set the special DELETE_SYSTEM_APP which requests different
13461                // semantics than normal for uninstalling system apps.
13462                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13463                final int userId = user.getIdentifier();
13464                ps.setUserState(userId,
13465                        COMPONENT_ENABLED_STATE_DEFAULT,
13466                        false, //installed
13467                        true,  //stopped
13468                        true,  //notLaunched
13469                        false, //hidden
13470                        null, null, null,
13471                        false, // blockUninstall
13472                        ps.readUserState(userId).domainVerificationStatus, 0);
13473                if (!isSystemApp(ps)) {
13474                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13475                        // Other user still have this package installed, so all
13476                        // we need to do is clear this user's data and save that
13477                        // it is uninstalled.
13478                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13479                        removeUser = user.getIdentifier();
13480                        appId = ps.appId;
13481                        scheduleWritePackageRestrictionsLocked(removeUser);
13482                    } else {
13483                        // We need to set it back to 'installed' so the uninstall
13484                        // broadcasts will be sent correctly.
13485                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13486                        ps.setInstalled(true, user.getIdentifier());
13487                    }
13488                } else {
13489                    // This is a system app, so we assume that the
13490                    // other users still have this package installed, so all
13491                    // we need to do is clear this user's data and save that
13492                    // it is uninstalled.
13493                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13494                    removeUser = user.getIdentifier();
13495                    appId = ps.appId;
13496                    scheduleWritePackageRestrictionsLocked(removeUser);
13497                }
13498            }
13499        }
13500
13501        if (removeUser >= 0) {
13502            // From above, we determined that we are deleting this only
13503            // for a single user.  Continue the work here.
13504            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13505            if (outInfo != null) {
13506                outInfo.removedPackage = packageName;
13507                outInfo.removedAppId = appId;
13508                outInfo.removedUsers = new int[] {removeUser};
13509            }
13510            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13511            removeKeystoreDataIfNeeded(removeUser, appId);
13512            schedulePackageCleaning(packageName, removeUser, false);
13513            synchronized (mPackages) {
13514                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13515                    scheduleWritePackageRestrictionsLocked(removeUser);
13516                }
13517                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13518            }
13519            return true;
13520        }
13521
13522        if (dataOnly) {
13523            // Delete application data first
13524            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13525            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13526            return true;
13527        }
13528
13529        boolean ret = false;
13530        if (isSystemApp(ps)) {
13531            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13532            // When an updated system application is deleted we delete the existing resources as well and
13533            // fall back to existing code in system partition
13534            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13535                    flags, outInfo, writeSettings);
13536        } else {
13537            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13538            // Kill application pre-emptively especially for apps on sd.
13539            killApplication(packageName, ps.appId, "uninstall pkg");
13540            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13541                    allUserHandles, perUserInstalled,
13542                    outInfo, writeSettings);
13543        }
13544
13545        return ret;
13546    }
13547
13548    private final class ClearStorageConnection implements ServiceConnection {
13549        IMediaContainerService mContainerService;
13550
13551        @Override
13552        public void onServiceConnected(ComponentName name, IBinder service) {
13553            synchronized (this) {
13554                mContainerService = IMediaContainerService.Stub.asInterface(service);
13555                notifyAll();
13556            }
13557        }
13558
13559        @Override
13560        public void onServiceDisconnected(ComponentName name) {
13561        }
13562    }
13563
13564    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13565        final boolean mounted;
13566        if (Environment.isExternalStorageEmulated()) {
13567            mounted = true;
13568        } else {
13569            final String status = Environment.getExternalStorageState();
13570
13571            mounted = status.equals(Environment.MEDIA_MOUNTED)
13572                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13573        }
13574
13575        if (!mounted) {
13576            return;
13577        }
13578
13579        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13580        int[] users;
13581        if (userId == UserHandle.USER_ALL) {
13582            users = sUserManager.getUserIds();
13583        } else {
13584            users = new int[] { userId };
13585        }
13586        final ClearStorageConnection conn = new ClearStorageConnection();
13587        if (mContext.bindServiceAsUser(
13588                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13589            try {
13590                for (int curUser : users) {
13591                    long timeout = SystemClock.uptimeMillis() + 5000;
13592                    synchronized (conn) {
13593                        long now = SystemClock.uptimeMillis();
13594                        while (conn.mContainerService == null && now < timeout) {
13595                            try {
13596                                conn.wait(timeout - now);
13597                            } catch (InterruptedException e) {
13598                            }
13599                        }
13600                    }
13601                    if (conn.mContainerService == null) {
13602                        return;
13603                    }
13604
13605                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13606                    clearDirectory(conn.mContainerService,
13607                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13608                    if (allData) {
13609                        clearDirectory(conn.mContainerService,
13610                                userEnv.buildExternalStorageAppDataDirs(packageName));
13611                        clearDirectory(conn.mContainerService,
13612                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13613                    }
13614                }
13615            } finally {
13616                mContext.unbindService(conn);
13617            }
13618        }
13619    }
13620
13621    @Override
13622    public void clearApplicationUserData(final String packageName,
13623            final IPackageDataObserver observer, final int userId) {
13624        mContext.enforceCallingOrSelfPermission(
13625                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13626        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13627        // Queue up an async operation since the package deletion may take a little while.
13628        mHandler.post(new Runnable() {
13629            public void run() {
13630                mHandler.removeCallbacks(this);
13631                final boolean succeeded;
13632                synchronized (mInstallLock) {
13633                    succeeded = clearApplicationUserDataLI(packageName, userId);
13634                }
13635                clearExternalStorageDataSync(packageName, userId, true);
13636                if (succeeded) {
13637                    // invoke DeviceStorageMonitor's update method to clear any notifications
13638                    DeviceStorageMonitorInternal
13639                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13640                    if (dsm != null) {
13641                        dsm.checkMemory();
13642                    }
13643                }
13644                if(observer != null) {
13645                    try {
13646                        observer.onRemoveCompleted(packageName, succeeded);
13647                    } catch (RemoteException e) {
13648                        Log.i(TAG, "Observer no longer exists.");
13649                    }
13650                } //end if observer
13651            } //end run
13652        });
13653    }
13654
13655    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13656        if (packageName == null) {
13657            Slog.w(TAG, "Attempt to delete null packageName.");
13658            return false;
13659        }
13660
13661        // Try finding details about the requested package
13662        PackageParser.Package pkg;
13663        synchronized (mPackages) {
13664            pkg = mPackages.get(packageName);
13665            if (pkg == null) {
13666                final PackageSetting ps = mSettings.mPackages.get(packageName);
13667                if (ps != null) {
13668                    pkg = ps.pkg;
13669                }
13670            }
13671
13672            if (pkg == null) {
13673                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13674                return false;
13675            }
13676
13677            PackageSetting ps = (PackageSetting) pkg.mExtras;
13678            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13679        }
13680
13681        // Always delete data directories for package, even if we found no other
13682        // record of app. This helps users recover from UID mismatches without
13683        // resorting to a full data wipe.
13684        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13685        if (retCode < 0) {
13686            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13687            return false;
13688        }
13689
13690        final int appId = pkg.applicationInfo.uid;
13691        removeKeystoreDataIfNeeded(userId, appId);
13692
13693        // Create a native library symlink only if we have native libraries
13694        // and if the native libraries are 32 bit libraries. We do not provide
13695        // this symlink for 64 bit libraries.
13696        if (pkg.applicationInfo.primaryCpuAbi != null &&
13697                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13698            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13699            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13700                    nativeLibPath, userId) < 0) {
13701                Slog.w(TAG, "Failed linking native library dir");
13702                return false;
13703            }
13704        }
13705
13706        return true;
13707    }
13708
13709    /**
13710     * Reverts user permission state changes (permissions and flags) in
13711     * all packages for a given user.
13712     *
13713     * @param userId The device user for which to do a reset.
13714     */
13715    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13716        final int packageCount = mPackages.size();
13717        for (int i = 0; i < packageCount; i++) {
13718            PackageParser.Package pkg = mPackages.valueAt(i);
13719            PackageSetting ps = (PackageSetting) pkg.mExtras;
13720            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13721        }
13722    }
13723
13724    /**
13725     * Reverts user permission state changes (permissions and flags).
13726     *
13727     * @param ps The package for which to reset.
13728     * @param userId The device user for which to do a reset.
13729     */
13730    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13731            final PackageSetting ps, final int userId) {
13732        if (ps.pkg == null) {
13733            return;
13734        }
13735
13736        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13737                | FLAG_PERMISSION_USER_FIXED
13738                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13739
13740        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13741                | FLAG_PERMISSION_POLICY_FIXED;
13742
13743        boolean writeInstallPermissions = false;
13744        boolean writeRuntimePermissions = false;
13745
13746        final int permissionCount = ps.pkg.requestedPermissions.size();
13747        for (int i = 0; i < permissionCount; i++) {
13748            String permission = ps.pkg.requestedPermissions.get(i);
13749
13750            BasePermission bp = mSettings.mPermissions.get(permission);
13751            if (bp == null) {
13752                continue;
13753            }
13754
13755            // If shared user we just reset the state to which only this app contributed.
13756            if (ps.sharedUser != null) {
13757                boolean used = false;
13758                final int packageCount = ps.sharedUser.packages.size();
13759                for (int j = 0; j < packageCount; j++) {
13760                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13761                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13762                            && pkg.pkg.requestedPermissions.contains(permission)) {
13763                        used = true;
13764                        break;
13765                    }
13766                }
13767                if (used) {
13768                    continue;
13769                }
13770            }
13771
13772            PermissionsState permissionsState = ps.getPermissionsState();
13773
13774            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13775
13776            // Always clear the user settable flags.
13777            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13778                    bp.name) != null;
13779            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13780                if (hasInstallState) {
13781                    writeInstallPermissions = true;
13782                } else {
13783                    writeRuntimePermissions = true;
13784                }
13785            }
13786
13787            // Below is only runtime permission handling.
13788            if (!bp.isRuntime()) {
13789                continue;
13790            }
13791
13792            // Never clobber system or policy.
13793            if ((oldFlags & policyOrSystemFlags) != 0) {
13794                continue;
13795            }
13796
13797            // If this permission was granted by default, make sure it is.
13798            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13799                if (permissionsState.grantRuntimePermission(bp, userId)
13800                        != PERMISSION_OPERATION_FAILURE) {
13801                    writeRuntimePermissions = true;
13802                }
13803            } else {
13804                // Otherwise, reset the permission.
13805                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13806                switch (revokeResult) {
13807                    case PERMISSION_OPERATION_SUCCESS: {
13808                        writeRuntimePermissions = true;
13809                    } break;
13810
13811                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13812                        writeRuntimePermissions = true;
13813                        final int appId = ps.appId;
13814                        mHandler.post(new Runnable() {
13815                            @Override
13816                            public void run() {
13817                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13818                            }
13819                        });
13820                    } break;
13821                }
13822            }
13823        }
13824
13825        // Synchronously write as we are taking permissions away.
13826        if (writeRuntimePermissions) {
13827            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13828        }
13829
13830        // Synchronously write as we are taking permissions away.
13831        if (writeInstallPermissions) {
13832            mSettings.writeLPr();
13833        }
13834    }
13835
13836    /**
13837     * Remove entries from the keystore daemon. Will only remove it if the
13838     * {@code appId} is valid.
13839     */
13840    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13841        if (appId < 0) {
13842            return;
13843        }
13844
13845        final KeyStore keyStore = KeyStore.getInstance();
13846        if (keyStore != null) {
13847            if (userId == UserHandle.USER_ALL) {
13848                for (final int individual : sUserManager.getUserIds()) {
13849                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13850                }
13851            } else {
13852                keyStore.clearUid(UserHandle.getUid(userId, appId));
13853            }
13854        } else {
13855            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13856        }
13857    }
13858
13859    @Override
13860    public void deleteApplicationCacheFiles(final String packageName,
13861            final IPackageDataObserver observer) {
13862        mContext.enforceCallingOrSelfPermission(
13863                android.Manifest.permission.DELETE_CACHE_FILES, null);
13864        // Queue up an async operation since the package deletion may take a little while.
13865        final int userId = UserHandle.getCallingUserId();
13866        mHandler.post(new Runnable() {
13867            public void run() {
13868                mHandler.removeCallbacks(this);
13869                final boolean succeded;
13870                synchronized (mInstallLock) {
13871                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13872                }
13873                clearExternalStorageDataSync(packageName, userId, false);
13874                if (observer != null) {
13875                    try {
13876                        observer.onRemoveCompleted(packageName, succeded);
13877                    } catch (RemoteException e) {
13878                        Log.i(TAG, "Observer no longer exists.");
13879                    }
13880                } //end if observer
13881            } //end run
13882        });
13883    }
13884
13885    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13886        if (packageName == null) {
13887            Slog.w(TAG, "Attempt to delete null packageName.");
13888            return false;
13889        }
13890        PackageParser.Package p;
13891        synchronized (mPackages) {
13892            p = mPackages.get(packageName);
13893        }
13894        if (p == null) {
13895            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13896            return false;
13897        }
13898        final ApplicationInfo applicationInfo = p.applicationInfo;
13899        if (applicationInfo == null) {
13900            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13901            return false;
13902        }
13903        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13904        if (retCode < 0) {
13905            Slog.w(TAG, "Couldn't remove cache files for package: "
13906                       + packageName + " u" + userId);
13907            return false;
13908        }
13909        return true;
13910    }
13911
13912    @Override
13913    public void getPackageSizeInfo(final String packageName, int userHandle,
13914            final IPackageStatsObserver observer) {
13915        mContext.enforceCallingOrSelfPermission(
13916                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13917        if (packageName == null) {
13918            throw new IllegalArgumentException("Attempt to get size of null packageName");
13919        }
13920
13921        PackageStats stats = new PackageStats(packageName, userHandle);
13922
13923        /*
13924         * Queue up an async operation since the package measurement may take a
13925         * little while.
13926         */
13927        Message msg = mHandler.obtainMessage(INIT_COPY);
13928        msg.obj = new MeasureParams(stats, observer);
13929        mHandler.sendMessage(msg);
13930    }
13931
13932    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13933            PackageStats pStats) {
13934        if (packageName == null) {
13935            Slog.w(TAG, "Attempt to get size of null packageName.");
13936            return false;
13937        }
13938        PackageParser.Package p;
13939        boolean dataOnly = false;
13940        String libDirRoot = null;
13941        String asecPath = null;
13942        PackageSetting ps = null;
13943        synchronized (mPackages) {
13944            p = mPackages.get(packageName);
13945            ps = mSettings.mPackages.get(packageName);
13946            if(p == null) {
13947                dataOnly = true;
13948                if((ps == null) || (ps.pkg == null)) {
13949                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13950                    return false;
13951                }
13952                p = ps.pkg;
13953            }
13954            if (ps != null) {
13955                libDirRoot = ps.legacyNativeLibraryPathString;
13956            }
13957            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13958                final long token = Binder.clearCallingIdentity();
13959                try {
13960                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13961                    if (secureContainerId != null) {
13962                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13963                    }
13964                } finally {
13965                    Binder.restoreCallingIdentity(token);
13966                }
13967            }
13968        }
13969        String publicSrcDir = null;
13970        if(!dataOnly) {
13971            final ApplicationInfo applicationInfo = p.applicationInfo;
13972            if (applicationInfo == null) {
13973                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13974                return false;
13975            }
13976            if (p.isForwardLocked()) {
13977                publicSrcDir = applicationInfo.getBaseResourcePath();
13978            }
13979        }
13980        // TODO: extend to measure size of split APKs
13981        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13982        // not just the first level.
13983        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13984        // just the primary.
13985        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13986
13987        String apkPath;
13988        File packageDir = new File(p.codePath);
13989
13990        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13991            apkPath = packageDir.getAbsolutePath();
13992            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13993            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13994                libDirRoot = null;
13995            }
13996        } else {
13997            apkPath = p.baseCodePath;
13998        }
13999
14000        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14001                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14002        if (res < 0) {
14003            return false;
14004        }
14005
14006        // Fix-up for forward-locked applications in ASEC containers.
14007        if (!isExternal(p)) {
14008            pStats.codeSize += pStats.externalCodeSize;
14009            pStats.externalCodeSize = 0L;
14010        }
14011
14012        return true;
14013    }
14014
14015
14016    @Override
14017    public void addPackageToPreferred(String packageName) {
14018        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14019    }
14020
14021    @Override
14022    public void removePackageFromPreferred(String packageName) {
14023        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14024    }
14025
14026    @Override
14027    public List<PackageInfo> getPreferredPackages(int flags) {
14028        return new ArrayList<PackageInfo>();
14029    }
14030
14031    private int getUidTargetSdkVersionLockedLPr(int uid) {
14032        Object obj = mSettings.getUserIdLPr(uid);
14033        if (obj instanceof SharedUserSetting) {
14034            final SharedUserSetting sus = (SharedUserSetting) obj;
14035            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14036            final Iterator<PackageSetting> it = sus.packages.iterator();
14037            while (it.hasNext()) {
14038                final PackageSetting ps = it.next();
14039                if (ps.pkg != null) {
14040                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14041                    if (v < vers) vers = v;
14042                }
14043            }
14044            return vers;
14045        } else if (obj instanceof PackageSetting) {
14046            final PackageSetting ps = (PackageSetting) obj;
14047            if (ps.pkg != null) {
14048                return ps.pkg.applicationInfo.targetSdkVersion;
14049            }
14050        }
14051        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14052    }
14053
14054    @Override
14055    public void addPreferredActivity(IntentFilter filter, int match,
14056            ComponentName[] set, ComponentName activity, int userId) {
14057        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14058                "Adding preferred");
14059    }
14060
14061    private void addPreferredActivityInternal(IntentFilter filter, int match,
14062            ComponentName[] set, ComponentName activity, boolean always, int userId,
14063            String opname) {
14064        // writer
14065        int callingUid = Binder.getCallingUid();
14066        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14067        if (filter.countActions() == 0) {
14068            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14069            return;
14070        }
14071        synchronized (mPackages) {
14072            if (mContext.checkCallingOrSelfPermission(
14073                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14074                    != PackageManager.PERMISSION_GRANTED) {
14075                if (getUidTargetSdkVersionLockedLPr(callingUid)
14076                        < Build.VERSION_CODES.FROYO) {
14077                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14078                            + callingUid);
14079                    return;
14080                }
14081                mContext.enforceCallingOrSelfPermission(
14082                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14083            }
14084
14085            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14086            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14087                    + userId + ":");
14088            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14089            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14090            scheduleWritePackageRestrictionsLocked(userId);
14091        }
14092    }
14093
14094    @Override
14095    public void replacePreferredActivity(IntentFilter filter, int match,
14096            ComponentName[] set, ComponentName activity, int userId) {
14097        if (filter.countActions() != 1) {
14098            throw new IllegalArgumentException(
14099                    "replacePreferredActivity expects filter to have only 1 action.");
14100        }
14101        if (filter.countDataAuthorities() != 0
14102                || filter.countDataPaths() != 0
14103                || filter.countDataSchemes() > 1
14104                || filter.countDataTypes() != 0) {
14105            throw new IllegalArgumentException(
14106                    "replacePreferredActivity expects filter to have no data authorities, " +
14107                    "paths, or types; and at most one scheme.");
14108        }
14109
14110        final int callingUid = Binder.getCallingUid();
14111        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14112        synchronized (mPackages) {
14113            if (mContext.checkCallingOrSelfPermission(
14114                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14115                    != PackageManager.PERMISSION_GRANTED) {
14116                if (getUidTargetSdkVersionLockedLPr(callingUid)
14117                        < Build.VERSION_CODES.FROYO) {
14118                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14119                            + Binder.getCallingUid());
14120                    return;
14121                }
14122                mContext.enforceCallingOrSelfPermission(
14123                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14124            }
14125
14126            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14127            if (pir != null) {
14128                // Get all of the existing entries that exactly match this filter.
14129                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14130                if (existing != null && existing.size() == 1) {
14131                    PreferredActivity cur = existing.get(0);
14132                    if (DEBUG_PREFERRED) {
14133                        Slog.i(TAG, "Checking replace of preferred:");
14134                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14135                        if (!cur.mPref.mAlways) {
14136                            Slog.i(TAG, "  -- CUR; not mAlways!");
14137                        } else {
14138                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14139                            Slog.i(TAG, "  -- CUR: mSet="
14140                                    + Arrays.toString(cur.mPref.mSetComponents));
14141                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14142                            Slog.i(TAG, "  -- NEW: mMatch="
14143                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14144                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14145                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14146                        }
14147                    }
14148                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14149                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14150                            && cur.mPref.sameSet(set)) {
14151                        // Setting the preferred activity to what it happens to be already
14152                        if (DEBUG_PREFERRED) {
14153                            Slog.i(TAG, "Replacing with same preferred activity "
14154                                    + cur.mPref.mShortComponent + " for user "
14155                                    + userId + ":");
14156                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14157                        }
14158                        return;
14159                    }
14160                }
14161
14162                if (existing != null) {
14163                    if (DEBUG_PREFERRED) {
14164                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14165                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14166                    }
14167                    for (int i = 0; i < existing.size(); i++) {
14168                        PreferredActivity pa = existing.get(i);
14169                        if (DEBUG_PREFERRED) {
14170                            Slog.i(TAG, "Removing existing preferred activity "
14171                                    + pa.mPref.mComponent + ":");
14172                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14173                        }
14174                        pir.removeFilter(pa);
14175                    }
14176                }
14177            }
14178            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14179                    "Replacing preferred");
14180        }
14181    }
14182
14183    @Override
14184    public void clearPackagePreferredActivities(String packageName) {
14185        final int uid = Binder.getCallingUid();
14186        // writer
14187        synchronized (mPackages) {
14188            PackageParser.Package pkg = mPackages.get(packageName);
14189            if (pkg == null || pkg.applicationInfo.uid != uid) {
14190                if (mContext.checkCallingOrSelfPermission(
14191                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14192                        != PackageManager.PERMISSION_GRANTED) {
14193                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14194                            < Build.VERSION_CODES.FROYO) {
14195                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14196                                + Binder.getCallingUid());
14197                        return;
14198                    }
14199                    mContext.enforceCallingOrSelfPermission(
14200                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14201                }
14202            }
14203
14204            int user = UserHandle.getCallingUserId();
14205            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14206                scheduleWritePackageRestrictionsLocked(user);
14207            }
14208        }
14209    }
14210
14211    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14212    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14213        ArrayList<PreferredActivity> removed = null;
14214        boolean changed = false;
14215        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14216            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14217            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14218            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14219                continue;
14220            }
14221            Iterator<PreferredActivity> it = pir.filterIterator();
14222            while (it.hasNext()) {
14223                PreferredActivity pa = it.next();
14224                // Mark entry for removal only if it matches the package name
14225                // and the entry is of type "always".
14226                if (packageName == null ||
14227                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14228                                && pa.mPref.mAlways)) {
14229                    if (removed == null) {
14230                        removed = new ArrayList<PreferredActivity>();
14231                    }
14232                    removed.add(pa);
14233                }
14234            }
14235            if (removed != null) {
14236                for (int j=0; j<removed.size(); j++) {
14237                    PreferredActivity pa = removed.get(j);
14238                    pir.removeFilter(pa);
14239                }
14240                changed = true;
14241            }
14242        }
14243        return changed;
14244    }
14245
14246    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14247    private void clearIntentFilterVerificationsLPw(int userId) {
14248        final int packageCount = mPackages.size();
14249        for (int i = 0; i < packageCount; i++) {
14250            PackageParser.Package pkg = mPackages.valueAt(i);
14251            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14252        }
14253    }
14254
14255    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14256    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14257        if (userId == UserHandle.USER_ALL) {
14258            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14259                    sUserManager.getUserIds())) {
14260                for (int oneUserId : sUserManager.getUserIds()) {
14261                    scheduleWritePackageRestrictionsLocked(oneUserId);
14262                }
14263            }
14264        } else {
14265            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14266                scheduleWritePackageRestrictionsLocked(userId);
14267            }
14268        }
14269    }
14270
14271    void clearDefaultBrowserIfNeeded(String packageName) {
14272        for (int oneUserId : sUserManager.getUserIds()) {
14273            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14274            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14275            if (packageName.equals(defaultBrowserPackageName)) {
14276                setDefaultBrowserPackageName(null, oneUserId);
14277            }
14278        }
14279    }
14280
14281    @Override
14282    public void resetApplicationPreferences(int userId) {
14283        mContext.enforceCallingOrSelfPermission(
14284                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14285        // writer
14286        synchronized (mPackages) {
14287            final long identity = Binder.clearCallingIdentity();
14288            try {
14289                clearPackagePreferredActivitiesLPw(null, userId);
14290                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14291                // TODO: We have to reset the default SMS and Phone. This requires
14292                // significant refactoring to keep all default apps in the package
14293                // manager (cleaner but more work) or have the services provide
14294                // callbacks to the package manager to request a default app reset.
14295                applyFactoryDefaultBrowserLPw(userId);
14296                clearIntentFilterVerificationsLPw(userId);
14297                primeDomainVerificationsLPw(userId);
14298                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14299                scheduleWritePackageRestrictionsLocked(userId);
14300            } finally {
14301                Binder.restoreCallingIdentity(identity);
14302            }
14303        }
14304    }
14305
14306    @Override
14307    public int getPreferredActivities(List<IntentFilter> outFilters,
14308            List<ComponentName> outActivities, String packageName) {
14309
14310        int num = 0;
14311        final int userId = UserHandle.getCallingUserId();
14312        // reader
14313        synchronized (mPackages) {
14314            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14315            if (pir != null) {
14316                final Iterator<PreferredActivity> it = pir.filterIterator();
14317                while (it.hasNext()) {
14318                    final PreferredActivity pa = it.next();
14319                    if (packageName == null
14320                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14321                                    && pa.mPref.mAlways)) {
14322                        if (outFilters != null) {
14323                            outFilters.add(new IntentFilter(pa));
14324                        }
14325                        if (outActivities != null) {
14326                            outActivities.add(pa.mPref.mComponent);
14327                        }
14328                    }
14329                }
14330            }
14331        }
14332
14333        return num;
14334    }
14335
14336    @Override
14337    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14338            int userId) {
14339        int callingUid = Binder.getCallingUid();
14340        if (callingUid != Process.SYSTEM_UID) {
14341            throw new SecurityException(
14342                    "addPersistentPreferredActivity can only be run by the system");
14343        }
14344        if (filter.countActions() == 0) {
14345            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14346            return;
14347        }
14348        synchronized (mPackages) {
14349            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14350                    " :");
14351            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14352            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14353                    new PersistentPreferredActivity(filter, activity));
14354            scheduleWritePackageRestrictionsLocked(userId);
14355        }
14356    }
14357
14358    @Override
14359    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14360        int callingUid = Binder.getCallingUid();
14361        if (callingUid != Process.SYSTEM_UID) {
14362            throw new SecurityException(
14363                    "clearPackagePersistentPreferredActivities can only be run by the system");
14364        }
14365        ArrayList<PersistentPreferredActivity> removed = null;
14366        boolean changed = false;
14367        synchronized (mPackages) {
14368            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14369                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14370                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14371                        .valueAt(i);
14372                if (userId != thisUserId) {
14373                    continue;
14374                }
14375                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14376                while (it.hasNext()) {
14377                    PersistentPreferredActivity ppa = it.next();
14378                    // Mark entry for removal only if it matches the package name.
14379                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14380                        if (removed == null) {
14381                            removed = new ArrayList<PersistentPreferredActivity>();
14382                        }
14383                        removed.add(ppa);
14384                    }
14385                }
14386                if (removed != null) {
14387                    for (int j=0; j<removed.size(); j++) {
14388                        PersistentPreferredActivity ppa = removed.get(j);
14389                        ppir.removeFilter(ppa);
14390                    }
14391                    changed = true;
14392                }
14393            }
14394
14395            if (changed) {
14396                scheduleWritePackageRestrictionsLocked(userId);
14397            }
14398        }
14399    }
14400
14401    /**
14402     * Common machinery for picking apart a restored XML blob and passing
14403     * it to a caller-supplied functor to be applied to the running system.
14404     */
14405    private void restoreFromXml(XmlPullParser parser, int userId,
14406            String expectedStartTag, BlobXmlRestorer functor)
14407            throws IOException, XmlPullParserException {
14408        int type;
14409        while ((type = parser.next()) != XmlPullParser.START_TAG
14410                && type != XmlPullParser.END_DOCUMENT) {
14411        }
14412        if (type != XmlPullParser.START_TAG) {
14413            // oops didn't find a start tag?!
14414            if (DEBUG_BACKUP) {
14415                Slog.e(TAG, "Didn't find start tag during restore");
14416            }
14417            return;
14418        }
14419
14420        // this is supposed to be TAG_PREFERRED_BACKUP
14421        if (!expectedStartTag.equals(parser.getName())) {
14422            if (DEBUG_BACKUP) {
14423                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14424            }
14425            return;
14426        }
14427
14428        // skip interfering stuff, then we're aligned with the backing implementation
14429        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14430        functor.apply(parser, userId);
14431    }
14432
14433    private interface BlobXmlRestorer {
14434        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14435    }
14436
14437    /**
14438     * Non-Binder method, support for the backup/restore mechanism: write the
14439     * full set of preferred activities in its canonical XML format.  Returns the
14440     * XML output as a byte array, or null if there is none.
14441     */
14442    @Override
14443    public byte[] getPreferredActivityBackup(int userId) {
14444        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14445            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14446        }
14447
14448        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14449        try {
14450            final XmlSerializer serializer = new FastXmlSerializer();
14451            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14452            serializer.startDocument(null, true);
14453            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14454
14455            synchronized (mPackages) {
14456                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14457            }
14458
14459            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14460            serializer.endDocument();
14461            serializer.flush();
14462        } catch (Exception e) {
14463            if (DEBUG_BACKUP) {
14464                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14465            }
14466            return null;
14467        }
14468
14469        return dataStream.toByteArray();
14470    }
14471
14472    @Override
14473    public void restorePreferredActivities(byte[] backup, int userId) {
14474        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14475            throw new SecurityException("Only the system may call restorePreferredActivities()");
14476        }
14477
14478        try {
14479            final XmlPullParser parser = Xml.newPullParser();
14480            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14481            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14482                    new BlobXmlRestorer() {
14483                        @Override
14484                        public void apply(XmlPullParser parser, int userId)
14485                                throws XmlPullParserException, IOException {
14486                            synchronized (mPackages) {
14487                                mSettings.readPreferredActivitiesLPw(parser, userId);
14488                            }
14489                        }
14490                    } );
14491        } catch (Exception e) {
14492            if (DEBUG_BACKUP) {
14493                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14494            }
14495        }
14496    }
14497
14498    /**
14499     * Non-Binder method, support for the backup/restore mechanism: write the
14500     * default browser (etc) settings in its canonical XML format.  Returns the default
14501     * browser XML representation as a byte array, or null if there is none.
14502     */
14503    @Override
14504    public byte[] getDefaultAppsBackup(int userId) {
14505        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14506            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14507        }
14508
14509        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14510        try {
14511            final XmlSerializer serializer = new FastXmlSerializer();
14512            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14513            serializer.startDocument(null, true);
14514            serializer.startTag(null, TAG_DEFAULT_APPS);
14515
14516            synchronized (mPackages) {
14517                mSettings.writeDefaultAppsLPr(serializer, userId);
14518            }
14519
14520            serializer.endTag(null, TAG_DEFAULT_APPS);
14521            serializer.endDocument();
14522            serializer.flush();
14523        } catch (Exception e) {
14524            if (DEBUG_BACKUP) {
14525                Slog.e(TAG, "Unable to write default apps for backup", e);
14526            }
14527            return null;
14528        }
14529
14530        return dataStream.toByteArray();
14531    }
14532
14533    @Override
14534    public void restoreDefaultApps(byte[] backup, int userId) {
14535        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14536            throw new SecurityException("Only the system may call restoreDefaultApps()");
14537        }
14538
14539        try {
14540            final XmlPullParser parser = Xml.newPullParser();
14541            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14542            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14543                    new BlobXmlRestorer() {
14544                        @Override
14545                        public void apply(XmlPullParser parser, int userId)
14546                                throws XmlPullParserException, IOException {
14547                            synchronized (mPackages) {
14548                                mSettings.readDefaultAppsLPw(parser, userId);
14549                            }
14550                        }
14551                    } );
14552        } catch (Exception e) {
14553            if (DEBUG_BACKUP) {
14554                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14555            }
14556        }
14557    }
14558
14559    @Override
14560    public byte[] getIntentFilterVerificationBackup(int userId) {
14561        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14562            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14563        }
14564
14565        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14566        try {
14567            final XmlSerializer serializer = new FastXmlSerializer();
14568            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14569            serializer.startDocument(null, true);
14570            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14571
14572            synchronized (mPackages) {
14573                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14574            }
14575
14576            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14577            serializer.endDocument();
14578            serializer.flush();
14579        } catch (Exception e) {
14580            if (DEBUG_BACKUP) {
14581                Slog.e(TAG, "Unable to write default apps for backup", e);
14582            }
14583            return null;
14584        }
14585
14586        return dataStream.toByteArray();
14587    }
14588
14589    @Override
14590    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14591        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14592            throw new SecurityException("Only the system may call restorePreferredActivities()");
14593        }
14594
14595        try {
14596            final XmlPullParser parser = Xml.newPullParser();
14597            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14598            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14599                    new BlobXmlRestorer() {
14600                        @Override
14601                        public void apply(XmlPullParser parser, int userId)
14602                                throws XmlPullParserException, IOException {
14603                            synchronized (mPackages) {
14604                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14605                                mSettings.writeLPr();
14606                            }
14607                        }
14608                    } );
14609        } catch (Exception e) {
14610            if (DEBUG_BACKUP) {
14611                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14612            }
14613        }
14614    }
14615
14616    @Override
14617    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14618            int sourceUserId, int targetUserId, int flags) {
14619        mContext.enforceCallingOrSelfPermission(
14620                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14621        int callingUid = Binder.getCallingUid();
14622        enforceOwnerRights(ownerPackage, callingUid);
14623        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14624        if (intentFilter.countActions() == 0) {
14625            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14626            return;
14627        }
14628        synchronized (mPackages) {
14629            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14630                    ownerPackage, targetUserId, flags);
14631            CrossProfileIntentResolver resolver =
14632                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14633            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14634            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14635            if (existing != null) {
14636                int size = existing.size();
14637                for (int i = 0; i < size; i++) {
14638                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14639                        return;
14640                    }
14641                }
14642            }
14643            resolver.addFilter(newFilter);
14644            scheduleWritePackageRestrictionsLocked(sourceUserId);
14645        }
14646    }
14647
14648    @Override
14649    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14650        mContext.enforceCallingOrSelfPermission(
14651                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14652        int callingUid = Binder.getCallingUid();
14653        enforceOwnerRights(ownerPackage, callingUid);
14654        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14655        synchronized (mPackages) {
14656            CrossProfileIntentResolver resolver =
14657                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14658            ArraySet<CrossProfileIntentFilter> set =
14659                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14660            for (CrossProfileIntentFilter filter : set) {
14661                if (filter.getOwnerPackage().equals(ownerPackage)) {
14662                    resolver.removeFilter(filter);
14663                }
14664            }
14665            scheduleWritePackageRestrictionsLocked(sourceUserId);
14666        }
14667    }
14668
14669    // Enforcing that callingUid is owning pkg on userId
14670    private void enforceOwnerRights(String pkg, int callingUid) {
14671        // The system owns everything.
14672        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14673            return;
14674        }
14675        int callingUserId = UserHandle.getUserId(callingUid);
14676        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14677        if (pi == null) {
14678            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14679                    + callingUserId);
14680        }
14681        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14682            throw new SecurityException("Calling uid " + callingUid
14683                    + " does not own package " + pkg);
14684        }
14685    }
14686
14687    @Override
14688    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14689        Intent intent = new Intent(Intent.ACTION_MAIN);
14690        intent.addCategory(Intent.CATEGORY_HOME);
14691
14692        final int callingUserId = UserHandle.getCallingUserId();
14693        List<ResolveInfo> list = queryIntentActivities(intent, null,
14694                PackageManager.GET_META_DATA, callingUserId);
14695        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14696                true, false, false, callingUserId);
14697
14698        allHomeCandidates.clear();
14699        if (list != null) {
14700            for (ResolveInfo ri : list) {
14701                allHomeCandidates.add(ri);
14702            }
14703        }
14704        return (preferred == null || preferred.activityInfo == null)
14705                ? null
14706                : new ComponentName(preferred.activityInfo.packageName,
14707                        preferred.activityInfo.name);
14708    }
14709
14710    @Override
14711    public void setApplicationEnabledSetting(String appPackageName,
14712            int newState, int flags, int userId, String callingPackage) {
14713        if (!sUserManager.exists(userId)) return;
14714        if (callingPackage == null) {
14715            callingPackage = Integer.toString(Binder.getCallingUid());
14716        }
14717        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14718    }
14719
14720    @Override
14721    public void setComponentEnabledSetting(ComponentName componentName,
14722            int newState, int flags, int userId) {
14723        if (!sUserManager.exists(userId)) return;
14724        setEnabledSetting(componentName.getPackageName(),
14725                componentName.getClassName(), newState, flags, userId, null);
14726    }
14727
14728    private void setEnabledSetting(final String packageName, String className, int newState,
14729            final int flags, int userId, String callingPackage) {
14730        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14731              || newState == COMPONENT_ENABLED_STATE_ENABLED
14732              || newState == COMPONENT_ENABLED_STATE_DISABLED
14733              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14734              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14735            throw new IllegalArgumentException("Invalid new component state: "
14736                    + newState);
14737        }
14738        PackageSetting pkgSetting;
14739        final int uid = Binder.getCallingUid();
14740        final int permission = mContext.checkCallingOrSelfPermission(
14741                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14742        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14743        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14744        boolean sendNow = false;
14745        boolean isApp = (className == null);
14746        String componentName = isApp ? packageName : className;
14747        int packageUid = -1;
14748        ArrayList<String> components;
14749
14750        // writer
14751        synchronized (mPackages) {
14752            pkgSetting = mSettings.mPackages.get(packageName);
14753            if (pkgSetting == null) {
14754                if (className == null) {
14755                    throw new IllegalArgumentException(
14756                            "Unknown package: " + packageName);
14757                }
14758                throw new IllegalArgumentException(
14759                        "Unknown component: " + packageName
14760                        + "/" + className);
14761            }
14762            // Allow root and verify that userId is not being specified by a different user
14763            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14764                throw new SecurityException(
14765                        "Permission Denial: attempt to change component state from pid="
14766                        + Binder.getCallingPid()
14767                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14768            }
14769            if (className == null) {
14770                // We're dealing with an application/package level state change
14771                if (pkgSetting.getEnabled(userId) == newState) {
14772                    // Nothing to do
14773                    return;
14774                }
14775                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14776                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14777                    // Don't care about who enables an app.
14778                    callingPackage = null;
14779                }
14780                pkgSetting.setEnabled(newState, userId, callingPackage);
14781                // pkgSetting.pkg.mSetEnabled = newState;
14782            } else {
14783                // We're dealing with a component level state change
14784                // First, verify that this is a valid class name.
14785                PackageParser.Package pkg = pkgSetting.pkg;
14786                if (pkg == null || !pkg.hasComponentClassName(className)) {
14787                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14788                        throw new IllegalArgumentException("Component class " + className
14789                                + " does not exist in " + packageName);
14790                    } else {
14791                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14792                                + className + " does not exist in " + packageName);
14793                    }
14794                }
14795                switch (newState) {
14796                case COMPONENT_ENABLED_STATE_ENABLED:
14797                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14798                        return;
14799                    }
14800                    break;
14801                case COMPONENT_ENABLED_STATE_DISABLED:
14802                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14803                        return;
14804                    }
14805                    break;
14806                case COMPONENT_ENABLED_STATE_DEFAULT:
14807                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14808                        return;
14809                    }
14810                    break;
14811                default:
14812                    Slog.e(TAG, "Invalid new component state: " + newState);
14813                    return;
14814                }
14815            }
14816            scheduleWritePackageRestrictionsLocked(userId);
14817            components = mPendingBroadcasts.get(userId, packageName);
14818            final boolean newPackage = components == null;
14819            if (newPackage) {
14820                components = new ArrayList<String>();
14821            }
14822            if (!components.contains(componentName)) {
14823                components.add(componentName);
14824            }
14825            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14826                sendNow = true;
14827                // Purge entry from pending broadcast list if another one exists already
14828                // since we are sending one right away.
14829                mPendingBroadcasts.remove(userId, packageName);
14830            } else {
14831                if (newPackage) {
14832                    mPendingBroadcasts.put(userId, packageName, components);
14833                }
14834                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14835                    // Schedule a message
14836                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14837                }
14838            }
14839        }
14840
14841        long callingId = Binder.clearCallingIdentity();
14842        try {
14843            if (sendNow) {
14844                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14845                sendPackageChangedBroadcast(packageName,
14846                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14847            }
14848        } finally {
14849            Binder.restoreCallingIdentity(callingId);
14850        }
14851    }
14852
14853    private void sendPackageChangedBroadcast(String packageName,
14854            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14855        if (DEBUG_INSTALL)
14856            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14857                    + componentNames);
14858        Bundle extras = new Bundle(4);
14859        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14860        String nameList[] = new String[componentNames.size()];
14861        componentNames.toArray(nameList);
14862        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14863        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14864        extras.putInt(Intent.EXTRA_UID, packageUid);
14865        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14866                new int[] {UserHandle.getUserId(packageUid)});
14867    }
14868
14869    @Override
14870    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14871        if (!sUserManager.exists(userId)) return;
14872        final int uid = Binder.getCallingUid();
14873        final int permission = mContext.checkCallingOrSelfPermission(
14874                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14875        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14876        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14877        // writer
14878        synchronized (mPackages) {
14879            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14880                    allowedByPermission, uid, userId)) {
14881                scheduleWritePackageRestrictionsLocked(userId);
14882            }
14883        }
14884    }
14885
14886    @Override
14887    public String getInstallerPackageName(String packageName) {
14888        // reader
14889        synchronized (mPackages) {
14890            return mSettings.getInstallerPackageNameLPr(packageName);
14891        }
14892    }
14893
14894    @Override
14895    public int getApplicationEnabledSetting(String packageName, int userId) {
14896        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14897        int uid = Binder.getCallingUid();
14898        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14899        // reader
14900        synchronized (mPackages) {
14901            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14902        }
14903    }
14904
14905    @Override
14906    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14907        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14908        int uid = Binder.getCallingUid();
14909        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14910        // reader
14911        synchronized (mPackages) {
14912            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14913        }
14914    }
14915
14916    @Override
14917    public void enterSafeMode() {
14918        enforceSystemOrRoot("Only the system can request entering safe mode");
14919
14920        if (!mSystemReady) {
14921            mSafeMode = true;
14922        }
14923    }
14924
14925    @Override
14926    public void systemReady() {
14927        mSystemReady = true;
14928
14929        // Read the compatibilty setting when the system is ready.
14930        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14931                mContext.getContentResolver(),
14932                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14933        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14934        if (DEBUG_SETTINGS) {
14935            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14936        }
14937
14938        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14939
14940        synchronized (mPackages) {
14941            // Verify that all of the preferred activity components actually
14942            // exist.  It is possible for applications to be updated and at
14943            // that point remove a previously declared activity component that
14944            // had been set as a preferred activity.  We try to clean this up
14945            // the next time we encounter that preferred activity, but it is
14946            // possible for the user flow to never be able to return to that
14947            // situation so here we do a sanity check to make sure we haven't
14948            // left any junk around.
14949            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14950            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14951                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14952                removed.clear();
14953                for (PreferredActivity pa : pir.filterSet()) {
14954                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14955                        removed.add(pa);
14956                    }
14957                }
14958                if (removed.size() > 0) {
14959                    for (int r=0; r<removed.size(); r++) {
14960                        PreferredActivity pa = removed.get(r);
14961                        Slog.w(TAG, "Removing dangling preferred activity: "
14962                                + pa.mPref.mComponent);
14963                        pir.removeFilter(pa);
14964                    }
14965                    mSettings.writePackageRestrictionsLPr(
14966                            mSettings.mPreferredActivities.keyAt(i));
14967                }
14968            }
14969
14970            for (int userId : UserManagerService.getInstance().getUserIds()) {
14971                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14972                    grantPermissionsUserIds = ArrayUtils.appendInt(
14973                            grantPermissionsUserIds, userId);
14974                }
14975            }
14976        }
14977        sUserManager.systemReady();
14978
14979        // If we upgraded grant all default permissions before kicking off.
14980        for (int userId : grantPermissionsUserIds) {
14981            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14982        }
14983
14984        // Kick off any messages waiting for system ready
14985        if (mPostSystemReadyMessages != null) {
14986            for (Message msg : mPostSystemReadyMessages) {
14987                msg.sendToTarget();
14988            }
14989            mPostSystemReadyMessages = null;
14990        }
14991
14992        // Watch for external volumes that come and go over time
14993        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14994        storage.registerListener(mStorageListener);
14995
14996        mInstallerService.systemReady();
14997        mPackageDexOptimizer.systemReady();
14998
14999        MountServiceInternal mountServiceInternal = LocalServices.getService(
15000                MountServiceInternal.class);
15001        mountServiceInternal.addExternalStoragePolicy(
15002                new MountServiceInternal.ExternalStorageMountPolicy() {
15003            @Override
15004            public int getMountMode(int uid, String packageName) {
15005                if (Process.isIsolated(uid)) {
15006                    return Zygote.MOUNT_EXTERNAL_NONE;
15007                }
15008                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15009                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15010                }
15011                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15012                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15013                }
15014                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15015                    return Zygote.MOUNT_EXTERNAL_READ;
15016                }
15017                return Zygote.MOUNT_EXTERNAL_WRITE;
15018            }
15019
15020            @Override
15021            public boolean hasExternalStorage(int uid, String packageName) {
15022                return true;
15023            }
15024        });
15025    }
15026
15027    @Override
15028    public boolean isSafeMode() {
15029        return mSafeMode;
15030    }
15031
15032    @Override
15033    public boolean hasSystemUidErrors() {
15034        return mHasSystemUidErrors;
15035    }
15036
15037    static String arrayToString(int[] array) {
15038        StringBuffer buf = new StringBuffer(128);
15039        buf.append('[');
15040        if (array != null) {
15041            for (int i=0; i<array.length; i++) {
15042                if (i > 0) buf.append(", ");
15043                buf.append(array[i]);
15044            }
15045        }
15046        buf.append(']');
15047        return buf.toString();
15048    }
15049
15050    static class DumpState {
15051        public static final int DUMP_LIBS = 1 << 0;
15052        public static final int DUMP_FEATURES = 1 << 1;
15053        public static final int DUMP_RESOLVERS = 1 << 2;
15054        public static final int DUMP_PERMISSIONS = 1 << 3;
15055        public static final int DUMP_PACKAGES = 1 << 4;
15056        public static final int DUMP_SHARED_USERS = 1 << 5;
15057        public static final int DUMP_MESSAGES = 1 << 6;
15058        public static final int DUMP_PROVIDERS = 1 << 7;
15059        public static final int DUMP_VERIFIERS = 1 << 8;
15060        public static final int DUMP_PREFERRED = 1 << 9;
15061        public static final int DUMP_PREFERRED_XML = 1 << 10;
15062        public static final int DUMP_KEYSETS = 1 << 11;
15063        public static final int DUMP_VERSION = 1 << 12;
15064        public static final int DUMP_INSTALLS = 1 << 13;
15065        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
15066        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
15067
15068        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15069
15070        private int mTypes;
15071
15072        private int mOptions;
15073
15074        private boolean mTitlePrinted;
15075
15076        private SharedUserSetting mSharedUser;
15077
15078        public boolean isDumping(int type) {
15079            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15080                return true;
15081            }
15082
15083            return (mTypes & type) != 0;
15084        }
15085
15086        public void setDump(int type) {
15087            mTypes |= type;
15088        }
15089
15090        public boolean isOptionEnabled(int option) {
15091            return (mOptions & option) != 0;
15092        }
15093
15094        public void setOptionEnabled(int option) {
15095            mOptions |= option;
15096        }
15097
15098        public boolean onTitlePrinted() {
15099            final boolean printed = mTitlePrinted;
15100            mTitlePrinted = true;
15101            return printed;
15102        }
15103
15104        public boolean getTitlePrinted() {
15105            return mTitlePrinted;
15106        }
15107
15108        public void setTitlePrinted(boolean enabled) {
15109            mTitlePrinted = enabled;
15110        }
15111
15112        public SharedUserSetting getSharedUser() {
15113            return mSharedUser;
15114        }
15115
15116        public void setSharedUser(SharedUserSetting user) {
15117            mSharedUser = user;
15118        }
15119    }
15120
15121    @Override
15122    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15123            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15124        (new PackageManagerShellCommand(this)).exec(
15125                this, in, out, err, args, resultReceiver);
15126    }
15127
15128    @Override
15129    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15130        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15131                != PackageManager.PERMISSION_GRANTED) {
15132            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15133                    + Binder.getCallingPid()
15134                    + ", uid=" + Binder.getCallingUid()
15135                    + " without permission "
15136                    + android.Manifest.permission.DUMP);
15137            return;
15138        }
15139
15140        DumpState dumpState = new DumpState();
15141        boolean fullPreferred = false;
15142        boolean checkin = false;
15143
15144        String packageName = null;
15145        ArraySet<String> permissionNames = null;
15146
15147        int opti = 0;
15148        while (opti < args.length) {
15149            String opt = args[opti];
15150            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15151                break;
15152            }
15153            opti++;
15154
15155            if ("-a".equals(opt)) {
15156                // Right now we only know how to print all.
15157            } else if ("-h".equals(opt)) {
15158                pw.println("Package manager dump options:");
15159                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15160                pw.println("    --checkin: dump for a checkin");
15161                pw.println("    -f: print details of intent filters");
15162                pw.println("    -h: print this help");
15163                pw.println("  cmd may be one of:");
15164                pw.println("    l[ibraries]: list known shared libraries");
15165                pw.println("    f[ibraries]: list device features");
15166                pw.println("    k[eysets]: print known keysets");
15167                pw.println("    r[esolvers]: dump intent resolvers");
15168                pw.println("    perm[issions]: dump permissions");
15169                pw.println("    permission [name ...]: dump declaration and use of given permission");
15170                pw.println("    pref[erred]: print preferred package settings");
15171                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15172                pw.println("    prov[iders]: dump content providers");
15173                pw.println("    p[ackages]: dump installed packages");
15174                pw.println("    s[hared-users]: dump shared user IDs");
15175                pw.println("    m[essages]: print collected runtime messages");
15176                pw.println("    v[erifiers]: print package verifier info");
15177                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15178                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15179                pw.println("    version: print database version info");
15180                pw.println("    write: write current settings now");
15181                pw.println("    installs: details about install sessions");
15182                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15183                pw.println("    <package.name>: info about given package");
15184                return;
15185            } else if ("--checkin".equals(opt)) {
15186                checkin = true;
15187            } else if ("-f".equals(opt)) {
15188                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15189            } else {
15190                pw.println("Unknown argument: " + opt + "; use -h for help");
15191            }
15192        }
15193
15194        // Is the caller requesting to dump a particular piece of data?
15195        if (opti < args.length) {
15196            String cmd = args[opti];
15197            opti++;
15198            // Is this a package name?
15199            if ("android".equals(cmd) || cmd.contains(".")) {
15200                packageName = cmd;
15201                // When dumping a single package, we always dump all of its
15202                // filter information since the amount of data will be reasonable.
15203                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15204            } else if ("check-permission".equals(cmd)) {
15205                if (opti >= args.length) {
15206                    pw.println("Error: check-permission missing permission argument");
15207                    return;
15208                }
15209                String perm = args[opti];
15210                opti++;
15211                if (opti >= args.length) {
15212                    pw.println("Error: check-permission missing package argument");
15213                    return;
15214                }
15215                String pkg = args[opti];
15216                opti++;
15217                int user = UserHandle.getUserId(Binder.getCallingUid());
15218                if (opti < args.length) {
15219                    try {
15220                        user = Integer.parseInt(args[opti]);
15221                    } catch (NumberFormatException e) {
15222                        pw.println("Error: check-permission user argument is not a number: "
15223                                + args[opti]);
15224                        return;
15225                    }
15226                }
15227                pw.println(checkPermission(perm, pkg, user));
15228                return;
15229            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15230                dumpState.setDump(DumpState.DUMP_LIBS);
15231            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15232                dumpState.setDump(DumpState.DUMP_FEATURES);
15233            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15234                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15235            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15236                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15237            } else if ("permission".equals(cmd)) {
15238                if (opti >= args.length) {
15239                    pw.println("Error: permission requires permission name");
15240                    return;
15241                }
15242                permissionNames = new ArraySet<>();
15243                while (opti < args.length) {
15244                    permissionNames.add(args[opti]);
15245                    opti++;
15246                }
15247                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15248                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15249            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15250                dumpState.setDump(DumpState.DUMP_PREFERRED);
15251            } else if ("preferred-xml".equals(cmd)) {
15252                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15253                if (opti < args.length && "--full".equals(args[opti])) {
15254                    fullPreferred = true;
15255                    opti++;
15256                }
15257            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15258                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15259            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15260                dumpState.setDump(DumpState.DUMP_PACKAGES);
15261            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15262                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15263            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15264                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15265            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15266                dumpState.setDump(DumpState.DUMP_MESSAGES);
15267            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15268                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15269            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15270                    || "intent-filter-verifiers".equals(cmd)) {
15271                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15272            } else if ("version".equals(cmd)) {
15273                dumpState.setDump(DumpState.DUMP_VERSION);
15274            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15275                dumpState.setDump(DumpState.DUMP_KEYSETS);
15276            } else if ("installs".equals(cmd)) {
15277                dumpState.setDump(DumpState.DUMP_INSTALLS);
15278            } else if ("write".equals(cmd)) {
15279                synchronized (mPackages) {
15280                    mSettings.writeLPr();
15281                    pw.println("Settings written.");
15282                    return;
15283                }
15284            }
15285        }
15286
15287        if (checkin) {
15288            pw.println("vers,1");
15289        }
15290
15291        // reader
15292        synchronized (mPackages) {
15293            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15294                if (!checkin) {
15295                    if (dumpState.onTitlePrinted())
15296                        pw.println();
15297                    pw.println("Database versions:");
15298                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15299                }
15300            }
15301
15302            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15303                if (!checkin) {
15304                    if (dumpState.onTitlePrinted())
15305                        pw.println();
15306                    pw.println("Verifiers:");
15307                    pw.print("  Required: ");
15308                    pw.print(mRequiredVerifierPackage);
15309                    pw.print(" (uid=");
15310                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15311                    pw.println(")");
15312                } else if (mRequiredVerifierPackage != null) {
15313                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15314                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15315                }
15316            }
15317
15318            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15319                    packageName == null) {
15320                if (mIntentFilterVerifierComponent != null) {
15321                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15322                    if (!checkin) {
15323                        if (dumpState.onTitlePrinted())
15324                            pw.println();
15325                        pw.println("Intent Filter Verifier:");
15326                        pw.print("  Using: ");
15327                        pw.print(verifierPackageName);
15328                        pw.print(" (uid=");
15329                        pw.print(getPackageUid(verifierPackageName, 0));
15330                        pw.println(")");
15331                    } else if (verifierPackageName != null) {
15332                        pw.print("ifv,"); pw.print(verifierPackageName);
15333                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15334                    }
15335                } else {
15336                    pw.println();
15337                    pw.println("No Intent Filter Verifier available!");
15338                }
15339            }
15340
15341            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15342                boolean printedHeader = false;
15343                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15344                while (it.hasNext()) {
15345                    String name = it.next();
15346                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15347                    if (!checkin) {
15348                        if (!printedHeader) {
15349                            if (dumpState.onTitlePrinted())
15350                                pw.println();
15351                            pw.println("Libraries:");
15352                            printedHeader = true;
15353                        }
15354                        pw.print("  ");
15355                    } else {
15356                        pw.print("lib,");
15357                    }
15358                    pw.print(name);
15359                    if (!checkin) {
15360                        pw.print(" -> ");
15361                    }
15362                    if (ent.path != null) {
15363                        if (!checkin) {
15364                            pw.print("(jar) ");
15365                            pw.print(ent.path);
15366                        } else {
15367                            pw.print(",jar,");
15368                            pw.print(ent.path);
15369                        }
15370                    } else {
15371                        if (!checkin) {
15372                            pw.print("(apk) ");
15373                            pw.print(ent.apk);
15374                        } else {
15375                            pw.print(",apk,");
15376                            pw.print(ent.apk);
15377                        }
15378                    }
15379                    pw.println();
15380                }
15381            }
15382
15383            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15384                if (dumpState.onTitlePrinted())
15385                    pw.println();
15386                if (!checkin) {
15387                    pw.println("Features:");
15388                }
15389                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15390                while (it.hasNext()) {
15391                    String name = it.next();
15392                    if (!checkin) {
15393                        pw.print("  ");
15394                    } else {
15395                        pw.print("feat,");
15396                    }
15397                    pw.println(name);
15398                }
15399            }
15400
15401            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15402                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15403                        : "Activity Resolver Table:", "  ", packageName,
15404                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15405                    dumpState.setTitlePrinted(true);
15406                }
15407                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15408                        : "Receiver Resolver Table:", "  ", packageName,
15409                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15410                    dumpState.setTitlePrinted(true);
15411                }
15412                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15413                        : "Service Resolver Table:", "  ", packageName,
15414                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15415                    dumpState.setTitlePrinted(true);
15416                }
15417                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15418                        : "Provider Resolver Table:", "  ", packageName,
15419                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15420                    dumpState.setTitlePrinted(true);
15421                }
15422            }
15423
15424            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15425                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15426                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15427                    int user = mSettings.mPreferredActivities.keyAt(i);
15428                    if (pir.dump(pw,
15429                            dumpState.getTitlePrinted()
15430                                ? "\nPreferred Activities User " + user + ":"
15431                                : "Preferred Activities User " + user + ":", "  ",
15432                            packageName, true, false)) {
15433                        dumpState.setTitlePrinted(true);
15434                    }
15435                }
15436            }
15437
15438            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15439                pw.flush();
15440                FileOutputStream fout = new FileOutputStream(fd);
15441                BufferedOutputStream str = new BufferedOutputStream(fout);
15442                XmlSerializer serializer = new FastXmlSerializer();
15443                try {
15444                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15445                    serializer.startDocument(null, true);
15446                    serializer.setFeature(
15447                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15448                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15449                    serializer.endDocument();
15450                    serializer.flush();
15451                } catch (IllegalArgumentException e) {
15452                    pw.println("Failed writing: " + e);
15453                } catch (IllegalStateException e) {
15454                    pw.println("Failed writing: " + e);
15455                } catch (IOException e) {
15456                    pw.println("Failed writing: " + e);
15457                }
15458            }
15459
15460            if (!checkin
15461                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15462                    && packageName == null) {
15463                pw.println();
15464                int count = mSettings.mPackages.size();
15465                if (count == 0) {
15466                    pw.println("No applications!");
15467                    pw.println();
15468                } else {
15469                    final String prefix = "  ";
15470                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15471                    if (allPackageSettings.size() == 0) {
15472                        pw.println("No domain preferred apps!");
15473                        pw.println();
15474                    } else {
15475                        pw.println("App verification status:");
15476                        pw.println();
15477                        count = 0;
15478                        for (PackageSetting ps : allPackageSettings) {
15479                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15480                            if (ivi == null || ivi.getPackageName() == null) continue;
15481                            pw.println(prefix + "Package: " + ivi.getPackageName());
15482                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15483                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15484                            pw.println();
15485                            count++;
15486                        }
15487                        if (count == 0) {
15488                            pw.println(prefix + "No app verification established.");
15489                            pw.println();
15490                        }
15491                        for (int userId : sUserManager.getUserIds()) {
15492                            pw.println("App linkages for user " + userId + ":");
15493                            pw.println();
15494                            count = 0;
15495                            for (PackageSetting ps : allPackageSettings) {
15496                                final long status = ps.getDomainVerificationStatusForUser(userId);
15497                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15498                                    continue;
15499                                }
15500                                pw.println(prefix + "Package: " + ps.name);
15501                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15502                                String statusStr = IntentFilterVerificationInfo.
15503                                        getStatusStringFromValue(status);
15504                                pw.println(prefix + "Status:  " + statusStr);
15505                                pw.println();
15506                                count++;
15507                            }
15508                            if (count == 0) {
15509                                pw.println(prefix + "No configured app linkages.");
15510                                pw.println();
15511                            }
15512                        }
15513                    }
15514                }
15515            }
15516
15517            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15518                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15519                if (packageName == null && permissionNames == null) {
15520                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15521                        if (iperm == 0) {
15522                            if (dumpState.onTitlePrinted())
15523                                pw.println();
15524                            pw.println("AppOp Permissions:");
15525                        }
15526                        pw.print("  AppOp Permission ");
15527                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15528                        pw.println(":");
15529                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15530                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15531                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15532                        }
15533                    }
15534                }
15535            }
15536
15537            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15538                boolean printedSomething = false;
15539                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15540                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15541                        continue;
15542                    }
15543                    if (!printedSomething) {
15544                        if (dumpState.onTitlePrinted())
15545                            pw.println();
15546                        pw.println("Registered ContentProviders:");
15547                        printedSomething = true;
15548                    }
15549                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15550                    pw.print("    "); pw.println(p.toString());
15551                }
15552                printedSomething = false;
15553                for (Map.Entry<String, PackageParser.Provider> entry :
15554                        mProvidersByAuthority.entrySet()) {
15555                    PackageParser.Provider p = entry.getValue();
15556                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15557                        continue;
15558                    }
15559                    if (!printedSomething) {
15560                        if (dumpState.onTitlePrinted())
15561                            pw.println();
15562                        pw.println("ContentProvider Authorities:");
15563                        printedSomething = true;
15564                    }
15565                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15566                    pw.print("    "); pw.println(p.toString());
15567                    if (p.info != null && p.info.applicationInfo != null) {
15568                        final String appInfo = p.info.applicationInfo.toString();
15569                        pw.print("      applicationInfo="); pw.println(appInfo);
15570                    }
15571                }
15572            }
15573
15574            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15575                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15576            }
15577
15578            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15579                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15580            }
15581
15582            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15583                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15584            }
15585
15586            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15587                // XXX should handle packageName != null by dumping only install data that
15588                // the given package is involved with.
15589                if (dumpState.onTitlePrinted()) pw.println();
15590                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15591            }
15592
15593            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15594                if (dumpState.onTitlePrinted()) pw.println();
15595                mSettings.dumpReadMessagesLPr(pw, dumpState);
15596
15597                pw.println();
15598                pw.println("Package warning messages:");
15599                BufferedReader in = null;
15600                String line = null;
15601                try {
15602                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15603                    while ((line = in.readLine()) != null) {
15604                        if (line.contains("ignored: updated version")) continue;
15605                        pw.println(line);
15606                    }
15607                } catch (IOException ignored) {
15608                } finally {
15609                    IoUtils.closeQuietly(in);
15610                }
15611            }
15612
15613            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15614                BufferedReader in = null;
15615                String line = null;
15616                try {
15617                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15618                    while ((line = in.readLine()) != null) {
15619                        if (line.contains("ignored: updated version")) continue;
15620                        pw.print("msg,");
15621                        pw.println(line);
15622                    }
15623                } catch (IOException ignored) {
15624                } finally {
15625                    IoUtils.closeQuietly(in);
15626                }
15627            }
15628        }
15629    }
15630
15631    private String dumpDomainString(String packageName) {
15632        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15633        List<IntentFilter> filters = getAllIntentFilters(packageName);
15634
15635        ArraySet<String> result = new ArraySet<>();
15636        if (iviList.size() > 0) {
15637            for (IntentFilterVerificationInfo ivi : iviList) {
15638                for (String host : ivi.getDomains()) {
15639                    result.add(host);
15640                }
15641            }
15642        }
15643        if (filters != null && filters.size() > 0) {
15644            for (IntentFilter filter : filters) {
15645                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15646                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15647                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15648                    result.addAll(filter.getHostsList());
15649                }
15650            }
15651        }
15652
15653        StringBuilder sb = new StringBuilder(result.size() * 16);
15654        for (String domain : result) {
15655            if (sb.length() > 0) sb.append(" ");
15656            sb.append(domain);
15657        }
15658        return sb.toString();
15659    }
15660
15661    // ------- apps on sdcard specific code -------
15662    static final boolean DEBUG_SD_INSTALL = false;
15663
15664    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15665
15666    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15667
15668    private boolean mMediaMounted = false;
15669
15670    static String getEncryptKey() {
15671        try {
15672            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15673                    SD_ENCRYPTION_KEYSTORE_NAME);
15674            if (sdEncKey == null) {
15675                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15676                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15677                if (sdEncKey == null) {
15678                    Slog.e(TAG, "Failed to create encryption keys");
15679                    return null;
15680                }
15681            }
15682            return sdEncKey;
15683        } catch (NoSuchAlgorithmException nsae) {
15684            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15685            return null;
15686        } catch (IOException ioe) {
15687            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15688            return null;
15689        }
15690    }
15691
15692    /*
15693     * Update media status on PackageManager.
15694     */
15695    @Override
15696    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15697        int callingUid = Binder.getCallingUid();
15698        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15699            throw new SecurityException("Media status can only be updated by the system");
15700        }
15701        // reader; this apparently protects mMediaMounted, but should probably
15702        // be a different lock in that case.
15703        synchronized (mPackages) {
15704            Log.i(TAG, "Updating external media status from "
15705                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15706                    + (mediaStatus ? "mounted" : "unmounted"));
15707            if (DEBUG_SD_INSTALL)
15708                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15709                        + ", mMediaMounted=" + mMediaMounted);
15710            if (mediaStatus == mMediaMounted) {
15711                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15712                        : 0, -1);
15713                mHandler.sendMessage(msg);
15714                return;
15715            }
15716            mMediaMounted = mediaStatus;
15717        }
15718        // Queue up an async operation since the package installation may take a
15719        // little while.
15720        mHandler.post(new Runnable() {
15721            public void run() {
15722                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15723            }
15724        });
15725    }
15726
15727    /**
15728     * Called by MountService when the initial ASECs to scan are available.
15729     * Should block until all the ASEC containers are finished being scanned.
15730     */
15731    public void scanAvailableAsecs() {
15732        updateExternalMediaStatusInner(true, false, false);
15733        if (mShouldRestoreconData) {
15734            SELinuxMMAC.setRestoreconDone();
15735            mShouldRestoreconData = false;
15736        }
15737    }
15738
15739    /*
15740     * Collect information of applications on external media, map them against
15741     * existing containers and update information based on current mount status.
15742     * Please note that we always have to report status if reportStatus has been
15743     * set to true especially when unloading packages.
15744     */
15745    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15746            boolean externalStorage) {
15747        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15748        int[] uidArr = EmptyArray.INT;
15749
15750        final String[] list = PackageHelper.getSecureContainerList();
15751        if (ArrayUtils.isEmpty(list)) {
15752            Log.i(TAG, "No secure containers found");
15753        } else {
15754            // Process list of secure containers and categorize them
15755            // as active or stale based on their package internal state.
15756
15757            // reader
15758            synchronized (mPackages) {
15759                for (String cid : list) {
15760                    // Leave stages untouched for now; installer service owns them
15761                    if (PackageInstallerService.isStageName(cid)) continue;
15762
15763                    if (DEBUG_SD_INSTALL)
15764                        Log.i(TAG, "Processing container " + cid);
15765                    String pkgName = getAsecPackageName(cid);
15766                    if (pkgName == null) {
15767                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15768                        continue;
15769                    }
15770                    if (DEBUG_SD_INSTALL)
15771                        Log.i(TAG, "Looking for pkg : " + pkgName);
15772
15773                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15774                    if (ps == null) {
15775                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15776                        continue;
15777                    }
15778
15779                    /*
15780                     * Skip packages that are not external if we're unmounting
15781                     * external storage.
15782                     */
15783                    if (externalStorage && !isMounted && !isExternal(ps)) {
15784                        continue;
15785                    }
15786
15787                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15788                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15789                    // The package status is changed only if the code path
15790                    // matches between settings and the container id.
15791                    if (ps.codePathString != null
15792                            && ps.codePathString.startsWith(args.getCodePath())) {
15793                        if (DEBUG_SD_INSTALL) {
15794                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15795                                    + " at code path: " + ps.codePathString);
15796                        }
15797
15798                        // We do have a valid package installed on sdcard
15799                        processCids.put(args, ps.codePathString);
15800                        final int uid = ps.appId;
15801                        if (uid != -1) {
15802                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15803                        }
15804                    } else {
15805                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15806                                + ps.codePathString);
15807                    }
15808                }
15809            }
15810
15811            Arrays.sort(uidArr);
15812        }
15813
15814        // Process packages with valid entries.
15815        if (isMounted) {
15816            if (DEBUG_SD_INSTALL)
15817                Log.i(TAG, "Loading packages");
15818            loadMediaPackages(processCids, uidArr, externalStorage);
15819            startCleaningPackages();
15820            mInstallerService.onSecureContainersAvailable();
15821        } else {
15822            if (DEBUG_SD_INSTALL)
15823                Log.i(TAG, "Unloading packages");
15824            unloadMediaPackages(processCids, uidArr, reportStatus);
15825        }
15826    }
15827
15828    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15829            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15830        final int size = infos.size();
15831        final String[] packageNames = new String[size];
15832        final int[] packageUids = new int[size];
15833        for (int i = 0; i < size; i++) {
15834            final ApplicationInfo info = infos.get(i);
15835            packageNames[i] = info.packageName;
15836            packageUids[i] = info.uid;
15837        }
15838        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15839                finishedReceiver);
15840    }
15841
15842    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15843            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15844        sendResourcesChangedBroadcast(mediaStatus, replacing,
15845                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15846    }
15847
15848    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15849            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15850        int size = pkgList.length;
15851        if (size > 0) {
15852            // Send broadcasts here
15853            Bundle extras = new Bundle();
15854            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15855            if (uidArr != null) {
15856                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15857            }
15858            if (replacing) {
15859                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15860            }
15861            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15862                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15863            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15864        }
15865    }
15866
15867   /*
15868     * Look at potentially valid container ids from processCids If package
15869     * information doesn't match the one on record or package scanning fails,
15870     * the cid is added to list of removeCids. We currently don't delete stale
15871     * containers.
15872     */
15873    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15874            boolean externalStorage) {
15875        ArrayList<String> pkgList = new ArrayList<String>();
15876        Set<AsecInstallArgs> keys = processCids.keySet();
15877
15878        for (AsecInstallArgs args : keys) {
15879            String codePath = processCids.get(args);
15880            if (DEBUG_SD_INSTALL)
15881                Log.i(TAG, "Loading container : " + args.cid);
15882            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15883            try {
15884                // Make sure there are no container errors first.
15885                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15886                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15887                            + " when installing from sdcard");
15888                    continue;
15889                }
15890                // Check code path here.
15891                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15892                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15893                            + " does not match one in settings " + codePath);
15894                    continue;
15895                }
15896                // Parse package
15897                int parseFlags = mDefParseFlags;
15898                if (args.isExternalAsec()) {
15899                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15900                }
15901                if (args.isFwdLocked()) {
15902                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15903                }
15904
15905                synchronized (mInstallLock) {
15906                    PackageParser.Package pkg = null;
15907                    try {
15908                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15909                    } catch (PackageManagerException e) {
15910                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15911                    }
15912                    // Scan the package
15913                    if (pkg != null) {
15914                        /*
15915                         * TODO why is the lock being held? doPostInstall is
15916                         * called in other places without the lock. This needs
15917                         * to be straightened out.
15918                         */
15919                        // writer
15920                        synchronized (mPackages) {
15921                            retCode = PackageManager.INSTALL_SUCCEEDED;
15922                            pkgList.add(pkg.packageName);
15923                            // Post process args
15924                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15925                                    pkg.applicationInfo.uid);
15926                        }
15927                    } else {
15928                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15929                    }
15930                }
15931
15932            } finally {
15933                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15934                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15935                }
15936            }
15937        }
15938        // writer
15939        synchronized (mPackages) {
15940            // If the platform SDK has changed since the last time we booted,
15941            // we need to re-grant app permission to catch any new ones that
15942            // appear. This is really a hack, and means that apps can in some
15943            // cases get permissions that the user didn't initially explicitly
15944            // allow... it would be nice to have some better way to handle
15945            // this situation.
15946            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15947                    : mSettings.getInternalVersion();
15948            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15949                    : StorageManager.UUID_PRIVATE_INTERNAL;
15950
15951            int updateFlags = UPDATE_PERMISSIONS_ALL;
15952            if (ver.sdkVersion != mSdkVersion) {
15953                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15954                        + mSdkVersion + "; regranting permissions for external");
15955                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15956            }
15957            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15958
15959            // Yay, everything is now upgraded
15960            ver.forceCurrent();
15961
15962            // can downgrade to reader
15963            // Persist settings
15964            mSettings.writeLPr();
15965        }
15966        // Send a broadcast to let everyone know we are done processing
15967        if (pkgList.size() > 0) {
15968            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15969        }
15970    }
15971
15972   /*
15973     * Utility method to unload a list of specified containers
15974     */
15975    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15976        // Just unmount all valid containers.
15977        for (AsecInstallArgs arg : cidArgs) {
15978            synchronized (mInstallLock) {
15979                arg.doPostDeleteLI(false);
15980           }
15981       }
15982   }
15983
15984    /*
15985     * Unload packages mounted on external media. This involves deleting package
15986     * data from internal structures, sending broadcasts about diabled packages,
15987     * gc'ing to free up references, unmounting all secure containers
15988     * corresponding to packages on external media, and posting a
15989     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15990     * that we always have to post this message if status has been requested no
15991     * matter what.
15992     */
15993    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15994            final boolean reportStatus) {
15995        if (DEBUG_SD_INSTALL)
15996            Log.i(TAG, "unloading media packages");
15997        ArrayList<String> pkgList = new ArrayList<String>();
15998        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15999        final Set<AsecInstallArgs> keys = processCids.keySet();
16000        for (AsecInstallArgs args : keys) {
16001            String pkgName = args.getPackageName();
16002            if (DEBUG_SD_INSTALL)
16003                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16004            // Delete package internally
16005            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16006            synchronized (mInstallLock) {
16007                boolean res = deletePackageLI(pkgName, null, false, null, null,
16008                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16009                if (res) {
16010                    pkgList.add(pkgName);
16011                } else {
16012                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16013                    failedList.add(args);
16014                }
16015            }
16016        }
16017
16018        // reader
16019        synchronized (mPackages) {
16020            // We didn't update the settings after removing each package;
16021            // write them now for all packages.
16022            mSettings.writeLPr();
16023        }
16024
16025        // We have to absolutely send UPDATED_MEDIA_STATUS only
16026        // after confirming that all the receivers processed the ordered
16027        // broadcast when packages get disabled, force a gc to clean things up.
16028        // and unload all the containers.
16029        if (pkgList.size() > 0) {
16030            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16031                    new IIntentReceiver.Stub() {
16032                public void performReceive(Intent intent, int resultCode, String data,
16033                        Bundle extras, boolean ordered, boolean sticky,
16034                        int sendingUser) throws RemoteException {
16035                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16036                            reportStatus ? 1 : 0, 1, keys);
16037                    mHandler.sendMessage(msg);
16038                }
16039            });
16040        } else {
16041            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16042                    keys);
16043            mHandler.sendMessage(msg);
16044        }
16045    }
16046
16047    private void loadPrivatePackages(final VolumeInfo vol) {
16048        mHandler.post(new Runnable() {
16049            @Override
16050            public void run() {
16051                loadPrivatePackagesInner(vol);
16052            }
16053        });
16054    }
16055
16056    private void loadPrivatePackagesInner(VolumeInfo vol) {
16057        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16058        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16059
16060        final VersionInfo ver;
16061        final List<PackageSetting> packages;
16062        synchronized (mPackages) {
16063            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16064            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16065        }
16066
16067        for (PackageSetting ps : packages) {
16068            synchronized (mInstallLock) {
16069                final PackageParser.Package pkg;
16070                try {
16071                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16072                    loaded.add(pkg.applicationInfo);
16073                } catch (PackageManagerException e) {
16074                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16075                }
16076
16077                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16078                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16079                }
16080            }
16081        }
16082
16083        synchronized (mPackages) {
16084            int updateFlags = UPDATE_PERMISSIONS_ALL;
16085            if (ver.sdkVersion != mSdkVersion) {
16086                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16087                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16088                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16089            }
16090            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16091
16092            // Yay, everything is now upgraded
16093            ver.forceCurrent();
16094
16095            mSettings.writeLPr();
16096        }
16097
16098        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16099        sendResourcesChangedBroadcast(true, false, loaded, null);
16100    }
16101
16102    private void unloadPrivatePackages(final VolumeInfo vol) {
16103        mHandler.post(new Runnable() {
16104            @Override
16105            public void run() {
16106                unloadPrivatePackagesInner(vol);
16107            }
16108        });
16109    }
16110
16111    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16112        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16113        synchronized (mInstallLock) {
16114        synchronized (mPackages) {
16115            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16116            for (PackageSetting ps : packages) {
16117                if (ps.pkg == null) continue;
16118
16119                final ApplicationInfo info = ps.pkg.applicationInfo;
16120                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16121                if (deletePackageLI(ps.name, null, false, null, null,
16122                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16123                    unloaded.add(info);
16124                } else {
16125                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16126                }
16127            }
16128
16129            mSettings.writeLPr();
16130        }
16131        }
16132
16133        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16134        sendResourcesChangedBroadcast(false, false, unloaded, null);
16135    }
16136
16137    /**
16138     * Examine all users present on given mounted volume, and destroy data
16139     * belonging to users that are no longer valid, or whose user ID has been
16140     * recycled.
16141     */
16142    private void reconcileUsers(String volumeUuid) {
16143        final File[] files = FileUtils
16144                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16145        for (File file : files) {
16146            if (!file.isDirectory()) continue;
16147
16148            final int userId;
16149            final UserInfo info;
16150            try {
16151                userId = Integer.parseInt(file.getName());
16152                info = sUserManager.getUserInfo(userId);
16153            } catch (NumberFormatException e) {
16154                Slog.w(TAG, "Invalid user directory " + file);
16155                continue;
16156            }
16157
16158            boolean destroyUser = false;
16159            if (info == null) {
16160                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16161                        + " because no matching user was found");
16162                destroyUser = true;
16163            } else {
16164                try {
16165                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16166                } catch (IOException e) {
16167                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16168                            + " because we failed to enforce serial number: " + e);
16169                    destroyUser = true;
16170                }
16171            }
16172
16173            if (destroyUser) {
16174                synchronized (mInstallLock) {
16175                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16176                }
16177            }
16178        }
16179
16180        final UserManager um = mContext.getSystemService(UserManager.class);
16181        for (UserInfo user : um.getUsers()) {
16182            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16183            if (userDir.exists()) continue;
16184
16185            try {
16186                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
16187                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16188            } catch (IOException e) {
16189                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16190            }
16191        }
16192    }
16193
16194    /**
16195     * Examine all apps present on given mounted volume, and destroy apps that
16196     * aren't expected, either due to uninstallation or reinstallation on
16197     * another volume.
16198     */
16199    private void reconcileApps(String volumeUuid) {
16200        final File[] files = FileUtils
16201                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16202        for (File file : files) {
16203            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16204                    && !PackageInstallerService.isStageName(file.getName());
16205            if (!isPackage) {
16206                // Ignore entries which are not packages
16207                continue;
16208            }
16209
16210            boolean destroyApp = false;
16211            String packageName = null;
16212            try {
16213                final PackageLite pkg = PackageParser.parsePackageLite(file,
16214                        PackageParser.PARSE_MUST_BE_APK);
16215                packageName = pkg.packageName;
16216
16217                synchronized (mPackages) {
16218                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16219                    if (ps == null) {
16220                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16221                                + volumeUuid + " because we found no install record");
16222                        destroyApp = true;
16223                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16224                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16225                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16226                        destroyApp = true;
16227                    }
16228                }
16229
16230            } catch (PackageParserException e) {
16231                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16232                destroyApp = true;
16233            }
16234
16235            if (destroyApp) {
16236                synchronized (mInstallLock) {
16237                    if (packageName != null) {
16238                        removeDataDirsLI(volumeUuid, packageName);
16239                    }
16240                    if (file.isDirectory()) {
16241                        mInstaller.rmPackageDir(file.getAbsolutePath());
16242                    } else {
16243                        file.delete();
16244                    }
16245                }
16246            }
16247        }
16248    }
16249
16250    private void unfreezePackage(String packageName) {
16251        synchronized (mPackages) {
16252            final PackageSetting ps = mSettings.mPackages.get(packageName);
16253            if (ps != null) {
16254                ps.frozen = false;
16255            }
16256        }
16257    }
16258
16259    @Override
16260    public int movePackage(final String packageName, final String volumeUuid) {
16261        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16262
16263        final int moveId = mNextMoveId.getAndIncrement();
16264        mHandler.post(new Runnable() {
16265            @Override
16266            public void run() {
16267                try {
16268                    movePackageInternal(packageName, volumeUuid, moveId);
16269                } catch (PackageManagerException e) {
16270                    Slog.w(TAG, "Failed to move " + packageName, e);
16271                    mMoveCallbacks.notifyStatusChanged(moveId,
16272                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16273                }
16274            }
16275        });
16276        return moveId;
16277    }
16278
16279    private void movePackageInternal(final String packageName, final String volumeUuid,
16280            final int moveId) throws PackageManagerException {
16281        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16282        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16283        final PackageManager pm = mContext.getPackageManager();
16284
16285        final boolean currentAsec;
16286        final String currentVolumeUuid;
16287        final File codeFile;
16288        final String installerPackageName;
16289        final String packageAbiOverride;
16290        final int appId;
16291        final String seinfo;
16292        final String label;
16293
16294        // reader
16295        synchronized (mPackages) {
16296            final PackageParser.Package pkg = mPackages.get(packageName);
16297            final PackageSetting ps = mSettings.mPackages.get(packageName);
16298            if (pkg == null || ps == null) {
16299                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16300            }
16301
16302            if (pkg.applicationInfo.isSystemApp()) {
16303                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16304                        "Cannot move system application");
16305            }
16306
16307            if (pkg.applicationInfo.isExternalAsec()) {
16308                currentAsec = true;
16309                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16310            } else if (pkg.applicationInfo.isForwardLocked()) {
16311                currentAsec = true;
16312                currentVolumeUuid = "forward_locked";
16313            } else {
16314                currentAsec = false;
16315                currentVolumeUuid = ps.volumeUuid;
16316
16317                final File probe = new File(pkg.codePath);
16318                final File probeOat = new File(probe, "oat");
16319                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16320                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16321                            "Move only supported for modern cluster style installs");
16322                }
16323            }
16324
16325            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16326                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16327                        "Package already moved to " + volumeUuid);
16328            }
16329
16330            if (ps.frozen) {
16331                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16332                        "Failed to move already frozen package");
16333            }
16334            ps.frozen = true;
16335
16336            codeFile = new File(pkg.codePath);
16337            installerPackageName = ps.installerPackageName;
16338            packageAbiOverride = ps.cpuAbiOverrideString;
16339            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16340            seinfo = pkg.applicationInfo.seinfo;
16341            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16342        }
16343
16344        // Now that we're guarded by frozen state, kill app during move
16345        final long token = Binder.clearCallingIdentity();
16346        try {
16347            killApplication(packageName, appId, "move pkg");
16348        } finally {
16349            Binder.restoreCallingIdentity(token);
16350        }
16351
16352        final Bundle extras = new Bundle();
16353        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16354        extras.putString(Intent.EXTRA_TITLE, label);
16355        mMoveCallbacks.notifyCreated(moveId, extras);
16356
16357        int installFlags;
16358        final boolean moveCompleteApp;
16359        final File measurePath;
16360
16361        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16362            installFlags = INSTALL_INTERNAL;
16363            moveCompleteApp = !currentAsec;
16364            measurePath = Environment.getDataAppDirectory(volumeUuid);
16365        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16366            installFlags = INSTALL_EXTERNAL;
16367            moveCompleteApp = false;
16368            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16369        } else {
16370            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16371            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16372                    || !volume.isMountedWritable()) {
16373                unfreezePackage(packageName);
16374                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16375                        "Move location not mounted private volume");
16376            }
16377
16378            Preconditions.checkState(!currentAsec);
16379
16380            installFlags = INSTALL_INTERNAL;
16381            moveCompleteApp = true;
16382            measurePath = Environment.getDataAppDirectory(volumeUuid);
16383        }
16384
16385        final PackageStats stats = new PackageStats(null, -1);
16386        synchronized (mInstaller) {
16387            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16388                unfreezePackage(packageName);
16389                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16390                        "Failed to measure package size");
16391            }
16392        }
16393
16394        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16395                + stats.dataSize);
16396
16397        final long startFreeBytes = measurePath.getFreeSpace();
16398        final long sizeBytes;
16399        if (moveCompleteApp) {
16400            sizeBytes = stats.codeSize + stats.dataSize;
16401        } else {
16402            sizeBytes = stats.codeSize;
16403        }
16404
16405        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16406            unfreezePackage(packageName);
16407            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16408                    "Not enough free space to move");
16409        }
16410
16411        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16412
16413        final CountDownLatch installedLatch = new CountDownLatch(1);
16414        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16415            @Override
16416            public void onUserActionRequired(Intent intent) throws RemoteException {
16417                throw new IllegalStateException();
16418            }
16419
16420            @Override
16421            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16422                    Bundle extras) throws RemoteException {
16423                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16424                        + PackageManager.installStatusToString(returnCode, msg));
16425
16426                installedLatch.countDown();
16427
16428                // Regardless of success or failure of the move operation,
16429                // always unfreeze the package
16430                unfreezePackage(packageName);
16431
16432                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16433                switch (status) {
16434                    case PackageInstaller.STATUS_SUCCESS:
16435                        mMoveCallbacks.notifyStatusChanged(moveId,
16436                                PackageManager.MOVE_SUCCEEDED);
16437                        break;
16438                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16439                        mMoveCallbacks.notifyStatusChanged(moveId,
16440                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16441                        break;
16442                    default:
16443                        mMoveCallbacks.notifyStatusChanged(moveId,
16444                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16445                        break;
16446                }
16447            }
16448        };
16449
16450        final MoveInfo move;
16451        if (moveCompleteApp) {
16452            // Kick off a thread to report progress estimates
16453            new Thread() {
16454                @Override
16455                public void run() {
16456                    while (true) {
16457                        try {
16458                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16459                                break;
16460                            }
16461                        } catch (InterruptedException ignored) {
16462                        }
16463
16464                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16465                        final int progress = 10 + (int) MathUtils.constrain(
16466                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16467                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16468                    }
16469                }
16470            }.start();
16471
16472            final String dataAppName = codeFile.getName();
16473            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16474                    dataAppName, appId, seinfo);
16475        } else {
16476            move = null;
16477        }
16478
16479        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16480
16481        final Message msg = mHandler.obtainMessage(INIT_COPY);
16482        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16483        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16484                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16485        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16486        msg.obj = params;
16487
16488        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16489                System.identityHashCode(msg.obj));
16490        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16491                System.identityHashCode(msg.obj));
16492
16493        mHandler.sendMessage(msg);
16494    }
16495
16496    @Override
16497    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16498        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16499
16500        final int realMoveId = mNextMoveId.getAndIncrement();
16501        final Bundle extras = new Bundle();
16502        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16503        mMoveCallbacks.notifyCreated(realMoveId, extras);
16504
16505        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16506            @Override
16507            public void onCreated(int moveId, Bundle extras) {
16508                // Ignored
16509            }
16510
16511            @Override
16512            public void onStatusChanged(int moveId, int status, long estMillis) {
16513                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16514            }
16515        };
16516
16517        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16518        storage.setPrimaryStorageUuid(volumeUuid, callback);
16519        return realMoveId;
16520    }
16521
16522    @Override
16523    public int getMoveStatus(int moveId) {
16524        mContext.enforceCallingOrSelfPermission(
16525                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16526        return mMoveCallbacks.mLastStatus.get(moveId);
16527    }
16528
16529    @Override
16530    public void registerMoveCallback(IPackageMoveObserver callback) {
16531        mContext.enforceCallingOrSelfPermission(
16532                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16533        mMoveCallbacks.register(callback);
16534    }
16535
16536    @Override
16537    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16538        mContext.enforceCallingOrSelfPermission(
16539                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16540        mMoveCallbacks.unregister(callback);
16541    }
16542
16543    @Override
16544    public boolean setInstallLocation(int loc) {
16545        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16546                null);
16547        if (getInstallLocation() == loc) {
16548            return true;
16549        }
16550        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16551                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16552            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16553                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16554            return true;
16555        }
16556        return false;
16557   }
16558
16559    @Override
16560    public int getInstallLocation() {
16561        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16562                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16563                PackageHelper.APP_INSTALL_AUTO);
16564    }
16565
16566    /** Called by UserManagerService */
16567    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16568        mDirtyUsers.remove(userHandle);
16569        mSettings.removeUserLPw(userHandle);
16570        mPendingBroadcasts.remove(userHandle);
16571        if (mInstaller != null) {
16572            // Technically, we shouldn't be doing this with the package lock
16573            // held.  However, this is very rare, and there is already so much
16574            // other disk I/O going on, that we'll let it slide for now.
16575            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16576            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16577                final String volumeUuid = vol.getFsUuid();
16578                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16579                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16580            }
16581        }
16582        mUserNeedsBadging.delete(userHandle);
16583        removeUnusedPackagesLILPw(userManager, userHandle);
16584    }
16585
16586    /**
16587     * We're removing userHandle and would like to remove any downloaded packages
16588     * that are no longer in use by any other user.
16589     * @param userHandle the user being removed
16590     */
16591    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16592        final boolean DEBUG_CLEAN_APKS = false;
16593        int [] users = userManager.getUserIds();
16594        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16595        while (psit.hasNext()) {
16596            PackageSetting ps = psit.next();
16597            if (ps.pkg == null) {
16598                continue;
16599            }
16600            final String packageName = ps.pkg.packageName;
16601            // Skip over if system app
16602            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16603                continue;
16604            }
16605            if (DEBUG_CLEAN_APKS) {
16606                Slog.i(TAG, "Checking package " + packageName);
16607            }
16608            boolean keep = false;
16609            for (int i = 0; i < users.length; i++) {
16610                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16611                    keep = true;
16612                    if (DEBUG_CLEAN_APKS) {
16613                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16614                                + users[i]);
16615                    }
16616                    break;
16617                }
16618            }
16619            if (!keep) {
16620                if (DEBUG_CLEAN_APKS) {
16621                    Slog.i(TAG, "  Removing package " + packageName);
16622                }
16623                mHandler.post(new Runnable() {
16624                    public void run() {
16625                        deletePackageX(packageName, userHandle, 0);
16626                    } //end run
16627                });
16628            }
16629        }
16630    }
16631
16632    /** Called by UserManagerService */
16633    void createNewUserLILPw(int userHandle) {
16634        if (mInstaller != null) {
16635            mInstaller.createUserConfig(userHandle);
16636            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16637            applyFactoryDefaultBrowserLPw(userHandle);
16638            primeDomainVerificationsLPw(userHandle);
16639        }
16640    }
16641
16642    void newUserCreated(final int userHandle) {
16643        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16644    }
16645
16646    @Override
16647    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16648        mContext.enforceCallingOrSelfPermission(
16649                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16650                "Only package verification agents can read the verifier device identity");
16651
16652        synchronized (mPackages) {
16653            return mSettings.getVerifierDeviceIdentityLPw();
16654        }
16655    }
16656
16657    @Override
16658    public void setPermissionEnforced(String permission, boolean enforced) {
16659        // TODO: Now that we no longer change GID for storage, this should to away.
16660        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16661                "setPermissionEnforced");
16662        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16663            synchronized (mPackages) {
16664                if (mSettings.mReadExternalStorageEnforced == null
16665                        || mSettings.mReadExternalStorageEnforced != enforced) {
16666                    mSettings.mReadExternalStorageEnforced = enforced;
16667                    mSettings.writeLPr();
16668                }
16669            }
16670            // kill any non-foreground processes so we restart them and
16671            // grant/revoke the GID.
16672            final IActivityManager am = ActivityManagerNative.getDefault();
16673            if (am != null) {
16674                final long token = Binder.clearCallingIdentity();
16675                try {
16676                    am.killProcessesBelowForeground("setPermissionEnforcement");
16677                } catch (RemoteException e) {
16678                } finally {
16679                    Binder.restoreCallingIdentity(token);
16680                }
16681            }
16682        } else {
16683            throw new IllegalArgumentException("No selective enforcement for " + permission);
16684        }
16685    }
16686
16687    @Override
16688    @Deprecated
16689    public boolean isPermissionEnforced(String permission) {
16690        return true;
16691    }
16692
16693    @Override
16694    public boolean isStorageLow() {
16695        final long token = Binder.clearCallingIdentity();
16696        try {
16697            final DeviceStorageMonitorInternal
16698                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16699            if (dsm != null) {
16700                return dsm.isMemoryLow();
16701            } else {
16702                return false;
16703            }
16704        } finally {
16705            Binder.restoreCallingIdentity(token);
16706        }
16707    }
16708
16709    @Override
16710    public IPackageInstaller getPackageInstaller() {
16711        return mInstallerService;
16712    }
16713
16714    private boolean userNeedsBadging(int userId) {
16715        int index = mUserNeedsBadging.indexOfKey(userId);
16716        if (index < 0) {
16717            final UserInfo userInfo;
16718            final long token = Binder.clearCallingIdentity();
16719            try {
16720                userInfo = sUserManager.getUserInfo(userId);
16721            } finally {
16722                Binder.restoreCallingIdentity(token);
16723            }
16724            final boolean b;
16725            if (userInfo != null && userInfo.isManagedProfile()) {
16726                b = true;
16727            } else {
16728                b = false;
16729            }
16730            mUserNeedsBadging.put(userId, b);
16731            return b;
16732        }
16733        return mUserNeedsBadging.valueAt(index);
16734    }
16735
16736    @Override
16737    public KeySet getKeySetByAlias(String packageName, String alias) {
16738        if (packageName == null || alias == null) {
16739            return null;
16740        }
16741        synchronized(mPackages) {
16742            final PackageParser.Package pkg = mPackages.get(packageName);
16743            if (pkg == null) {
16744                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16745                throw new IllegalArgumentException("Unknown package: " + packageName);
16746            }
16747            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16748            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16749        }
16750    }
16751
16752    @Override
16753    public KeySet getSigningKeySet(String packageName) {
16754        if (packageName == null) {
16755            return null;
16756        }
16757        synchronized(mPackages) {
16758            final PackageParser.Package pkg = mPackages.get(packageName);
16759            if (pkg == null) {
16760                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16761                throw new IllegalArgumentException("Unknown package: " + packageName);
16762            }
16763            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16764                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16765                throw new SecurityException("May not access signing KeySet of other apps.");
16766            }
16767            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16768            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16769        }
16770    }
16771
16772    @Override
16773    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16774        if (packageName == null || ks == null) {
16775            return false;
16776        }
16777        synchronized(mPackages) {
16778            final PackageParser.Package pkg = mPackages.get(packageName);
16779            if (pkg == null) {
16780                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16781                throw new IllegalArgumentException("Unknown package: " + packageName);
16782            }
16783            IBinder ksh = ks.getToken();
16784            if (ksh instanceof KeySetHandle) {
16785                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16786                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16787            }
16788            return false;
16789        }
16790    }
16791
16792    @Override
16793    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16794        if (packageName == null || ks == null) {
16795            return false;
16796        }
16797        synchronized(mPackages) {
16798            final PackageParser.Package pkg = mPackages.get(packageName);
16799            if (pkg == null) {
16800                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16801                throw new IllegalArgumentException("Unknown package: " + packageName);
16802            }
16803            IBinder ksh = ks.getToken();
16804            if (ksh instanceof KeySetHandle) {
16805                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16806                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16807            }
16808            return false;
16809        }
16810    }
16811
16812    public void getUsageStatsIfNoPackageUsageInfo() {
16813        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16814            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16815            if (usm == null) {
16816                throw new IllegalStateException("UsageStatsManager must be initialized");
16817            }
16818            long now = System.currentTimeMillis();
16819            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16820            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16821                String packageName = entry.getKey();
16822                PackageParser.Package pkg = mPackages.get(packageName);
16823                if (pkg == null) {
16824                    continue;
16825                }
16826                UsageStats usage = entry.getValue();
16827                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16828                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16829            }
16830        }
16831    }
16832
16833    /**
16834     * Check and throw if the given before/after packages would be considered a
16835     * downgrade.
16836     */
16837    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16838            throws PackageManagerException {
16839        if (after.versionCode < before.mVersionCode) {
16840            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16841                    "Update version code " + after.versionCode + " is older than current "
16842                    + before.mVersionCode);
16843        } else if (after.versionCode == before.mVersionCode) {
16844            if (after.baseRevisionCode < before.baseRevisionCode) {
16845                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16846                        "Update base revision code " + after.baseRevisionCode
16847                        + " is older than current " + before.baseRevisionCode);
16848            }
16849
16850            if (!ArrayUtils.isEmpty(after.splitNames)) {
16851                for (int i = 0; i < after.splitNames.length; i++) {
16852                    final String splitName = after.splitNames[i];
16853                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16854                    if (j != -1) {
16855                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16856                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16857                                    "Update split " + splitName + " revision code "
16858                                    + after.splitRevisionCodes[i] + " is older than current "
16859                                    + before.splitRevisionCodes[j]);
16860                        }
16861                    }
16862                }
16863            }
16864        }
16865    }
16866
16867    private static class MoveCallbacks extends Handler {
16868        private static final int MSG_CREATED = 1;
16869        private static final int MSG_STATUS_CHANGED = 2;
16870
16871        private final RemoteCallbackList<IPackageMoveObserver>
16872                mCallbacks = new RemoteCallbackList<>();
16873
16874        private final SparseIntArray mLastStatus = new SparseIntArray();
16875
16876        public MoveCallbacks(Looper looper) {
16877            super(looper);
16878        }
16879
16880        public void register(IPackageMoveObserver callback) {
16881            mCallbacks.register(callback);
16882        }
16883
16884        public void unregister(IPackageMoveObserver callback) {
16885            mCallbacks.unregister(callback);
16886        }
16887
16888        @Override
16889        public void handleMessage(Message msg) {
16890            final SomeArgs args = (SomeArgs) msg.obj;
16891            final int n = mCallbacks.beginBroadcast();
16892            for (int i = 0; i < n; i++) {
16893                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16894                try {
16895                    invokeCallback(callback, msg.what, args);
16896                } catch (RemoteException ignored) {
16897                }
16898            }
16899            mCallbacks.finishBroadcast();
16900            args.recycle();
16901        }
16902
16903        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16904                throws RemoteException {
16905            switch (what) {
16906                case MSG_CREATED: {
16907                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16908                    break;
16909                }
16910                case MSG_STATUS_CHANGED: {
16911                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16912                    break;
16913                }
16914            }
16915        }
16916
16917        private void notifyCreated(int moveId, Bundle extras) {
16918            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16919
16920            final SomeArgs args = SomeArgs.obtain();
16921            args.argi1 = moveId;
16922            args.arg2 = extras;
16923            obtainMessage(MSG_CREATED, args).sendToTarget();
16924        }
16925
16926        private void notifyStatusChanged(int moveId, int status) {
16927            notifyStatusChanged(moveId, status, -1);
16928        }
16929
16930        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16931            Slog.v(TAG, "Move " + moveId + " status " + status);
16932
16933            final SomeArgs args = SomeArgs.obtain();
16934            args.argi1 = moveId;
16935            args.argi2 = status;
16936            args.arg3 = estMillis;
16937            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16938
16939            synchronized (mLastStatus) {
16940                mLastStatus.put(moveId, status);
16941            }
16942        }
16943    }
16944
16945    private final class OnPermissionChangeListeners extends Handler {
16946        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16947
16948        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16949                new RemoteCallbackList<>();
16950
16951        public OnPermissionChangeListeners(Looper looper) {
16952            super(looper);
16953        }
16954
16955        @Override
16956        public void handleMessage(Message msg) {
16957            switch (msg.what) {
16958                case MSG_ON_PERMISSIONS_CHANGED: {
16959                    final int uid = msg.arg1;
16960                    handleOnPermissionsChanged(uid);
16961                } break;
16962            }
16963        }
16964
16965        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16966            mPermissionListeners.register(listener);
16967
16968        }
16969
16970        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16971            mPermissionListeners.unregister(listener);
16972        }
16973
16974        public void onPermissionsChanged(int uid) {
16975            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16976                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16977            }
16978        }
16979
16980        private void handleOnPermissionsChanged(int uid) {
16981            final int count = mPermissionListeners.beginBroadcast();
16982            try {
16983                for (int i = 0; i < count; i++) {
16984                    IOnPermissionsChangeListener callback = mPermissionListeners
16985                            .getBroadcastItem(i);
16986                    try {
16987                        callback.onPermissionsChanged(uid);
16988                    } catch (RemoteException e) {
16989                        Log.e(TAG, "Permission listener is dead", e);
16990                    }
16991                }
16992            } finally {
16993                mPermissionListeners.finishBroadcast();
16994            }
16995        }
16996    }
16997
16998    private class PackageManagerInternalImpl extends PackageManagerInternal {
16999        @Override
17000        public void setLocationPackagesProvider(PackagesProvider provider) {
17001            synchronized (mPackages) {
17002                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17003            }
17004        }
17005
17006        @Override
17007        public void setImePackagesProvider(PackagesProvider provider) {
17008            synchronized (mPackages) {
17009                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17010            }
17011        }
17012
17013        @Override
17014        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17015            synchronized (mPackages) {
17016                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17017            }
17018        }
17019
17020        @Override
17021        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17022            synchronized (mPackages) {
17023                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17024            }
17025        }
17026
17027        @Override
17028        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17029            synchronized (mPackages) {
17030                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17031            }
17032        }
17033
17034        @Override
17035        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17036            synchronized (mPackages) {
17037                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17038            }
17039        }
17040
17041        @Override
17042        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17043            synchronized (mPackages) {
17044                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17045            }
17046        }
17047
17048        @Override
17049        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17050            synchronized (mPackages) {
17051                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17052                        packageName, userId);
17053            }
17054        }
17055
17056        @Override
17057        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17058            synchronized (mPackages) {
17059                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17060                        packageName, userId);
17061            }
17062        }
17063        @Override
17064        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17065            synchronized (mPackages) {
17066                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17067                        packageName, userId);
17068            }
17069        }
17070    }
17071
17072    @Override
17073    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17074        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17075        synchronized (mPackages) {
17076            final long identity = Binder.clearCallingIdentity();
17077            try {
17078                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17079                        packageNames, userId);
17080            } finally {
17081                Binder.restoreCallingIdentity(identity);
17082            }
17083        }
17084    }
17085
17086    private static void enforceSystemOrPhoneCaller(String tag) {
17087        int callingUid = Binder.getCallingUid();
17088        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17089            throw new SecurityException(
17090                    "Cannot call " + tag + " from UID " + callingUid);
17091        }
17092    }
17093}
17094