PackageManagerService.java revision 70f929eedec10b154170ad66c9d53f18bfc4f613
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 DisplayMetrics mMetrics;
433    final int mDefParseFlags;
434    final String[] mSeparateProcesses;
435    final boolean mIsUpgrade;
436
437    // This is where all application persistent data goes.
438    final File mAppDataDir;
439
440    // This is where all application persistent data goes for secondary users.
441    final File mUserAppDataDir;
442
443    /** The location for ASEC container files on internal storage. */
444    final String mAsecInternalPath;
445
446    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
447    // LOCK HELD.  Can be called with mInstallLock held.
448    @GuardedBy("mInstallLock")
449    final Installer mInstaller;
450
451    /** Directory where installed third-party apps stored */
452    final File mAppInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    public static final class SharedLibraryEntry {
515        public final String path;
516        public final String apk;
517
518        SharedLibraryEntry(String _path, String _apk) {
519            path = _path;
520            apk = _apk;
521        }
522    }
523
524    // Currently known shared libraries.
525    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
526            new ArrayMap<String, SharedLibraryEntry>();
527
528    // All available activities, for your resolving pleasure.
529    final ActivityIntentResolver mActivities =
530            new ActivityIntentResolver();
531
532    // All available receivers, for your resolving pleasure.
533    final ActivityIntentResolver mReceivers =
534            new ActivityIntentResolver();
535
536    // All available services, for your resolving pleasure.
537    final ServiceIntentResolver mServices = new ServiceIntentResolver();
538
539    // All available providers, for your resolving pleasure.
540    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
541
542    // Mapping from provider base names (first directory in content URI codePath)
543    // to the provider information.
544    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
545            new ArrayMap<String, PackageParser.Provider>();
546
547    // Mapping from instrumentation class names to info about them.
548    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
549            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
550
551    // Mapping from permission names to info about them.
552    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
553            new ArrayMap<String, PackageParser.PermissionGroup>();
554
555    // Packages whose data we have transfered into another package, thus
556    // should no longer exist.
557    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
558
559    // Broadcast actions that are only available to the system.
560    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
561
562    /** List of packages waiting for verification. */
563    final SparseArray<PackageVerificationState> mPendingVerification
564            = new SparseArray<PackageVerificationState>();
565
566    /** Set of packages associated with each app op permission. */
567    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
568
569    final PackageInstallerService mInstallerService;
570
571    private final PackageDexOptimizer mPackageDexOptimizer;
572
573    private AtomicInteger mNextMoveId = new AtomicInteger();
574    private final MoveCallbacks mMoveCallbacks;
575
576    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
577
578    // Cache of users who need badging.
579    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
580
581    /** Token for keys in mPendingVerification. */
582    private int mPendingVerificationToken = 0;
583
584    volatile boolean mSystemReady;
585    volatile boolean mSafeMode;
586    volatile boolean mHasSystemUidErrors;
587
588    ApplicationInfo mAndroidApplication;
589    final ActivityInfo mResolveActivity = new ActivityInfo();
590    final ResolveInfo mResolveInfo = new ResolveInfo();
591    ComponentName mResolveComponentName;
592    PackageParser.Package mPlatformPackage;
593    ComponentName mCustomResolverComponentName;
594
595    boolean mResolverReplaced = false;
596
597    private final ComponentName mIntentFilterVerifierComponent;
598    private int mIntentFilterVerificationToken = 0;
599
600    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
601            = new SparseArray<IntentFilterVerificationState>();
602
603    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
604            new DefaultPermissionGrantPolicy(this);
605
606    private static class IFVerificationParams {
607        PackageParser.Package pkg;
608        boolean replacing;
609        int userId;
610        int verifierUid;
611
612        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
613                int _userId, int _verifierUid) {
614            pkg = _pkg;
615            replacing = _replacing;
616            userId = _userId;
617            replacing = _replacing;
618            verifierUid = _verifierUid;
619        }
620    }
621
622    private interface IntentFilterVerifier<T extends IntentFilter> {
623        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
624                                               T filter, String packageName);
625        void startVerifications(int userId);
626        void receiveVerificationResponse(int verificationId);
627    }
628
629    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
630        private Context mContext;
631        private ComponentName mIntentFilterVerifierComponent;
632        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
633
634        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
635            mContext = context;
636            mIntentFilterVerifierComponent = verifierComponent;
637        }
638
639        private String getDefaultScheme() {
640            return IntentFilter.SCHEME_HTTPS;
641        }
642
643        @Override
644        public void startVerifications(int userId) {
645            // Launch verifications requests
646            int count = mCurrentIntentFilterVerifications.size();
647            for (int n=0; n<count; n++) {
648                int verificationId = mCurrentIntentFilterVerifications.get(n);
649                final IntentFilterVerificationState ivs =
650                        mIntentFilterVerificationStates.get(verificationId);
651
652                String packageName = ivs.getPackageName();
653
654                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
655                final int filterCount = filters.size();
656                ArraySet<String> domainsSet = new ArraySet<>();
657                for (int m=0; m<filterCount; m++) {
658                    PackageParser.ActivityIntentInfo filter = filters.get(m);
659                    domainsSet.addAll(filter.getHostsList());
660                }
661                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
662                synchronized (mPackages) {
663                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
664                            packageName, domainsList) != null) {
665                        scheduleWriteSettingsLocked();
666                    }
667                }
668                sendVerificationRequest(userId, verificationId, ivs);
669            }
670            mCurrentIntentFilterVerifications.clear();
671        }
672
673        private void sendVerificationRequest(int userId, int verificationId,
674                IntentFilterVerificationState ivs) {
675
676            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
677            verificationIntent.putExtra(
678                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
679                    verificationId);
680            verificationIntent.putExtra(
681                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
682                    getDefaultScheme());
683            verificationIntent.putExtra(
684                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
685                    ivs.getHostsString());
686            verificationIntent.putExtra(
687                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
688                    ivs.getPackageName());
689            verificationIntent.setComponent(mIntentFilterVerifierComponent);
690            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
691
692            UserHandle user = new UserHandle(userId);
693            mContext.sendBroadcastAsUser(verificationIntent, user);
694            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
695                    "Sending IntentFilter verification broadcast");
696        }
697
698        public void receiveVerificationResponse(int verificationId) {
699            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
700
701            final boolean verified = ivs.isVerified();
702
703            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
704            final int count = filters.size();
705            if (DEBUG_DOMAIN_VERIFICATION) {
706                Slog.i(TAG, "Received verification response " + verificationId
707                        + " for " + count + " filters, verified=" + verified);
708            }
709            for (int n=0; n<count; n++) {
710                PackageParser.ActivityIntentInfo filter = filters.get(n);
711                filter.setVerified(verified);
712
713                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
714                        + " verified with result:" + verified + " and hosts:"
715                        + ivs.getHostsString());
716            }
717
718            mIntentFilterVerificationStates.remove(verificationId);
719
720            final String packageName = ivs.getPackageName();
721            IntentFilterVerificationInfo ivi = null;
722
723            synchronized (mPackages) {
724                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
725            }
726            if (ivi == null) {
727                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
728                        + verificationId + " packageName:" + packageName);
729                return;
730            }
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Updating IntentFilterVerificationInfo for package " + packageName
733                            +" verificationId:" + verificationId);
734
735            synchronized (mPackages) {
736                if (verified) {
737                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
738                } else {
739                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
740                }
741                scheduleWriteSettingsLocked();
742
743                final int userId = ivs.getUserId();
744                if (userId != UserHandle.USER_ALL) {
745                    final int userStatus =
746                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
747
748                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
749                    boolean needUpdate = false;
750
751                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
752                    // already been set by the User thru the Disambiguation dialog
753                    switch (userStatus) {
754                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
755                            if (verified) {
756                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
757                            } else {
758                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
759                            }
760                            needUpdate = true;
761                            break;
762
763                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
764                            if (verified) {
765                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
766                                needUpdate = true;
767                            }
768                            break;
769
770                        default:
771                            // Nothing to do
772                    }
773
774                    if (needUpdate) {
775                        mSettings.updateIntentFilterVerificationStatusLPw(
776                                packageName, updatedStatus, userId);
777                        scheduleWritePackageRestrictionsLocked(userId);
778                    }
779                }
780            }
781        }
782
783        @Override
784        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
785                    ActivityIntentInfo filter, String packageName) {
786            if (!hasValidDomains(filter)) {
787                return false;
788            }
789            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
790            if (ivs == null) {
791                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
792                        packageName);
793            }
794            if (DEBUG_DOMAIN_VERIFICATION) {
795                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
796            }
797            ivs.addFilter(filter);
798            return true;
799        }
800
801        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
802                int userId, int verificationId, String packageName) {
803            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
804                    verifierUid, userId, packageName);
805            ivs.setPendingState();
806            synchronized (mPackages) {
807                mIntentFilterVerificationStates.append(verificationId, ivs);
808                mCurrentIntentFilterVerifications.add(verificationId);
809            }
810            return ivs;
811        }
812    }
813
814    private static boolean hasValidDomains(ActivityIntentInfo filter) {
815        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
816                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
817                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
818    }
819
820    private IntentFilterVerifier mIntentFilterVerifier;
821
822    // Set of pending broadcasts for aggregating enable/disable of components.
823    static class PendingPackageBroadcasts {
824        // for each user id, a map of <package name -> components within that package>
825        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
826
827        public PendingPackageBroadcasts() {
828            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
829        }
830
831        public ArrayList<String> get(int userId, String packageName) {
832            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
833            return packages.get(packageName);
834        }
835
836        public void put(int userId, String packageName, ArrayList<String> components) {
837            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
838            packages.put(packageName, components);
839        }
840
841        public void remove(int userId, String packageName) {
842            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
843            if (packages != null) {
844                packages.remove(packageName);
845            }
846        }
847
848        public void remove(int userId) {
849            mUidMap.remove(userId);
850        }
851
852        public int userIdCount() {
853            return mUidMap.size();
854        }
855
856        public int userIdAt(int n) {
857            return mUidMap.keyAt(n);
858        }
859
860        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
861            return mUidMap.get(userId);
862        }
863
864        public int size() {
865            // total number of pending broadcast entries across all userIds
866            int num = 0;
867            for (int i = 0; i< mUidMap.size(); i++) {
868                num += mUidMap.valueAt(i).size();
869            }
870            return num;
871        }
872
873        public void clear() {
874            mUidMap.clear();
875        }
876
877        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
878            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
879            if (map == null) {
880                map = new ArrayMap<String, ArrayList<String>>();
881                mUidMap.put(userId, map);
882            }
883            return map;
884        }
885    }
886    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
887
888    // Service Connection to remote media container service to copy
889    // package uri's from external media onto secure containers
890    // or internal storage.
891    private IMediaContainerService mContainerService = null;
892
893    static final int SEND_PENDING_BROADCAST = 1;
894    static final int MCS_BOUND = 3;
895    static final int END_COPY = 4;
896    static final int INIT_COPY = 5;
897    static final int MCS_UNBIND = 6;
898    static final int START_CLEANING_PACKAGE = 7;
899    static final int FIND_INSTALL_LOC = 8;
900    static final int POST_INSTALL = 9;
901    static final int MCS_RECONNECT = 10;
902    static final int MCS_GIVE_UP = 11;
903    static final int UPDATED_MEDIA_STATUS = 12;
904    static final int WRITE_SETTINGS = 13;
905    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
906    static final int PACKAGE_VERIFIED = 15;
907    static final int CHECK_PENDING_VERIFICATION = 16;
908    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
909    static final int INTENT_FILTER_VERIFIED = 18;
910
911    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
912
913    // Delay time in millisecs
914    static final int BROADCAST_DELAY = 10 * 1000;
915
916    static UserManagerService sUserManager;
917
918    // Stores a list of users whose package restrictions file needs to be updated
919    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
920
921    final private DefaultContainerConnection mDefContainerConn =
922            new DefaultContainerConnection();
923    class DefaultContainerConnection implements ServiceConnection {
924        public void onServiceConnected(ComponentName name, IBinder service) {
925            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
926            IMediaContainerService imcs =
927                IMediaContainerService.Stub.asInterface(service);
928            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
929        }
930
931        public void onServiceDisconnected(ComponentName name) {
932            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
933        }
934    }
935
936    // Recordkeeping of restore-after-install operations that are currently in flight
937    // between the Package Manager and the Backup Manager
938    class PostInstallData {
939        public InstallArgs args;
940        public PackageInstalledInfo res;
941
942        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
943            args = _a;
944            res = _r;
945        }
946    }
947
948    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
949    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
950
951    // XML tags for backup/restore of various bits of state
952    private static final String TAG_PREFERRED_BACKUP = "pa";
953    private static final String TAG_DEFAULT_APPS = "da";
954    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
955
956    final String mRequiredVerifierPackage;
957    final String mRequiredInstallerPackage;
958
959    private final PackageUsage mPackageUsage = new PackageUsage();
960
961    private class PackageUsage {
962        private static final int WRITE_INTERVAL
963            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
964
965        private final Object mFileLock = new Object();
966        private final AtomicLong mLastWritten = new AtomicLong(0);
967        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
968
969        private boolean mIsHistoricalPackageUsageAvailable = true;
970
971        boolean isHistoricalPackageUsageAvailable() {
972            return mIsHistoricalPackageUsageAvailable;
973        }
974
975        void write(boolean force) {
976            if (force) {
977                writeInternal();
978                return;
979            }
980            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
981                && !DEBUG_DEXOPT) {
982                return;
983            }
984            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
985                new Thread("PackageUsage_DiskWriter") {
986                    @Override
987                    public void run() {
988                        try {
989                            writeInternal();
990                        } finally {
991                            mBackgroundWriteRunning.set(false);
992                        }
993                    }
994                }.start();
995            }
996        }
997
998        private void writeInternal() {
999            synchronized (mPackages) {
1000                synchronized (mFileLock) {
1001                    AtomicFile file = getFile();
1002                    FileOutputStream f = null;
1003                    try {
1004                        f = file.startWrite();
1005                        BufferedOutputStream out = new BufferedOutputStream(f);
1006                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1007                        StringBuilder sb = new StringBuilder();
1008                        for (PackageParser.Package pkg : mPackages.values()) {
1009                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1010                                continue;
1011                            }
1012                            sb.setLength(0);
1013                            sb.append(pkg.packageName);
1014                            sb.append(' ');
1015                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1016                            sb.append('\n');
1017                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1018                        }
1019                        out.flush();
1020                        file.finishWrite(f);
1021                    } catch (IOException e) {
1022                        if (f != null) {
1023                            file.failWrite(f);
1024                        }
1025                        Log.e(TAG, "Failed to write package usage times", e);
1026                    }
1027                }
1028            }
1029            mLastWritten.set(SystemClock.elapsedRealtime());
1030        }
1031
1032        void readLP() {
1033            synchronized (mFileLock) {
1034                AtomicFile file = getFile();
1035                BufferedInputStream in = null;
1036                try {
1037                    in = new BufferedInputStream(file.openRead());
1038                    StringBuffer sb = new StringBuffer();
1039                    while (true) {
1040                        String packageName = readToken(in, sb, ' ');
1041                        if (packageName == null) {
1042                            break;
1043                        }
1044                        String timeInMillisString = readToken(in, sb, '\n');
1045                        if (timeInMillisString == null) {
1046                            throw new IOException("Failed to find last usage time for package "
1047                                                  + packageName);
1048                        }
1049                        PackageParser.Package pkg = mPackages.get(packageName);
1050                        if (pkg == null) {
1051                            continue;
1052                        }
1053                        long timeInMillis;
1054                        try {
1055                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1056                        } catch (NumberFormatException e) {
1057                            throw new IOException("Failed to parse " + timeInMillisString
1058                                                  + " as a long.", e);
1059                        }
1060                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1061                    }
1062                } catch (FileNotFoundException expected) {
1063                    mIsHistoricalPackageUsageAvailable = false;
1064                } catch (IOException e) {
1065                    Log.w(TAG, "Failed to read package usage times", e);
1066                } finally {
1067                    IoUtils.closeQuietly(in);
1068                }
1069            }
1070            mLastWritten.set(SystemClock.elapsedRealtime());
1071        }
1072
1073        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1074                throws IOException {
1075            sb.setLength(0);
1076            while (true) {
1077                int ch = in.read();
1078                if (ch == -1) {
1079                    if (sb.length() == 0) {
1080                        return null;
1081                    }
1082                    throw new IOException("Unexpected EOF");
1083                }
1084                if (ch == endOfToken) {
1085                    return sb.toString();
1086                }
1087                sb.append((char)ch);
1088            }
1089        }
1090
1091        private AtomicFile getFile() {
1092            File dataDir = Environment.getDataDirectory();
1093            File systemDir = new File(dataDir, "system");
1094            File fname = new File(systemDir, "package-usage.list");
1095            return new AtomicFile(fname);
1096        }
1097    }
1098
1099    class PackageHandler extends Handler {
1100        private boolean mBound = false;
1101        final ArrayList<HandlerParams> mPendingInstalls =
1102            new ArrayList<HandlerParams>();
1103
1104        private boolean connectToService() {
1105            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1106                    " DefaultContainerService");
1107            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1108            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1109            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1110                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1111                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                mBound = true;
1113                return true;
1114            }
1115            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1116            return false;
1117        }
1118
1119        private void disconnectService() {
1120            mContainerService = null;
1121            mBound = false;
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            mContext.unbindService(mDefContainerConn);
1124            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125        }
1126
1127        PackageHandler(Looper looper) {
1128            super(looper);
1129        }
1130
1131        public void handleMessage(Message msg) {
1132            try {
1133                doHandleMessage(msg);
1134            } finally {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136            }
1137        }
1138
1139        void doHandleMessage(Message msg) {
1140            switch (msg.what) {
1141                case INIT_COPY: {
1142                    HandlerParams params = (HandlerParams) msg.obj;
1143                    int idx = mPendingInstalls.size();
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1145                    // If a bind was already initiated we dont really
1146                    // need to do anything. The pending install
1147                    // will be processed later on.
1148                    if (!mBound) {
1149                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1150                                System.identityHashCode(mHandler));
1151                        // If this is the only one pending we might
1152                        // have to bind to the service again.
1153                        if (!connectToService()) {
1154                            Slog.e(TAG, "Failed to bind to media container service");
1155                            params.serviceError();
1156                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1157                                    System.identityHashCode(mHandler));
1158                            if (params.traceMethod != null) {
1159                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1160                                        params.traceCookie);
1161                            }
1162                            return;
1163                        } else {
1164                            // Once we bind to the service, the first
1165                            // pending request will be processed.
1166                            mPendingInstalls.add(idx, params);
1167                        }
1168                    } else {
1169                        mPendingInstalls.add(idx, params);
1170                        // Already bound to the service. Just make
1171                        // sure we trigger off processing the first request.
1172                        if (idx == 0) {
1173                            mHandler.sendEmptyMessage(MCS_BOUND);
1174                        }
1175                    }
1176                    break;
1177                }
1178                case MCS_BOUND: {
1179                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1180                    if (msg.obj != null) {
1181                        mContainerService = (IMediaContainerService) msg.obj;
1182                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1183                                System.identityHashCode(mHandler));
1184                    }
1185                    if (mContainerService == null) {
1186                        if (!mBound) {
1187                            // Something seriously wrong since we are not bound and we are not
1188                            // waiting for connection. Bail out.
1189                            Slog.e(TAG, "Cannot bind to media container service");
1190                            for (HandlerParams params : mPendingInstalls) {
1191                                // Indicate service bind error
1192                                params.serviceError();
1193                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1194                                        System.identityHashCode(params));
1195                                if (params.traceMethod != null) {
1196                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1197                                            params.traceMethod, params.traceCookie);
1198                                }
1199                                return;
1200                            }
1201                            mPendingInstalls.clear();
1202                        } else {
1203                            Slog.w(TAG, "Waiting to connect to media container service");
1204                        }
1205                    } else if (mPendingInstalls.size() > 0) {
1206                        HandlerParams params = mPendingInstalls.get(0);
1207                        if (params != null) {
1208                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1209                                    System.identityHashCode(params));
1210                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1211                            if (params.startCopy()) {
1212                                // We are done...  look for more work or to
1213                                // go idle.
1214                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1215                                        "Checking for more work or unbind...");
1216                                // Delete pending install
1217                                if (mPendingInstalls.size() > 0) {
1218                                    mPendingInstalls.remove(0);
1219                                }
1220                                if (mPendingInstalls.size() == 0) {
1221                                    if (mBound) {
1222                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1223                                                "Posting delayed MCS_UNBIND");
1224                                        removeMessages(MCS_UNBIND);
1225                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1226                                        // Unbind after a little delay, to avoid
1227                                        // continual thrashing.
1228                                        sendMessageDelayed(ubmsg, 10000);
1229                                    }
1230                                } else {
1231                                    // There are more pending requests in queue.
1232                                    // Just post MCS_BOUND message to trigger processing
1233                                    // of next pending install.
1234                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1235                                            "Posting MCS_BOUND for next work");
1236                                    mHandler.sendEmptyMessage(MCS_BOUND);
1237                                }
1238                            }
1239                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1240                        }
1241                    } else {
1242                        // Should never happen ideally.
1243                        Slog.w(TAG, "Empty queue");
1244                    }
1245                    break;
1246                }
1247                case MCS_RECONNECT: {
1248                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1249                    if (mPendingInstalls.size() > 0) {
1250                        if (mBound) {
1251                            disconnectService();
1252                        }
1253                        if (!connectToService()) {
1254                            Slog.e(TAG, "Failed to bind to media container service");
1255                            for (HandlerParams params : mPendingInstalls) {
1256                                // Indicate service bind error
1257                                params.serviceError();
1258                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1259                                        System.identityHashCode(params));
1260                            }
1261                            mPendingInstalls.clear();
1262                        }
1263                    }
1264                    break;
1265                }
1266                case MCS_UNBIND: {
1267                    // If there is no actual work left, then time to unbind.
1268                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1269
1270                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1271                        if (mBound) {
1272                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1273
1274                            disconnectService();
1275                        }
1276                    } else if (mPendingInstalls.size() > 0) {
1277                        // There are more pending requests in queue.
1278                        // Just post MCS_BOUND message to trigger processing
1279                        // of next pending install.
1280                        mHandler.sendEmptyMessage(MCS_BOUND);
1281                    }
1282
1283                    break;
1284                }
1285                case MCS_GIVE_UP: {
1286                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1287                    HandlerParams params = mPendingInstalls.remove(0);
1288                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1289                            System.identityHashCode(params));
1290                    break;
1291                }
1292                case SEND_PENDING_BROADCAST: {
1293                    String packages[];
1294                    ArrayList<String> components[];
1295                    int size = 0;
1296                    int uids[];
1297                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1298                    synchronized (mPackages) {
1299                        if (mPendingBroadcasts == null) {
1300                            return;
1301                        }
1302                        size = mPendingBroadcasts.size();
1303                        if (size <= 0) {
1304                            // Nothing to be done. Just return
1305                            return;
1306                        }
1307                        packages = new String[size];
1308                        components = new ArrayList[size];
1309                        uids = new int[size];
1310                        int i = 0;  // filling out the above arrays
1311
1312                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1313                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1314                            Iterator<Map.Entry<String, ArrayList<String>>> it
1315                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1316                                            .entrySet().iterator();
1317                            while (it.hasNext() && i < size) {
1318                                Map.Entry<String, ArrayList<String>> ent = it.next();
1319                                packages[i] = ent.getKey();
1320                                components[i] = ent.getValue();
1321                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1322                                uids[i] = (ps != null)
1323                                        ? UserHandle.getUid(packageUserId, ps.appId)
1324                                        : -1;
1325                                i++;
1326                            }
1327                        }
1328                        size = i;
1329                        mPendingBroadcasts.clear();
1330                    }
1331                    // Send broadcasts
1332                    for (int i = 0; i < size; i++) {
1333                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1334                    }
1335                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336                    break;
1337                }
1338                case START_CLEANING_PACKAGE: {
1339                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1340                    final String packageName = (String)msg.obj;
1341                    final int userId = msg.arg1;
1342                    final boolean andCode = msg.arg2 != 0;
1343                    synchronized (mPackages) {
1344                        if (userId == UserHandle.USER_ALL) {
1345                            int[] users = sUserManager.getUserIds();
1346                            for (int user : users) {
1347                                mSettings.addPackageToCleanLPw(
1348                                        new PackageCleanItem(user, packageName, andCode));
1349                            }
1350                        } else {
1351                            mSettings.addPackageToCleanLPw(
1352                                    new PackageCleanItem(userId, packageName, andCode));
1353                        }
1354                    }
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1356                    startCleaningPackages();
1357                } break;
1358                case POST_INSTALL: {
1359                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1360                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1361                    mRunningInstalls.delete(msg.arg1);
1362                    boolean deleteOld = false;
1363
1364                    if (data != null) {
1365                        InstallArgs args = data.args;
1366                        PackageInstalledInfo res = data.res;
1367
1368                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1369                            final String packageName = res.pkg.applicationInfo.packageName;
1370                            res.removedInfo.sendBroadcast(false, true, false);
1371                            Bundle extras = new Bundle(1);
1372                            extras.putInt(Intent.EXTRA_UID, res.uid);
1373
1374                            // Now that we successfully installed the package, grant runtime
1375                            // permissions if requested before broadcasting the install.
1376                            if ((args.installFlags
1377                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1378                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1379                                        args.installGrantPermissions);
1380                            }
1381
1382                            // Determine the set of users who are adding this
1383                            // package for the first time vs. those who are seeing
1384                            // an update.
1385                            int[] firstUsers;
1386                            int[] updateUsers = new int[0];
1387                            if (res.origUsers == null || res.origUsers.length == 0) {
1388                                firstUsers = res.newUsers;
1389                            } else {
1390                                firstUsers = new int[0];
1391                                for (int i=0; i<res.newUsers.length; i++) {
1392                                    int user = res.newUsers[i];
1393                                    boolean isNew = true;
1394                                    for (int j=0; j<res.origUsers.length; j++) {
1395                                        if (res.origUsers[j] == user) {
1396                                            isNew = false;
1397                                            break;
1398                                        }
1399                                    }
1400                                    if (isNew) {
1401                                        int[] newFirst = new int[firstUsers.length+1];
1402                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1403                                                firstUsers.length);
1404                                        newFirst[firstUsers.length] = user;
1405                                        firstUsers = newFirst;
1406                                    } else {
1407                                        int[] newUpdate = new int[updateUsers.length+1];
1408                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1409                                                updateUsers.length);
1410                                        newUpdate[updateUsers.length] = user;
1411                                        updateUsers = newUpdate;
1412                                    }
1413                                }
1414                            }
1415                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1416                                    packageName, extras, null, null, firstUsers);
1417                            final boolean update = res.removedInfo.removedPackage != null;
1418                            if (update) {
1419                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1420                            }
1421                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1422                                    packageName, extras, null, null, updateUsers);
1423                            if (update) {
1424                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1425                                        packageName, extras, null, null, updateUsers);
1426                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1427                                        null, null, packageName, null, updateUsers);
1428
1429                                // treat asec-hosted packages like removable media on upgrade
1430                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1431                                    if (DEBUG_INSTALL) {
1432                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1433                                                + " is ASEC-hosted -> AVAILABLE");
1434                                    }
1435                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1436                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1437                                    pkgList.add(packageName);
1438                                    sendResourcesChangedBroadcast(true, true,
1439                                            pkgList,uidArray, null);
1440                                }
1441                            }
1442                            if (res.removedInfo.args != null) {
1443                                // Remove the replaced package's older resources safely now
1444                                deleteOld = true;
1445                            }
1446
1447                            // If this app is a browser and it's newly-installed for some
1448                            // users, clear any default-browser state in those users
1449                            if (firstUsers.length > 0) {
1450                                // the app's nature doesn't depend on the user, so we can just
1451                                // check its browser nature in any user and generalize.
1452                                if (packageIsBrowser(packageName, firstUsers[0])) {
1453                                    synchronized (mPackages) {
1454                                        for (int userId : firstUsers) {
1455                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1456                                        }
1457                                    }
1458                                }
1459                            }
1460                            // Log current value of "unknown sources" setting
1461                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1462                                getUnknownSourcesSettings());
1463                        }
1464                        // Force a gc to clear up things
1465                        Runtime.getRuntime().gc();
1466                        // We delete after a gc for applications  on sdcard.
1467                        if (deleteOld) {
1468                            synchronized (mInstallLock) {
1469                                res.removedInfo.args.doPostDeleteLI(true);
1470                            }
1471                        }
1472                        if (args.observer != null) {
1473                            try {
1474                                Bundle extras = extrasForInstallResult(res);
1475                                args.observer.onPackageInstalled(res.name, res.returnCode,
1476                                        res.returnMsg, extras);
1477                            } catch (RemoteException e) {
1478                                Slog.i(TAG, "Observer no longer exists.");
1479                            }
1480                        }
1481                        if (args.traceMethod != null) {
1482                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1483                                    args.traceCookie);
1484                        }
1485                        return;
1486                    } else {
1487                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1488                    }
1489
1490                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1491                } break;
1492                case UPDATED_MEDIA_STATUS: {
1493                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1494                    boolean reportStatus = msg.arg1 == 1;
1495                    boolean doGc = msg.arg2 == 1;
1496                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1497                    if (doGc) {
1498                        // Force a gc to clear up stale containers.
1499                        Runtime.getRuntime().gc();
1500                    }
1501                    if (msg.obj != null) {
1502                        @SuppressWarnings("unchecked")
1503                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1504                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1505                        // Unload containers
1506                        unloadAllContainers(args);
1507                    }
1508                    if (reportStatus) {
1509                        try {
1510                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1511                            PackageHelper.getMountService().finishMediaUpdate();
1512                        } catch (RemoteException e) {
1513                            Log.e(TAG, "MountService not running?");
1514                        }
1515                    }
1516                } break;
1517                case WRITE_SETTINGS: {
1518                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1519                    synchronized (mPackages) {
1520                        removeMessages(WRITE_SETTINGS);
1521                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1522                        mSettings.writeLPr();
1523                        mDirtyUsers.clear();
1524                    }
1525                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1526                } break;
1527                case WRITE_PACKAGE_RESTRICTIONS: {
1528                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1529                    synchronized (mPackages) {
1530                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1531                        for (int userId : mDirtyUsers) {
1532                            mSettings.writePackageRestrictionsLPr(userId);
1533                        }
1534                        mDirtyUsers.clear();
1535                    }
1536                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1537                } break;
1538                case CHECK_PENDING_VERIFICATION: {
1539                    final int verificationId = msg.arg1;
1540                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1541
1542                    if ((state != null) && !state.timeoutExtended()) {
1543                        final InstallArgs args = state.getInstallArgs();
1544                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1545
1546                        Slog.i(TAG, "Verification timed out for " + originUri);
1547                        mPendingVerification.remove(verificationId);
1548
1549                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1550
1551                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1552                            Slog.i(TAG, "Continuing with installation of " + originUri);
1553                            state.setVerifierResponse(Binder.getCallingUid(),
1554                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1555                            broadcastPackageVerified(verificationId, originUri,
1556                                    PackageManager.VERIFICATION_ALLOW,
1557                                    state.getInstallArgs().getUser());
1558                            try {
1559                                ret = args.copyApk(mContainerService, true);
1560                            } catch (RemoteException e) {
1561                                Slog.e(TAG, "Could not contact the ContainerService");
1562                            }
1563                        } else {
1564                            broadcastPackageVerified(verificationId, originUri,
1565                                    PackageManager.VERIFICATION_REJECT,
1566                                    state.getInstallArgs().getUser());
1567                        }
1568
1569                        Trace.asyncTraceEnd(
1570                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1571
1572                        processPendingInstall(args, ret);
1573                        mHandler.sendEmptyMessage(MCS_UNBIND);
1574                    }
1575                    break;
1576                }
1577                case PACKAGE_VERIFIED: {
1578                    final int verificationId = msg.arg1;
1579
1580                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1581                    if (state == null) {
1582                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1583                        break;
1584                    }
1585
1586                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1587
1588                    state.setVerifierResponse(response.callerUid, response.code);
1589
1590                    if (state.isVerificationComplete()) {
1591                        mPendingVerification.remove(verificationId);
1592
1593                        final InstallArgs args = state.getInstallArgs();
1594                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1595
1596                        int ret;
1597                        if (state.isInstallAllowed()) {
1598                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    response.code, state.getInstallArgs().getUser());
1601                            try {
1602                                ret = args.copyApk(mContainerService, true);
1603                            } catch (RemoteException e) {
1604                                Slog.e(TAG, "Could not contact the ContainerService");
1605                            }
1606                        } else {
1607                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1608                        }
1609
1610                        Trace.asyncTraceEnd(
1611                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1612
1613                        processPendingInstall(args, ret);
1614                        mHandler.sendEmptyMessage(MCS_UNBIND);
1615                    }
1616
1617                    break;
1618                }
1619                case START_INTENT_FILTER_VERIFICATIONS: {
1620                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1621                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1622                            params.replacing, params.pkg);
1623                    break;
1624                }
1625                case INTENT_FILTER_VERIFIED: {
1626                    final int verificationId = msg.arg1;
1627
1628                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1629                            verificationId);
1630                    if (state == null) {
1631                        Slog.w(TAG, "Invalid IntentFilter verification token "
1632                                + verificationId + " received");
1633                        break;
1634                    }
1635
1636                    final int userId = state.getUserId();
1637
1638                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1639                            "Processing IntentFilter verification with token:"
1640                            + verificationId + " and userId:" + userId);
1641
1642                    final IntentFilterVerificationResponse response =
1643                            (IntentFilterVerificationResponse) msg.obj;
1644
1645                    state.setVerifierResponse(response.callerUid, response.code);
1646
1647                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1648                            "IntentFilter verification with token:" + verificationId
1649                            + " and userId:" + userId
1650                            + " is settings verifier response with response code:"
1651                            + response.code);
1652
1653                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1654                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1655                                + response.getFailedDomainsString());
1656                    }
1657
1658                    if (state.isVerificationComplete()) {
1659                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1660                    } else {
1661                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1662                                "IntentFilter verification with token:" + verificationId
1663                                + " was not said to be complete");
1664                    }
1665
1666                    break;
1667                }
1668            }
1669        }
1670    }
1671
1672    private StorageEventListener mStorageListener = new StorageEventListener() {
1673        @Override
1674        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1675            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1676                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1677                    final String volumeUuid = vol.getFsUuid();
1678
1679                    // Clean up any users or apps that were removed or recreated
1680                    // while this volume was missing
1681                    reconcileUsers(volumeUuid);
1682                    reconcileApps(volumeUuid);
1683
1684                    // Clean up any install sessions that expired or were
1685                    // cancelled while this volume was missing
1686                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1687
1688                    loadPrivatePackages(vol);
1689
1690                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1691                    unloadPrivatePackages(vol);
1692                }
1693            }
1694
1695            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1696                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1697                    updateExternalMediaStatus(true, false);
1698                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1699                    updateExternalMediaStatus(false, false);
1700                }
1701            }
1702        }
1703
1704        @Override
1705        public void onVolumeForgotten(String fsUuid) {
1706            if (TextUtils.isEmpty(fsUuid)) {
1707                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1708                return;
1709            }
1710
1711            // Remove any apps installed on the forgotten volume
1712            synchronized (mPackages) {
1713                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1714                for (PackageSetting ps : packages) {
1715                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1716                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1717                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1718                }
1719
1720                mSettings.onVolumeForgotten(fsUuid);
1721                mSettings.writeLPr();
1722            }
1723        }
1724    };
1725
1726    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1727            String[] grantedPermissions) {
1728        if (userId >= UserHandle.USER_SYSTEM) {
1729            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1730        } else if (userId == UserHandle.USER_ALL) {
1731            final int[] userIds;
1732            synchronized (mPackages) {
1733                userIds = UserManagerService.getInstance().getUserIds();
1734            }
1735            for (int someUserId : userIds) {
1736                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1737            }
1738        }
1739
1740        // We could have touched GID membership, so flush out packages.list
1741        synchronized (mPackages) {
1742            mSettings.writePackageListLPr();
1743        }
1744    }
1745
1746    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1747            String[] grantedPermissions) {
1748        SettingBase sb = (SettingBase) pkg.mExtras;
1749        if (sb == null) {
1750            return;
1751        }
1752
1753        PermissionsState permissionsState = sb.getPermissionsState();
1754
1755        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1756                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1757
1758        synchronized (mPackages) {
1759            for (String permission : pkg.requestedPermissions) {
1760                BasePermission bp = mSettings.mPermissions.get(permission);
1761                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1762                        && (grantedPermissions == null
1763                               || ArrayUtils.contains(grantedPermissions, permission))) {
1764                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1765                    // Installer cannot change immutable permissions.
1766                    if ((flags & immutableFlags) == 0) {
1767                        grantRuntimePermission(pkg.packageName, permission, userId);
1768                    }
1769                }
1770            }
1771        }
1772    }
1773
1774    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1775        Bundle extras = null;
1776        switch (res.returnCode) {
1777            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1778                extras = new Bundle();
1779                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1780                        res.origPermission);
1781                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1782                        res.origPackage);
1783                break;
1784            }
1785            case PackageManager.INSTALL_SUCCEEDED: {
1786                extras = new Bundle();
1787                extras.putBoolean(Intent.EXTRA_REPLACING,
1788                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1789                break;
1790            }
1791        }
1792        return extras;
1793    }
1794
1795    void scheduleWriteSettingsLocked() {
1796        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1797            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1798        }
1799    }
1800
1801    void scheduleWritePackageRestrictionsLocked(int userId) {
1802        if (!sUserManager.exists(userId)) return;
1803        mDirtyUsers.add(userId);
1804        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1805            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1806        }
1807    }
1808
1809    public static PackageManagerService main(Context context, Installer installer,
1810            boolean factoryTest, boolean onlyCore) {
1811        PackageManagerService m = new PackageManagerService(context, installer,
1812                factoryTest, onlyCore);
1813        ServiceManager.addService("package", m);
1814        return m;
1815    }
1816
1817    static String[] splitString(String str, char sep) {
1818        int count = 1;
1819        int i = 0;
1820        while ((i=str.indexOf(sep, i)) >= 0) {
1821            count++;
1822            i++;
1823        }
1824
1825        String[] res = new String[count];
1826        i=0;
1827        count = 0;
1828        int lastI=0;
1829        while ((i=str.indexOf(sep, i)) >= 0) {
1830            res[count] = str.substring(lastI, i);
1831            count++;
1832            i++;
1833            lastI = i;
1834        }
1835        res[count] = str.substring(lastI, str.length());
1836        return res;
1837    }
1838
1839    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1840        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1841                Context.DISPLAY_SERVICE);
1842        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1843    }
1844
1845    public PackageManagerService(Context context, Installer installer,
1846            boolean factoryTest, boolean onlyCore) {
1847        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1848                SystemClock.uptimeMillis());
1849
1850        if (mSdkVersion <= 0) {
1851            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1852        }
1853
1854        mContext = context;
1855        mFactoryTest = factoryTest;
1856        mOnlyCore = onlyCore;
1857        mMetrics = new DisplayMetrics();
1858        mSettings = new Settings(mPackages);
1859        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1860                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1861        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1862                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1863        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1864                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1865        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1866                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1867        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1868                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1869        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1870                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1871
1872        String separateProcesses = SystemProperties.get("debug.separate_processes");
1873        if (separateProcesses != null && separateProcesses.length() > 0) {
1874            if ("*".equals(separateProcesses)) {
1875                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1876                mSeparateProcesses = null;
1877                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1878            } else {
1879                mDefParseFlags = 0;
1880                mSeparateProcesses = separateProcesses.split(",");
1881                Slog.w(TAG, "Running with debug.separate_processes: "
1882                        + separateProcesses);
1883            }
1884        } else {
1885            mDefParseFlags = 0;
1886            mSeparateProcesses = null;
1887        }
1888
1889        mInstaller = installer;
1890        mPackageDexOptimizer = new PackageDexOptimizer(this);
1891        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1892
1893        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1894                FgThread.get().getLooper());
1895
1896        getDefaultDisplayMetrics(context, mMetrics);
1897
1898        SystemConfig systemConfig = SystemConfig.getInstance();
1899        mGlobalGids = systemConfig.getGlobalGids();
1900        mSystemPermissions = systemConfig.getSystemPermissions();
1901        mAvailableFeatures = systemConfig.getAvailableFeatures();
1902
1903        synchronized (mInstallLock) {
1904        // writer
1905        synchronized (mPackages) {
1906            mHandlerThread = new ServiceThread(TAG,
1907                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1908            mHandlerThread.start();
1909            mHandler = new PackageHandler(mHandlerThread.getLooper());
1910            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1911
1912            File dataDir = Environment.getDataDirectory();
1913            mAppDataDir = new File(dataDir, "data");
1914            mAppInstallDir = new File(dataDir, "app");
1915            mAppLib32InstallDir = new File(dataDir, "app-lib");
1916            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1917            mUserAppDataDir = new File(dataDir, "user");
1918            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1919
1920            sUserManager = new UserManagerService(context, this,
1921                    mInstallLock, mPackages);
1922
1923            // Propagate permission configuration in to package manager.
1924            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1925                    = systemConfig.getPermissions();
1926            for (int i=0; i<permConfig.size(); i++) {
1927                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1928                BasePermission bp = mSettings.mPermissions.get(perm.name);
1929                if (bp == null) {
1930                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1931                    mSettings.mPermissions.put(perm.name, bp);
1932                }
1933                if (perm.gids != null) {
1934                    bp.setGids(perm.gids, perm.perUser);
1935                }
1936            }
1937
1938            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1939            for (int i=0; i<libConfig.size(); i++) {
1940                mSharedLibraries.put(libConfig.keyAt(i),
1941                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1942            }
1943
1944            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1945
1946            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1947
1948            String customResolverActivity = Resources.getSystem().getString(
1949                    R.string.config_customResolverActivity);
1950            if (TextUtils.isEmpty(customResolverActivity)) {
1951                customResolverActivity = null;
1952            } else {
1953                mCustomResolverComponentName = ComponentName.unflattenFromString(
1954                        customResolverActivity);
1955            }
1956
1957            long startTime = SystemClock.uptimeMillis();
1958
1959            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1960                    startTime);
1961
1962            // Set flag to monitor and not change apk file paths when
1963            // scanning install directories.
1964            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1965
1966            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1967            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1968
1969            if (bootClassPath == null) {
1970                Slog.w(TAG, "No BOOTCLASSPATH found!");
1971            }
1972
1973            if (systemServerClassPath == null) {
1974                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1975            }
1976
1977            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1978            final String[] dexCodeInstructionSets =
1979                    getDexCodeInstructionSets(
1980                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1981
1982            /**
1983             * Ensure all external libraries have had dexopt run on them.
1984             */
1985            if (mSharedLibraries.size() > 0) {
1986                // NOTE: For now, we're compiling these system "shared libraries"
1987                // (and framework jars) into all available architectures. It's possible
1988                // to compile them only when we come across an app that uses them (there's
1989                // already logic for that in scanPackageLI) but that adds some complexity.
1990                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1991                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1992                        final String lib = libEntry.path;
1993                        if (lib == null) {
1994                            continue;
1995                        }
1996
1997                        try {
1998                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1999                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2000                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2001                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2002                            }
2003                        } catch (FileNotFoundException e) {
2004                            Slog.w(TAG, "Library not found: " + lib);
2005                        } catch (IOException e) {
2006                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2007                                    + e.getMessage());
2008                        }
2009                    }
2010                }
2011            }
2012
2013            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2014
2015            final VersionInfo ver = mSettings.getInternalVersion();
2016            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2017            // when upgrading from pre-M, promote system app permissions from install to runtime
2018            mPromoteSystemApps =
2019                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2020
2021            // save off the names of pre-existing system packages prior to scanning; we don't
2022            // want to automatically grant runtime permissions for new system apps
2023            if (mPromoteSystemApps) {
2024                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2025                while (pkgSettingIter.hasNext()) {
2026                    PackageSetting ps = pkgSettingIter.next();
2027                    if (isSystemApp(ps)) {
2028                        mExistingSystemPackages.add(ps.name);
2029                    }
2030                }
2031            }
2032
2033            // Collect vendor overlay packages.
2034            // (Do this before scanning any apps.)
2035            // For security and version matching reason, only consider
2036            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2037            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2038            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2039                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2040
2041            // Find base frameworks (resource packages without code).
2042            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2043                    | PackageParser.PARSE_IS_SYSTEM_DIR
2044                    | PackageParser.PARSE_IS_PRIVILEGED,
2045                    scanFlags | SCAN_NO_DEX, 0);
2046
2047            // Collected privileged system packages.
2048            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2049            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2050                    | PackageParser.PARSE_IS_SYSTEM_DIR
2051                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2052
2053            // Collect ordinary system packages.
2054            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2055            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2056                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2057
2058            // Collect all vendor packages.
2059            File vendorAppDir = new File("/vendor/app");
2060            try {
2061                vendorAppDir = vendorAppDir.getCanonicalFile();
2062            } catch (IOException e) {
2063                // failed to look up canonical path, continue with original one
2064            }
2065            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2066                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2067
2068            // Collect all OEM packages.
2069            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2070            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2071                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2072
2073            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2074            mInstaller.moveFiles();
2075
2076            // Prune any system packages that no longer exist.
2077            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2078            if (!mOnlyCore) {
2079                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2080                while (psit.hasNext()) {
2081                    PackageSetting ps = psit.next();
2082
2083                    /*
2084                     * If this is not a system app, it can't be a
2085                     * disable system app.
2086                     */
2087                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2088                        continue;
2089                    }
2090
2091                    /*
2092                     * If the package is scanned, it's not erased.
2093                     */
2094                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2095                    if (scannedPkg != null) {
2096                        /*
2097                         * If the system app is both scanned and in the
2098                         * disabled packages list, then it must have been
2099                         * added via OTA. Remove it from the currently
2100                         * scanned package so the previously user-installed
2101                         * application can be scanned.
2102                         */
2103                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2104                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2105                                    + ps.name + "; removing system app.  Last known codePath="
2106                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2107                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2108                                    + scannedPkg.mVersionCode);
2109                            removePackageLI(ps, true);
2110                            mExpectingBetter.put(ps.name, ps.codePath);
2111                        }
2112
2113                        continue;
2114                    }
2115
2116                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2117                        psit.remove();
2118                        logCriticalInfo(Log.WARN, "System package " + ps.name
2119                                + " no longer exists; wiping its data");
2120                        removeDataDirsLI(null, ps.name);
2121                    } else {
2122                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2123                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2124                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2125                        }
2126                    }
2127                }
2128            }
2129
2130            //look for any incomplete package installations
2131            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2132            //clean up list
2133            for(int i = 0; i < deletePkgsList.size(); i++) {
2134                //clean up here
2135                cleanupInstallFailedPackage(deletePkgsList.get(i));
2136            }
2137            //delete tmp files
2138            deleteTempPackageFiles();
2139
2140            // Remove any shared userIDs that have no associated packages
2141            mSettings.pruneSharedUsersLPw();
2142
2143            if (!mOnlyCore) {
2144                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2145                        SystemClock.uptimeMillis());
2146                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2147
2148                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2149                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2150
2151                /**
2152                 * Remove disable package settings for any updated system
2153                 * apps that were removed via an OTA. If they're not a
2154                 * previously-updated app, remove them completely.
2155                 * Otherwise, just revoke their system-level permissions.
2156                 */
2157                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2158                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2159                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2160
2161                    String msg;
2162                    if (deletedPkg == null) {
2163                        msg = "Updated system package " + deletedAppName
2164                                + " no longer exists; wiping its data";
2165                        removeDataDirsLI(null, deletedAppName);
2166                    } else {
2167                        msg = "Updated system app + " + deletedAppName
2168                                + " no longer present; removing system privileges for "
2169                                + deletedAppName;
2170
2171                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2172
2173                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2174                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2175                    }
2176                    logCriticalInfo(Log.WARN, msg);
2177                }
2178
2179                /**
2180                 * Make sure all system apps that we expected to appear on
2181                 * the userdata partition actually showed up. If they never
2182                 * appeared, crawl back and revive the system version.
2183                 */
2184                for (int i = 0; i < mExpectingBetter.size(); i++) {
2185                    final String packageName = mExpectingBetter.keyAt(i);
2186                    if (!mPackages.containsKey(packageName)) {
2187                        final File scanFile = mExpectingBetter.valueAt(i);
2188
2189                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2190                                + " but never showed up; reverting to system");
2191
2192                        final int reparseFlags;
2193                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2194                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2195                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2196                                    | PackageParser.PARSE_IS_PRIVILEGED;
2197                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2198                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2199                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2200                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2201                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2202                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2203                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2204                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2205                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2206                        } else {
2207                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2208                            continue;
2209                        }
2210
2211                        mSettings.enableSystemPackageLPw(packageName);
2212
2213                        try {
2214                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2215                        } catch (PackageManagerException e) {
2216                            Slog.e(TAG, "Failed to parse original system package: "
2217                                    + e.getMessage());
2218                        }
2219                    }
2220                }
2221            }
2222            mExpectingBetter.clear();
2223
2224            // Now that we know all of the shared libraries, update all clients to have
2225            // the correct library paths.
2226            updateAllSharedLibrariesLPw();
2227
2228            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2229                // NOTE: We ignore potential failures here during a system scan (like
2230                // the rest of the commands above) because there's precious little we
2231                // can do about it. A settings error is reported, though.
2232                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2233                        false /* boot complete */);
2234            }
2235
2236            // Now that we know all the packages we are keeping,
2237            // read and update their last usage times.
2238            mPackageUsage.readLP();
2239
2240            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2241                    SystemClock.uptimeMillis());
2242            Slog.i(TAG, "Time to scan packages: "
2243                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2244                    + " seconds");
2245
2246            // If the platform SDK has changed since the last time we booted,
2247            // we need to re-grant app permission to catch any new ones that
2248            // appear.  This is really a hack, and means that apps can in some
2249            // cases get permissions that the user didn't initially explicitly
2250            // allow...  it would be nice to have some better way to handle
2251            // this situation.
2252            int updateFlags = UPDATE_PERMISSIONS_ALL;
2253            if (ver.sdkVersion != mSdkVersion) {
2254                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2255                        + mSdkVersion + "; regranting permissions for internal storage");
2256                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2257            }
2258            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2259            ver.sdkVersion = mSdkVersion;
2260
2261            // If this is the first boot or an update from pre-M, and it is a normal
2262            // boot, then we need to initialize the default preferred apps across
2263            // all defined users.
2264            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2265                for (UserInfo user : sUserManager.getUsers(true)) {
2266                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2267                    applyFactoryDefaultBrowserLPw(user.id);
2268                    primeDomainVerificationsLPw(user.id);
2269                }
2270            }
2271
2272            // If this is first boot after an OTA, and a normal boot, then
2273            // we need to clear code cache directories.
2274            if (mIsUpgrade && !onlyCore) {
2275                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2276                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2277                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2278                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2279                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2280                    }
2281                }
2282                ver.fingerprint = Build.FINGERPRINT;
2283            }
2284
2285            checkDefaultBrowser();
2286
2287            // clear only after permissions and other defaults have been updated
2288            mExistingSystemPackages.clear();
2289            mPromoteSystemApps = false;
2290
2291            // All the changes are done during package scanning.
2292            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2293
2294            // can downgrade to reader
2295            mSettings.writeLPr();
2296
2297            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2298                    SystemClock.uptimeMillis());
2299
2300            mRequiredVerifierPackage = getRequiredVerifierLPr();
2301            mRequiredInstallerPackage = getRequiredInstallerLPr();
2302
2303            mInstallerService = new PackageInstallerService(context, this);
2304
2305            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2306            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2307                    mIntentFilterVerifierComponent);
2308
2309        } // synchronized (mPackages)
2310        } // synchronized (mInstallLock)
2311
2312        // Now after opening every single application zip, make sure they
2313        // are all flushed.  Not really needed, but keeps things nice and
2314        // tidy.
2315        Runtime.getRuntime().gc();
2316
2317        // The initial scanning above does many calls into installd while
2318        // holding the mPackages lock, but we're mostly interested in yelling
2319        // once we have a booted system.
2320        mInstaller.setWarnIfHeld(mPackages);
2321
2322        // Expose private service for system components to use.
2323        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2324    }
2325
2326    @Override
2327    public boolean isFirstBoot() {
2328        return !mRestoredSettings;
2329    }
2330
2331    @Override
2332    public boolean isOnlyCoreApps() {
2333        return mOnlyCore;
2334    }
2335
2336    @Override
2337    public boolean isUpgrade() {
2338        return mIsUpgrade;
2339    }
2340
2341    private String getRequiredVerifierLPr() {
2342        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2343        // We only care about verifier that's installed under system user.
2344        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2345                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2346
2347        String requiredVerifier = null;
2348
2349        final int N = receivers.size();
2350        for (int i = 0; i < N; i++) {
2351            final ResolveInfo info = receivers.get(i);
2352
2353            if (info.activityInfo == null) {
2354                continue;
2355            }
2356
2357            final String packageName = info.activityInfo.packageName;
2358
2359            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2360                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2361                continue;
2362            }
2363
2364            if (requiredVerifier != null) {
2365                throw new RuntimeException("There can be only one required verifier");
2366            }
2367
2368            requiredVerifier = packageName;
2369        }
2370
2371        return requiredVerifier;
2372    }
2373
2374    private String getRequiredInstallerLPr() {
2375        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2376        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2377        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2378
2379        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2380                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2381
2382        String requiredInstaller = null;
2383
2384        final int N = installers.size();
2385        for (int i = 0; i < N; i++) {
2386            final ResolveInfo info = installers.get(i);
2387            final String packageName = info.activityInfo.packageName;
2388
2389            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2390                continue;
2391            }
2392
2393            if (requiredInstaller != null) {
2394                throw new RuntimeException("There must be one required installer");
2395            }
2396
2397            requiredInstaller = packageName;
2398        }
2399
2400        if (requiredInstaller == null) {
2401            throw new RuntimeException("There must be one required installer");
2402        }
2403
2404        return requiredInstaller;
2405    }
2406
2407    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2408        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2409        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2410                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2411
2412        ComponentName verifierComponentName = null;
2413
2414        int priority = -1000;
2415        final int N = receivers.size();
2416        for (int i = 0; i < N; i++) {
2417            final ResolveInfo info = receivers.get(i);
2418
2419            if (info.activityInfo == null) {
2420                continue;
2421            }
2422
2423            final String packageName = info.activityInfo.packageName;
2424
2425            final PackageSetting ps = mSettings.mPackages.get(packageName);
2426            if (ps == null) {
2427                continue;
2428            }
2429
2430            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2431                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2432                continue;
2433            }
2434
2435            // Select the IntentFilterVerifier with the highest priority
2436            if (priority < info.priority) {
2437                priority = info.priority;
2438                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2439                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2440                        + verifierComponentName + " with priority: " + info.priority);
2441            }
2442        }
2443
2444        return verifierComponentName;
2445    }
2446
2447    private void primeDomainVerificationsLPw(int userId) {
2448        if (DEBUG_DOMAIN_VERIFICATION) {
2449            Slog.d(TAG, "Priming domain verifications in user " + userId);
2450        }
2451
2452        SystemConfig systemConfig = SystemConfig.getInstance();
2453        ArraySet<String> packages = systemConfig.getLinkedApps();
2454        ArraySet<String> domains = new ArraySet<String>();
2455
2456        for (String packageName : packages) {
2457            PackageParser.Package pkg = mPackages.get(packageName);
2458            if (pkg != null) {
2459                if (!pkg.isSystemApp()) {
2460                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2461                    continue;
2462                }
2463
2464                domains.clear();
2465                for (PackageParser.Activity a : pkg.activities) {
2466                    for (ActivityIntentInfo filter : a.intents) {
2467                        if (hasValidDomains(filter)) {
2468                            domains.addAll(filter.getHostsList());
2469                        }
2470                    }
2471                }
2472
2473                if (domains.size() > 0) {
2474                    if (DEBUG_DOMAIN_VERIFICATION) {
2475                        Slog.v(TAG, "      + " + packageName);
2476                    }
2477                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2478                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2479                    // and then 'always' in the per-user state actually used for intent resolution.
2480                    final IntentFilterVerificationInfo ivi;
2481                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2482                            new ArrayList<String>(domains));
2483                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2484                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2485                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2486                } else {
2487                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2488                            + "' does not handle web links");
2489                }
2490            } else {
2491                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2492            }
2493        }
2494
2495        scheduleWritePackageRestrictionsLocked(userId);
2496        scheduleWriteSettingsLocked();
2497    }
2498
2499    private void applyFactoryDefaultBrowserLPw(int userId) {
2500        // The default browser app's package name is stored in a string resource,
2501        // with a product-specific overlay used for vendor customization.
2502        String browserPkg = mContext.getResources().getString(
2503                com.android.internal.R.string.default_browser);
2504        if (!TextUtils.isEmpty(browserPkg)) {
2505            // non-empty string => required to be a known package
2506            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2507            if (ps == null) {
2508                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2509                browserPkg = null;
2510            } else {
2511                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2512            }
2513        }
2514
2515        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2516        // default.  If there's more than one, just leave everything alone.
2517        if (browserPkg == null) {
2518            calculateDefaultBrowserLPw(userId);
2519        }
2520    }
2521
2522    private void calculateDefaultBrowserLPw(int userId) {
2523        List<String> allBrowsers = resolveAllBrowserApps(userId);
2524        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2525        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2526    }
2527
2528    private List<String> resolveAllBrowserApps(int userId) {
2529        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2530        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2531                PackageManager.MATCH_ALL, userId);
2532
2533        final int count = list.size();
2534        List<String> result = new ArrayList<String>(count);
2535        for (int i=0; i<count; i++) {
2536            ResolveInfo info = list.get(i);
2537            if (info.activityInfo == null
2538                    || !info.handleAllWebDataURI
2539                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2540                    || result.contains(info.activityInfo.packageName)) {
2541                continue;
2542            }
2543            result.add(info.activityInfo.packageName);
2544        }
2545
2546        return result;
2547    }
2548
2549    private boolean packageIsBrowser(String packageName, int userId) {
2550        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2551                PackageManager.MATCH_ALL, userId);
2552        final int N = list.size();
2553        for (int i = 0; i < N; i++) {
2554            ResolveInfo info = list.get(i);
2555            if (packageName.equals(info.activityInfo.packageName)) {
2556                return true;
2557            }
2558        }
2559        return false;
2560    }
2561
2562    private void checkDefaultBrowser() {
2563        final int myUserId = UserHandle.myUserId();
2564        final String packageName = getDefaultBrowserPackageName(myUserId);
2565        if (packageName != null) {
2566            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2567            if (info == null) {
2568                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2569                synchronized (mPackages) {
2570                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2571                }
2572            }
2573        }
2574    }
2575
2576    @Override
2577    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2578            throws RemoteException {
2579        try {
2580            return super.onTransact(code, data, reply, flags);
2581        } catch (RuntimeException e) {
2582            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2583                Slog.wtf(TAG, "Package Manager Crash", e);
2584            }
2585            throw e;
2586        }
2587    }
2588
2589    void cleanupInstallFailedPackage(PackageSetting ps) {
2590        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2591
2592        removeDataDirsLI(ps.volumeUuid, ps.name);
2593        if (ps.codePath != null) {
2594            if (ps.codePath.isDirectory()) {
2595                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2596            } else {
2597                ps.codePath.delete();
2598            }
2599        }
2600        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2601            if (ps.resourcePath.isDirectory()) {
2602                FileUtils.deleteContents(ps.resourcePath);
2603            }
2604            ps.resourcePath.delete();
2605        }
2606        mSettings.removePackageLPw(ps.name);
2607    }
2608
2609    static int[] appendInts(int[] cur, int[] add) {
2610        if (add == null) return cur;
2611        if (cur == null) return add;
2612        final int N = add.length;
2613        for (int i=0; i<N; i++) {
2614            cur = appendInt(cur, add[i]);
2615        }
2616        return cur;
2617    }
2618
2619    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2620        if (!sUserManager.exists(userId)) return null;
2621        final PackageSetting ps = (PackageSetting) p.mExtras;
2622        if (ps == null) {
2623            return null;
2624        }
2625
2626        final PermissionsState permissionsState = ps.getPermissionsState();
2627
2628        final int[] gids = permissionsState.computeGids(userId);
2629        final Set<String> permissions = permissionsState.getPermissions(userId);
2630        final PackageUserState state = ps.readUserState(userId);
2631
2632        return PackageParser.generatePackageInfo(p, gids, flags,
2633                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2634    }
2635
2636    @Override
2637    public boolean isPackageFrozen(String packageName) {
2638        synchronized (mPackages) {
2639            final PackageSetting ps = mSettings.mPackages.get(packageName);
2640            if (ps != null) {
2641                return ps.frozen;
2642            }
2643        }
2644        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2645        return true;
2646    }
2647
2648    @Override
2649    public boolean isPackageAvailable(String packageName, int userId) {
2650        if (!sUserManager.exists(userId)) return false;
2651        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2652        synchronized (mPackages) {
2653            PackageParser.Package p = mPackages.get(packageName);
2654            if (p != null) {
2655                final PackageSetting ps = (PackageSetting) p.mExtras;
2656                if (ps != null) {
2657                    final PackageUserState state = ps.readUserState(userId);
2658                    if (state != null) {
2659                        return PackageParser.isAvailable(state);
2660                    }
2661                }
2662            }
2663        }
2664        return false;
2665    }
2666
2667    @Override
2668    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2669        if (!sUserManager.exists(userId)) return null;
2670        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2671        // reader
2672        synchronized (mPackages) {
2673            PackageParser.Package p = mPackages.get(packageName);
2674            if (DEBUG_PACKAGE_INFO)
2675                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2676            if (p != null) {
2677                return generatePackageInfo(p, flags, userId);
2678            }
2679            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2680                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2681            }
2682        }
2683        return null;
2684    }
2685
2686    @Override
2687    public String[] currentToCanonicalPackageNames(String[] names) {
2688        String[] out = new String[names.length];
2689        // reader
2690        synchronized (mPackages) {
2691            for (int i=names.length-1; i>=0; i--) {
2692                PackageSetting ps = mSettings.mPackages.get(names[i]);
2693                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2694            }
2695        }
2696        return out;
2697    }
2698
2699    @Override
2700    public String[] canonicalToCurrentPackageNames(String[] names) {
2701        String[] out = new String[names.length];
2702        // reader
2703        synchronized (mPackages) {
2704            for (int i=names.length-1; i>=0; i--) {
2705                String cur = mSettings.mRenamedPackages.get(names[i]);
2706                out[i] = cur != null ? cur : names[i];
2707            }
2708        }
2709        return out;
2710    }
2711
2712    @Override
2713    public int getPackageUid(String packageName, int userId) {
2714        return getPackageUidEtc(packageName, 0, userId);
2715    }
2716
2717    @Override
2718    public int getPackageUidEtc(String packageName, int flags, int userId) {
2719        if (!sUserManager.exists(userId)) return -1;
2720        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2721
2722        // reader
2723        synchronized (mPackages) {
2724            final PackageParser.Package p = mPackages.get(packageName);
2725            if (p != null) {
2726                return UserHandle.getUid(userId, p.applicationInfo.uid);
2727            }
2728            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2729                final PackageSetting ps = mSettings.mPackages.get(packageName);
2730                if (ps != null) {
2731                    return UserHandle.getUid(userId, ps.appId);
2732                }
2733            }
2734        }
2735
2736        return -1;
2737    }
2738
2739    @Override
2740    public int[] getPackageGids(String packageName, int userId) {
2741        return getPackageGidsEtc(packageName, 0, userId);
2742    }
2743
2744    @Override
2745    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2746        if (!sUserManager.exists(userId)) {
2747            return null;
2748        }
2749
2750        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2751                "getPackageGids");
2752
2753        // reader
2754        synchronized (mPackages) {
2755            final PackageParser.Package p = mPackages.get(packageName);
2756            if (p != null) {
2757                PackageSetting ps = (PackageSetting) p.mExtras;
2758                return ps.getPermissionsState().computeGids(userId);
2759            }
2760            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2761                final PackageSetting ps = mSettings.mPackages.get(packageName);
2762                if (ps != null) {
2763                    return ps.getPermissionsState().computeGids(userId);
2764                }
2765            }
2766        }
2767
2768        return null;
2769    }
2770
2771    static PermissionInfo generatePermissionInfo(
2772            BasePermission bp, int flags) {
2773        if (bp.perm != null) {
2774            return PackageParser.generatePermissionInfo(bp.perm, flags);
2775        }
2776        PermissionInfo pi = new PermissionInfo();
2777        pi.name = bp.name;
2778        pi.packageName = bp.sourcePackage;
2779        pi.nonLocalizedLabel = bp.name;
2780        pi.protectionLevel = bp.protectionLevel;
2781        return pi;
2782    }
2783
2784    @Override
2785    public PermissionInfo getPermissionInfo(String name, int flags) {
2786        // reader
2787        synchronized (mPackages) {
2788            final BasePermission p = mSettings.mPermissions.get(name);
2789            if (p != null) {
2790                return generatePermissionInfo(p, flags);
2791            }
2792            return null;
2793        }
2794    }
2795
2796    @Override
2797    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2798        // reader
2799        synchronized (mPackages) {
2800            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2801            for (BasePermission p : mSettings.mPermissions.values()) {
2802                if (group == null) {
2803                    if (p.perm == null || p.perm.info.group == null) {
2804                        out.add(generatePermissionInfo(p, flags));
2805                    }
2806                } else {
2807                    if (p.perm != null && group.equals(p.perm.info.group)) {
2808                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2809                    }
2810                }
2811            }
2812
2813            if (out.size() > 0) {
2814                return out;
2815            }
2816            return mPermissionGroups.containsKey(group) ? out : null;
2817        }
2818    }
2819
2820    @Override
2821    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2822        // reader
2823        synchronized (mPackages) {
2824            return PackageParser.generatePermissionGroupInfo(
2825                    mPermissionGroups.get(name), flags);
2826        }
2827    }
2828
2829    @Override
2830    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2831        // reader
2832        synchronized (mPackages) {
2833            final int N = mPermissionGroups.size();
2834            ArrayList<PermissionGroupInfo> out
2835                    = new ArrayList<PermissionGroupInfo>(N);
2836            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2837                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2838            }
2839            return out;
2840        }
2841    }
2842
2843    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2844            int userId) {
2845        if (!sUserManager.exists(userId)) return null;
2846        PackageSetting ps = mSettings.mPackages.get(packageName);
2847        if (ps != null) {
2848            if (ps.pkg == null) {
2849                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2850                        flags, userId);
2851                if (pInfo != null) {
2852                    return pInfo.applicationInfo;
2853                }
2854                return null;
2855            }
2856            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2857                    ps.readUserState(userId), userId);
2858        }
2859        return null;
2860    }
2861
2862    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2863            int userId) {
2864        if (!sUserManager.exists(userId)) return null;
2865        PackageSetting ps = mSettings.mPackages.get(packageName);
2866        if (ps != null) {
2867            PackageParser.Package pkg = ps.pkg;
2868            if (pkg == null) {
2869                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2870                    return null;
2871                }
2872                // Only data remains, so we aren't worried about code paths
2873                pkg = new PackageParser.Package(packageName);
2874                pkg.applicationInfo.packageName = packageName;
2875                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2876                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2877                pkg.applicationInfo.uid = ps.appId;
2878                pkg.applicationInfo.initForUser(userId);
2879                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2880                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2881            }
2882            return generatePackageInfo(pkg, flags, userId);
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2889        if (!sUserManager.exists(userId)) return null;
2890        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2891        // writer
2892        synchronized (mPackages) {
2893            PackageParser.Package p = mPackages.get(packageName);
2894            if (DEBUG_PACKAGE_INFO) Log.v(
2895                    TAG, "getApplicationInfo " + packageName
2896                    + ": " + p);
2897            if (p != null) {
2898                PackageSetting ps = mSettings.mPackages.get(packageName);
2899                if (ps == null) return null;
2900                // Note: isEnabledLP() does not apply here - always return info
2901                return PackageParser.generateApplicationInfo(
2902                        p, flags, ps.readUserState(userId), userId);
2903            }
2904            if ("android".equals(packageName)||"system".equals(packageName)) {
2905                return mAndroidApplication;
2906            }
2907            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2908                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2909            }
2910        }
2911        return null;
2912    }
2913
2914    @Override
2915    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2916            final IPackageDataObserver observer) {
2917        mContext.enforceCallingOrSelfPermission(
2918                android.Manifest.permission.CLEAR_APP_CACHE, null);
2919        // Queue up an async operation since clearing cache may take a little while.
2920        mHandler.post(new Runnable() {
2921            public void run() {
2922                mHandler.removeCallbacks(this);
2923                int retCode = -1;
2924                synchronized (mInstallLock) {
2925                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2926                    if (retCode < 0) {
2927                        Slog.w(TAG, "Couldn't clear application caches");
2928                    }
2929                }
2930                if (observer != null) {
2931                    try {
2932                        observer.onRemoveCompleted(null, (retCode >= 0));
2933                    } catch (RemoteException e) {
2934                        Slog.w(TAG, "RemoveException when invoking call back");
2935                    }
2936                }
2937            }
2938        });
2939    }
2940
2941    @Override
2942    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2943            final IntentSender pi) {
2944        mContext.enforceCallingOrSelfPermission(
2945                android.Manifest.permission.CLEAR_APP_CACHE, null);
2946        // Queue up an async operation since clearing cache may take a little while.
2947        mHandler.post(new Runnable() {
2948            public void run() {
2949                mHandler.removeCallbacks(this);
2950                int retCode = -1;
2951                synchronized (mInstallLock) {
2952                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2953                    if (retCode < 0) {
2954                        Slog.w(TAG, "Couldn't clear application caches");
2955                    }
2956                }
2957                if(pi != null) {
2958                    try {
2959                        // Callback via pending intent
2960                        int code = (retCode >= 0) ? 1 : 0;
2961                        pi.sendIntent(null, code, null,
2962                                null, null);
2963                    } catch (SendIntentException e1) {
2964                        Slog.i(TAG, "Failed to send pending intent");
2965                    }
2966                }
2967            }
2968        });
2969    }
2970
2971    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2972        synchronized (mInstallLock) {
2973            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2974                throw new IOException("Failed to free enough space");
2975            }
2976        }
2977    }
2978
2979    /**
2980     * Augment the given flags depending on current user running state. This is
2981     * purposefully done before acquiring {@link #mPackages} lock.
2982     */
2983    private int augmentFlagsForUser(int flags, int userId) {
2984        if (SystemProperties.getBoolean(StorageManager.PROP_HAS_FBE, false)) {
2985            final IMountService mount = IMountService.Stub
2986                    .asInterface(ServiceManager.getService(Context.STORAGE_SERVICE));
2987            if (mount == null) {
2988                // We must be early in boot, so the best we can do is assume the
2989                // user is fully running.
2990                return flags;
2991            }
2992            final long token = Binder.clearCallingIdentity();
2993            try {
2994                if (!mount.isUserKeyUnlocked(userId)) {
2995                    flags |= PackageManager.FLAG_USER_RUNNING_WITH_AMNESIA;
2996                }
2997            } catch (RemoteException e) {
2998                throw e.rethrowAsRuntimeException();
2999            } finally {
3000                Binder.restoreCallingIdentity(token);
3001            }
3002        }
3003        return flags;
3004    }
3005
3006    @Override
3007    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        flags = augmentFlagsForUser(flags, userId);
3010        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3011        synchronized (mPackages) {
3012            PackageParser.Activity a = mActivities.mActivities.get(component);
3013
3014            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3015            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3016                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3017                if (ps == null) return null;
3018                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3019                        userId);
3020            }
3021            if (mResolveComponentName.equals(component)) {
3022                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3023                        new PackageUserState(), userId);
3024            }
3025        }
3026        return null;
3027    }
3028
3029    @Override
3030    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3031            String resolvedType) {
3032        synchronized (mPackages) {
3033            if (component.equals(mResolveComponentName)) {
3034                // The resolver supports EVERYTHING!
3035                return true;
3036            }
3037            PackageParser.Activity a = mActivities.mActivities.get(component);
3038            if (a == null) {
3039                return false;
3040            }
3041            for (int i=0; i<a.intents.size(); i++) {
3042                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3043                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3044                    return true;
3045                }
3046            }
3047            return false;
3048        }
3049    }
3050
3051    @Override
3052    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3053        if (!sUserManager.exists(userId)) return null;
3054        flags = augmentFlagsForUser(flags, userId);
3055        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3056        synchronized (mPackages) {
3057            PackageParser.Activity a = mReceivers.mActivities.get(component);
3058            if (DEBUG_PACKAGE_INFO) Log.v(
3059                TAG, "getReceiverInfo " + component + ": " + a);
3060            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3061                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3062                if (ps == null) return null;
3063                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3064                        userId);
3065            }
3066        }
3067        return null;
3068    }
3069
3070    @Override
3071    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3072        if (!sUserManager.exists(userId)) return null;
3073        flags = augmentFlagsForUser(flags, userId);
3074        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3075        synchronized (mPackages) {
3076            PackageParser.Service s = mServices.mServices.get(component);
3077            if (DEBUG_PACKAGE_INFO) Log.v(
3078                TAG, "getServiceInfo " + component + ": " + s);
3079            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3080                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3081                if (ps == null) return null;
3082                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3083                        userId);
3084            }
3085        }
3086        return null;
3087    }
3088
3089    @Override
3090    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3091        if (!sUserManager.exists(userId)) return null;
3092        flags = augmentFlagsForUser(flags, userId);
3093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3094        synchronized (mPackages) {
3095            PackageParser.Provider p = mProviders.mProviders.get(component);
3096            if (DEBUG_PACKAGE_INFO) Log.v(
3097                TAG, "getProviderInfo " + component + ": " + p);
3098            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3099                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3100                if (ps == null) return null;
3101                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3102                        userId);
3103            }
3104        }
3105        return null;
3106    }
3107
3108    @Override
3109    public String[] getSystemSharedLibraryNames() {
3110        Set<String> libSet;
3111        synchronized (mPackages) {
3112            libSet = mSharedLibraries.keySet();
3113            int size = libSet.size();
3114            if (size > 0) {
3115                String[] libs = new String[size];
3116                libSet.toArray(libs);
3117                return libs;
3118            }
3119        }
3120        return null;
3121    }
3122
3123    /**
3124     * @hide
3125     */
3126    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3127        synchronized (mPackages) {
3128            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3129            if (lib != null && lib.apk != null) {
3130                return mPackages.get(lib.apk);
3131            }
3132        }
3133        return null;
3134    }
3135
3136    @Override
3137    public FeatureInfo[] getSystemAvailableFeatures() {
3138        Collection<FeatureInfo> featSet;
3139        synchronized (mPackages) {
3140            featSet = mAvailableFeatures.values();
3141            int size = featSet.size();
3142            if (size > 0) {
3143                FeatureInfo[] features = new FeatureInfo[size+1];
3144                featSet.toArray(features);
3145                FeatureInfo fi = new FeatureInfo();
3146                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3147                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3148                features[size] = fi;
3149                return features;
3150            }
3151        }
3152        return null;
3153    }
3154
3155    @Override
3156    public boolean hasSystemFeature(String name) {
3157        synchronized (mPackages) {
3158            return mAvailableFeatures.containsKey(name);
3159        }
3160    }
3161
3162    private void checkValidCaller(int uid, int userId) {
3163        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3164            return;
3165
3166        throw new SecurityException("Caller uid=" + uid
3167                + " is not privileged to communicate with user=" + userId);
3168    }
3169
3170    @Override
3171    public int checkPermission(String permName, String pkgName, int userId) {
3172        if (!sUserManager.exists(userId)) {
3173            return PackageManager.PERMISSION_DENIED;
3174        }
3175
3176        synchronized (mPackages) {
3177            final PackageParser.Package p = mPackages.get(pkgName);
3178            if (p != null && p.mExtras != null) {
3179                final PackageSetting ps = (PackageSetting) p.mExtras;
3180                final PermissionsState permissionsState = ps.getPermissionsState();
3181                if (permissionsState.hasPermission(permName, userId)) {
3182                    return PackageManager.PERMISSION_GRANTED;
3183                }
3184                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3185                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3186                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3187                    return PackageManager.PERMISSION_GRANTED;
3188                }
3189            }
3190        }
3191
3192        return PackageManager.PERMISSION_DENIED;
3193    }
3194
3195    @Override
3196    public int checkUidPermission(String permName, int uid) {
3197        final int userId = UserHandle.getUserId(uid);
3198
3199        if (!sUserManager.exists(userId)) {
3200            return PackageManager.PERMISSION_DENIED;
3201        }
3202
3203        synchronized (mPackages) {
3204            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3205            if (obj != null) {
3206                final SettingBase ps = (SettingBase) obj;
3207                final PermissionsState permissionsState = ps.getPermissionsState();
3208                if (permissionsState.hasPermission(permName, userId)) {
3209                    return PackageManager.PERMISSION_GRANTED;
3210                }
3211                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3212                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3213                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3214                    return PackageManager.PERMISSION_GRANTED;
3215                }
3216            } else {
3217                ArraySet<String> perms = mSystemPermissions.get(uid);
3218                if (perms != null) {
3219                    if (perms.contains(permName)) {
3220                        return PackageManager.PERMISSION_GRANTED;
3221                    }
3222                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3223                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3224                        return PackageManager.PERMISSION_GRANTED;
3225                    }
3226                }
3227            }
3228        }
3229
3230        return PackageManager.PERMISSION_DENIED;
3231    }
3232
3233    @Override
3234    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3235        if (UserHandle.getCallingUserId() != userId) {
3236            mContext.enforceCallingPermission(
3237                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3238                    "isPermissionRevokedByPolicy for user " + userId);
3239        }
3240
3241        if (checkPermission(permission, packageName, userId)
3242                == PackageManager.PERMISSION_GRANTED) {
3243            return false;
3244        }
3245
3246        final long identity = Binder.clearCallingIdentity();
3247        try {
3248            final int flags = getPermissionFlags(permission, packageName, userId);
3249            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3250        } finally {
3251            Binder.restoreCallingIdentity(identity);
3252        }
3253    }
3254
3255    @Override
3256    public String getPermissionControllerPackageName() {
3257        synchronized (mPackages) {
3258            return mRequiredInstallerPackage;
3259        }
3260    }
3261
3262    /**
3263     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3264     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3265     * @param checkShell TODO(yamasani):
3266     * @param message the message to log on security exception
3267     */
3268    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3269            boolean checkShell, String message) {
3270        if (userId < 0) {
3271            throw new IllegalArgumentException("Invalid userId " + userId);
3272        }
3273        if (checkShell) {
3274            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3275        }
3276        if (userId == UserHandle.getUserId(callingUid)) return;
3277        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3278            if (requireFullPermission) {
3279                mContext.enforceCallingOrSelfPermission(
3280                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3281            } else {
3282                try {
3283                    mContext.enforceCallingOrSelfPermission(
3284                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3285                } catch (SecurityException se) {
3286                    mContext.enforceCallingOrSelfPermission(
3287                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3288                }
3289            }
3290        }
3291    }
3292
3293    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3294        if (callingUid == Process.SHELL_UID) {
3295            if (userHandle >= 0
3296                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3297                throw new SecurityException("Shell does not have permission to access user "
3298                        + userHandle);
3299            } else if (userHandle < 0) {
3300                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3301                        + Debug.getCallers(3));
3302            }
3303        }
3304    }
3305
3306    private BasePermission findPermissionTreeLP(String permName) {
3307        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3308            if (permName.startsWith(bp.name) &&
3309                    permName.length() > bp.name.length() &&
3310                    permName.charAt(bp.name.length()) == '.') {
3311                return bp;
3312            }
3313        }
3314        return null;
3315    }
3316
3317    private BasePermission checkPermissionTreeLP(String permName) {
3318        if (permName != null) {
3319            BasePermission bp = findPermissionTreeLP(permName);
3320            if (bp != null) {
3321                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3322                    return bp;
3323                }
3324                throw new SecurityException("Calling uid "
3325                        + Binder.getCallingUid()
3326                        + " is not allowed to add to permission tree "
3327                        + bp.name + " owned by uid " + bp.uid);
3328            }
3329        }
3330        throw new SecurityException("No permission tree found for " + permName);
3331    }
3332
3333    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3334        if (s1 == null) {
3335            return s2 == null;
3336        }
3337        if (s2 == null) {
3338            return false;
3339        }
3340        if (s1.getClass() != s2.getClass()) {
3341            return false;
3342        }
3343        return s1.equals(s2);
3344    }
3345
3346    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3347        if (pi1.icon != pi2.icon) return false;
3348        if (pi1.logo != pi2.logo) return false;
3349        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3350        if (!compareStrings(pi1.name, pi2.name)) return false;
3351        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3352        // We'll take care of setting this one.
3353        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3354        // These are not currently stored in settings.
3355        //if (!compareStrings(pi1.group, pi2.group)) return false;
3356        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3357        //if (pi1.labelRes != pi2.labelRes) return false;
3358        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3359        return true;
3360    }
3361
3362    int permissionInfoFootprint(PermissionInfo info) {
3363        int size = info.name.length();
3364        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3365        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3366        return size;
3367    }
3368
3369    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3370        int size = 0;
3371        for (BasePermission perm : mSettings.mPermissions.values()) {
3372            if (perm.uid == tree.uid) {
3373                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3374            }
3375        }
3376        return size;
3377    }
3378
3379    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3380        // We calculate the max size of permissions defined by this uid and throw
3381        // if that plus the size of 'info' would exceed our stated maximum.
3382        if (tree.uid != Process.SYSTEM_UID) {
3383            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3384            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3385                throw new SecurityException("Permission tree size cap exceeded");
3386            }
3387        }
3388    }
3389
3390    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3391        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3392            throw new SecurityException("Label must be specified in permission");
3393        }
3394        BasePermission tree = checkPermissionTreeLP(info.name);
3395        BasePermission bp = mSettings.mPermissions.get(info.name);
3396        boolean added = bp == null;
3397        boolean changed = true;
3398        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3399        if (added) {
3400            enforcePermissionCapLocked(info, tree);
3401            bp = new BasePermission(info.name, tree.sourcePackage,
3402                    BasePermission.TYPE_DYNAMIC);
3403        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3404            throw new SecurityException(
3405                    "Not allowed to modify non-dynamic permission "
3406                    + info.name);
3407        } else {
3408            if (bp.protectionLevel == fixedLevel
3409                    && bp.perm.owner.equals(tree.perm.owner)
3410                    && bp.uid == tree.uid
3411                    && comparePermissionInfos(bp.perm.info, info)) {
3412                changed = false;
3413            }
3414        }
3415        bp.protectionLevel = fixedLevel;
3416        info = new PermissionInfo(info);
3417        info.protectionLevel = fixedLevel;
3418        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3419        bp.perm.info.packageName = tree.perm.info.packageName;
3420        bp.uid = tree.uid;
3421        if (added) {
3422            mSettings.mPermissions.put(info.name, bp);
3423        }
3424        if (changed) {
3425            if (!async) {
3426                mSettings.writeLPr();
3427            } else {
3428                scheduleWriteSettingsLocked();
3429            }
3430        }
3431        return added;
3432    }
3433
3434    @Override
3435    public boolean addPermission(PermissionInfo info) {
3436        synchronized (mPackages) {
3437            return addPermissionLocked(info, false);
3438        }
3439    }
3440
3441    @Override
3442    public boolean addPermissionAsync(PermissionInfo info) {
3443        synchronized (mPackages) {
3444            return addPermissionLocked(info, true);
3445        }
3446    }
3447
3448    @Override
3449    public void removePermission(String name) {
3450        synchronized (mPackages) {
3451            checkPermissionTreeLP(name);
3452            BasePermission bp = mSettings.mPermissions.get(name);
3453            if (bp != null) {
3454                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3455                    throw new SecurityException(
3456                            "Not allowed to modify non-dynamic permission "
3457                            + name);
3458                }
3459                mSettings.mPermissions.remove(name);
3460                mSettings.writeLPr();
3461            }
3462        }
3463    }
3464
3465    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3466            BasePermission bp) {
3467        int index = pkg.requestedPermissions.indexOf(bp.name);
3468        if (index == -1) {
3469            throw new SecurityException("Package " + pkg.packageName
3470                    + " has not requested permission " + bp.name);
3471        }
3472        if (!bp.isRuntime() && !bp.isDevelopment()) {
3473            throw new SecurityException("Permission " + bp.name
3474                    + " is not a changeable permission type");
3475        }
3476    }
3477
3478    @Override
3479    public void grantRuntimePermission(String packageName, String name, final int userId) {
3480        if (!sUserManager.exists(userId)) {
3481            Log.e(TAG, "No such user:" + userId);
3482            return;
3483        }
3484
3485        mContext.enforceCallingOrSelfPermission(
3486                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3487                "grantRuntimePermission");
3488
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3490                "grantRuntimePermission");
3491
3492        final int uid;
3493        final SettingBase sb;
3494
3495        synchronized (mPackages) {
3496            final PackageParser.Package pkg = mPackages.get(packageName);
3497            if (pkg == null) {
3498                throw new IllegalArgumentException("Unknown package: " + packageName);
3499            }
3500
3501            final BasePermission bp = mSettings.mPermissions.get(name);
3502            if (bp == null) {
3503                throw new IllegalArgumentException("Unknown permission: " + name);
3504            }
3505
3506            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3507
3508            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3509            sb = (SettingBase) pkg.mExtras;
3510            if (sb == null) {
3511                throw new IllegalArgumentException("Unknown package: " + packageName);
3512            }
3513
3514            final PermissionsState permissionsState = sb.getPermissionsState();
3515
3516            final int flags = permissionsState.getPermissionFlags(name, userId);
3517            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3518                throw new SecurityException("Cannot grant system fixed permission: "
3519                        + name + " for package: " + packageName);
3520            }
3521
3522            if (bp.isDevelopment()) {
3523                // Development permissions must be handled specially, since they are not
3524                // normal runtime permissions.  For now they apply to all users.
3525                if (permissionsState.grantInstallPermission(bp) !=
3526                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3527                    scheduleWriteSettingsLocked();
3528                }
3529                return;
3530            }
3531
3532            final int result = permissionsState.grantRuntimePermission(bp, userId);
3533            switch (result) {
3534                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3535                    return;
3536                }
3537
3538                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3539                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3540                    mHandler.post(new Runnable() {
3541                        @Override
3542                        public void run() {
3543                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3544                        }
3545                    });
3546                }
3547                break;
3548            }
3549
3550            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3551
3552            // Not critical if that is lost - app has to request again.
3553            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3554        }
3555
3556        // Only need to do this if user is initialized. Otherwise it's a new user
3557        // and there are no processes running as the user yet and there's no need
3558        // to make an expensive call to remount processes for the changed permissions.
3559        if (READ_EXTERNAL_STORAGE.equals(name)
3560                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3561            final long token = Binder.clearCallingIdentity();
3562            try {
3563                if (sUserManager.isInitialized(userId)) {
3564                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3565                            MountServiceInternal.class);
3566                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3567                }
3568            } finally {
3569                Binder.restoreCallingIdentity(token);
3570            }
3571        }
3572    }
3573
3574    @Override
3575    public void revokeRuntimePermission(String packageName, String name, int userId) {
3576        if (!sUserManager.exists(userId)) {
3577            Log.e(TAG, "No such user:" + userId);
3578            return;
3579        }
3580
3581        mContext.enforceCallingOrSelfPermission(
3582                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3583                "revokeRuntimePermission");
3584
3585        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3586                "revokeRuntimePermission");
3587
3588        final int appId;
3589
3590        synchronized (mPackages) {
3591            final PackageParser.Package pkg = mPackages.get(packageName);
3592            if (pkg == null) {
3593                throw new IllegalArgumentException("Unknown package: " + packageName);
3594            }
3595
3596            final BasePermission bp = mSettings.mPermissions.get(name);
3597            if (bp == null) {
3598                throw new IllegalArgumentException("Unknown permission: " + name);
3599            }
3600
3601            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3602
3603            SettingBase sb = (SettingBase) pkg.mExtras;
3604            if (sb == null) {
3605                throw new IllegalArgumentException("Unknown package: " + packageName);
3606            }
3607
3608            final PermissionsState permissionsState = sb.getPermissionsState();
3609
3610            final int flags = permissionsState.getPermissionFlags(name, userId);
3611            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3612                throw new SecurityException("Cannot revoke system fixed permission: "
3613                        + name + " for package: " + packageName);
3614            }
3615
3616            if (bp.isDevelopment()) {
3617                // Development permissions must be handled specially, since they are not
3618                // normal runtime permissions.  For now they apply to all users.
3619                if (permissionsState.revokeInstallPermission(bp) !=
3620                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3621                    scheduleWriteSettingsLocked();
3622                }
3623                return;
3624            }
3625
3626            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3627                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3628                return;
3629            }
3630
3631            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3632
3633            // Critical, after this call app should never have the permission.
3634            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3635
3636            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3637        }
3638
3639        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3640    }
3641
3642    @Override
3643    public void resetRuntimePermissions() {
3644        mContext.enforceCallingOrSelfPermission(
3645                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3646                "revokeRuntimePermission");
3647
3648        int callingUid = Binder.getCallingUid();
3649        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3650            mContext.enforceCallingOrSelfPermission(
3651                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3652                    "resetRuntimePermissions");
3653        }
3654
3655        synchronized (mPackages) {
3656            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3657            for (int userId : UserManagerService.getInstance().getUserIds()) {
3658                final int packageCount = mPackages.size();
3659                for (int i = 0; i < packageCount; i++) {
3660                    PackageParser.Package pkg = mPackages.valueAt(i);
3661                    if (!(pkg.mExtras instanceof PackageSetting)) {
3662                        continue;
3663                    }
3664                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3665                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3666                }
3667            }
3668        }
3669    }
3670
3671    @Override
3672    public int getPermissionFlags(String name, String packageName, int userId) {
3673        if (!sUserManager.exists(userId)) {
3674            return 0;
3675        }
3676
3677        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3678
3679        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3680                "getPermissionFlags");
3681
3682        synchronized (mPackages) {
3683            final PackageParser.Package pkg = mPackages.get(packageName);
3684            if (pkg == null) {
3685                throw new IllegalArgumentException("Unknown package: " + packageName);
3686            }
3687
3688            final BasePermission bp = mSettings.mPermissions.get(name);
3689            if (bp == null) {
3690                throw new IllegalArgumentException("Unknown permission: " + name);
3691            }
3692
3693            SettingBase sb = (SettingBase) pkg.mExtras;
3694            if (sb == null) {
3695                throw new IllegalArgumentException("Unknown package: " + packageName);
3696            }
3697
3698            PermissionsState permissionsState = sb.getPermissionsState();
3699            return permissionsState.getPermissionFlags(name, userId);
3700        }
3701    }
3702
3703    @Override
3704    public void updatePermissionFlags(String name, String packageName, int flagMask,
3705            int flagValues, int userId) {
3706        if (!sUserManager.exists(userId)) {
3707            return;
3708        }
3709
3710        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3711
3712        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3713                "updatePermissionFlags");
3714
3715        // Only the system can change these flags and nothing else.
3716        if (getCallingUid() != Process.SYSTEM_UID) {
3717            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3718            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3719            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3720            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3721        }
3722
3723        synchronized (mPackages) {
3724            final PackageParser.Package pkg = mPackages.get(packageName);
3725            if (pkg == null) {
3726                throw new IllegalArgumentException("Unknown package: " + packageName);
3727            }
3728
3729            final BasePermission bp = mSettings.mPermissions.get(name);
3730            if (bp == null) {
3731                throw new IllegalArgumentException("Unknown permission: " + name);
3732            }
3733
3734            SettingBase sb = (SettingBase) pkg.mExtras;
3735            if (sb == null) {
3736                throw new IllegalArgumentException("Unknown package: " + packageName);
3737            }
3738
3739            PermissionsState permissionsState = sb.getPermissionsState();
3740
3741            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3742
3743            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3744                // Install and runtime permissions are stored in different places,
3745                // so figure out what permission changed and persist the change.
3746                if (permissionsState.getInstallPermissionState(name) != null) {
3747                    scheduleWriteSettingsLocked();
3748                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3749                        || hadState) {
3750                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3751                }
3752            }
3753        }
3754    }
3755
3756    /**
3757     * Update the permission flags for all packages and runtime permissions of a user in order
3758     * to allow device or profile owner to remove POLICY_FIXED.
3759     */
3760    @Override
3761    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3762        if (!sUserManager.exists(userId)) {
3763            return;
3764        }
3765
3766        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3767
3768        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3769                "updatePermissionFlagsForAllApps");
3770
3771        // Only the system can change system fixed flags.
3772        if (getCallingUid() != Process.SYSTEM_UID) {
3773            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3774            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3775        }
3776
3777        synchronized (mPackages) {
3778            boolean changed = false;
3779            final int packageCount = mPackages.size();
3780            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3781                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3782                SettingBase sb = (SettingBase) pkg.mExtras;
3783                if (sb == null) {
3784                    continue;
3785                }
3786                PermissionsState permissionsState = sb.getPermissionsState();
3787                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3788                        userId, flagMask, flagValues);
3789            }
3790            if (changed) {
3791                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3792            }
3793        }
3794    }
3795
3796    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3797        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3798                != PackageManager.PERMISSION_GRANTED
3799            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3800                != PackageManager.PERMISSION_GRANTED) {
3801            throw new SecurityException(message + " requires "
3802                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3803                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3804        }
3805    }
3806
3807    @Override
3808    public boolean shouldShowRequestPermissionRationale(String permissionName,
3809            String packageName, int userId) {
3810        if (UserHandle.getCallingUserId() != userId) {
3811            mContext.enforceCallingPermission(
3812                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3813                    "canShowRequestPermissionRationale for user " + userId);
3814        }
3815
3816        final int uid = getPackageUid(packageName, userId);
3817        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3818            return false;
3819        }
3820
3821        if (checkPermission(permissionName, packageName, userId)
3822                == PackageManager.PERMISSION_GRANTED) {
3823            return false;
3824        }
3825
3826        final int flags;
3827
3828        final long identity = Binder.clearCallingIdentity();
3829        try {
3830            flags = getPermissionFlags(permissionName,
3831                    packageName, userId);
3832        } finally {
3833            Binder.restoreCallingIdentity(identity);
3834        }
3835
3836        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3837                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3838                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3839
3840        if ((flags & fixedFlags) != 0) {
3841            return false;
3842        }
3843
3844        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3845    }
3846
3847    @Override
3848    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3849        mContext.enforceCallingOrSelfPermission(
3850                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3851                "addOnPermissionsChangeListener");
3852
3853        synchronized (mPackages) {
3854            mOnPermissionChangeListeners.addListenerLocked(listener);
3855        }
3856    }
3857
3858    @Override
3859    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3860        synchronized (mPackages) {
3861            mOnPermissionChangeListeners.removeListenerLocked(listener);
3862        }
3863    }
3864
3865    @Override
3866    public boolean isProtectedBroadcast(String actionName) {
3867        synchronized (mPackages) {
3868            return mProtectedBroadcasts.contains(actionName);
3869        }
3870    }
3871
3872    @Override
3873    public int checkSignatures(String pkg1, String pkg2) {
3874        synchronized (mPackages) {
3875            final PackageParser.Package p1 = mPackages.get(pkg1);
3876            final PackageParser.Package p2 = mPackages.get(pkg2);
3877            if (p1 == null || p1.mExtras == null
3878                    || p2 == null || p2.mExtras == null) {
3879                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3880            }
3881            return compareSignatures(p1.mSignatures, p2.mSignatures);
3882        }
3883    }
3884
3885    @Override
3886    public int checkUidSignatures(int uid1, int uid2) {
3887        // Map to base uids.
3888        uid1 = UserHandle.getAppId(uid1);
3889        uid2 = UserHandle.getAppId(uid2);
3890        // reader
3891        synchronized (mPackages) {
3892            Signature[] s1;
3893            Signature[] s2;
3894            Object obj = mSettings.getUserIdLPr(uid1);
3895            if (obj != null) {
3896                if (obj instanceof SharedUserSetting) {
3897                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3898                } else if (obj instanceof PackageSetting) {
3899                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3900                } else {
3901                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3902                }
3903            } else {
3904                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3905            }
3906            obj = mSettings.getUserIdLPr(uid2);
3907            if (obj != null) {
3908                if (obj instanceof SharedUserSetting) {
3909                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3910                } else if (obj instanceof PackageSetting) {
3911                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3912                } else {
3913                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3914                }
3915            } else {
3916                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3917            }
3918            return compareSignatures(s1, s2);
3919        }
3920    }
3921
3922    private void killUid(int appId, int userId, String reason) {
3923        final long identity = Binder.clearCallingIdentity();
3924        try {
3925            IActivityManager am = ActivityManagerNative.getDefault();
3926            if (am != null) {
3927                try {
3928                    am.killUid(appId, userId, reason);
3929                } catch (RemoteException e) {
3930                    /* ignore - same process */
3931                }
3932            }
3933        } finally {
3934            Binder.restoreCallingIdentity(identity);
3935        }
3936    }
3937
3938    /**
3939     * Compares two sets of signatures. Returns:
3940     * <br />
3941     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3942     * <br />
3943     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3944     * <br />
3945     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3946     * <br />
3947     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3948     * <br />
3949     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3950     */
3951    static int compareSignatures(Signature[] s1, Signature[] s2) {
3952        if (s1 == null) {
3953            return s2 == null
3954                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3955                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3956        }
3957
3958        if (s2 == null) {
3959            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3960        }
3961
3962        if (s1.length != s2.length) {
3963            return PackageManager.SIGNATURE_NO_MATCH;
3964        }
3965
3966        // Since both signature sets are of size 1, we can compare without HashSets.
3967        if (s1.length == 1) {
3968            return s1[0].equals(s2[0]) ?
3969                    PackageManager.SIGNATURE_MATCH :
3970                    PackageManager.SIGNATURE_NO_MATCH;
3971        }
3972
3973        ArraySet<Signature> set1 = new ArraySet<Signature>();
3974        for (Signature sig : s1) {
3975            set1.add(sig);
3976        }
3977        ArraySet<Signature> set2 = new ArraySet<Signature>();
3978        for (Signature sig : s2) {
3979            set2.add(sig);
3980        }
3981        // Make sure s2 contains all signatures in s1.
3982        if (set1.equals(set2)) {
3983            return PackageManager.SIGNATURE_MATCH;
3984        }
3985        return PackageManager.SIGNATURE_NO_MATCH;
3986    }
3987
3988    /**
3989     * If the database version for this type of package (internal storage or
3990     * external storage) is less than the version where package signatures
3991     * were updated, return true.
3992     */
3993    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3994        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3995        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3996    }
3997
3998    /**
3999     * Used for backward compatibility to make sure any packages with
4000     * certificate chains get upgraded to the new style. {@code existingSigs}
4001     * will be in the old format (since they were stored on disk from before the
4002     * system upgrade) and {@code scannedSigs} will be in the newer format.
4003     */
4004    private int compareSignaturesCompat(PackageSignatures existingSigs,
4005            PackageParser.Package scannedPkg) {
4006        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4007            return PackageManager.SIGNATURE_NO_MATCH;
4008        }
4009
4010        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4011        for (Signature sig : existingSigs.mSignatures) {
4012            existingSet.add(sig);
4013        }
4014        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4015        for (Signature sig : scannedPkg.mSignatures) {
4016            try {
4017                Signature[] chainSignatures = sig.getChainSignatures();
4018                for (Signature chainSig : chainSignatures) {
4019                    scannedCompatSet.add(chainSig);
4020                }
4021            } catch (CertificateEncodingException e) {
4022                scannedCompatSet.add(sig);
4023            }
4024        }
4025        /*
4026         * Make sure the expanded scanned set contains all signatures in the
4027         * existing one.
4028         */
4029        if (scannedCompatSet.equals(existingSet)) {
4030            // Migrate the old signatures to the new scheme.
4031            existingSigs.assignSignatures(scannedPkg.mSignatures);
4032            // The new KeySets will be re-added later in the scanning process.
4033            synchronized (mPackages) {
4034                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4035            }
4036            return PackageManager.SIGNATURE_MATCH;
4037        }
4038        return PackageManager.SIGNATURE_NO_MATCH;
4039    }
4040
4041    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4042        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4043        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4044    }
4045
4046    private int compareSignaturesRecover(PackageSignatures existingSigs,
4047            PackageParser.Package scannedPkg) {
4048        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4049            return PackageManager.SIGNATURE_NO_MATCH;
4050        }
4051
4052        String msg = null;
4053        try {
4054            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4055                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4056                        + scannedPkg.packageName);
4057                return PackageManager.SIGNATURE_MATCH;
4058            }
4059        } catch (CertificateException e) {
4060            msg = e.getMessage();
4061        }
4062
4063        logCriticalInfo(Log.INFO,
4064                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4065        return PackageManager.SIGNATURE_NO_MATCH;
4066    }
4067
4068    @Override
4069    public String[] getPackagesForUid(int uid) {
4070        uid = UserHandle.getAppId(uid);
4071        // reader
4072        synchronized (mPackages) {
4073            Object obj = mSettings.getUserIdLPr(uid);
4074            if (obj instanceof SharedUserSetting) {
4075                final SharedUserSetting sus = (SharedUserSetting) obj;
4076                final int N = sus.packages.size();
4077                final String[] res = new String[N];
4078                final Iterator<PackageSetting> it = sus.packages.iterator();
4079                int i = 0;
4080                while (it.hasNext()) {
4081                    res[i++] = it.next().name;
4082                }
4083                return res;
4084            } else if (obj instanceof PackageSetting) {
4085                final PackageSetting ps = (PackageSetting) obj;
4086                return new String[] { ps.name };
4087            }
4088        }
4089        return null;
4090    }
4091
4092    @Override
4093    public String getNameForUid(int uid) {
4094        // reader
4095        synchronized (mPackages) {
4096            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4097            if (obj instanceof SharedUserSetting) {
4098                final SharedUserSetting sus = (SharedUserSetting) obj;
4099                return sus.name + ":" + sus.userId;
4100            } else if (obj instanceof PackageSetting) {
4101                final PackageSetting ps = (PackageSetting) obj;
4102                return ps.name;
4103            }
4104        }
4105        return null;
4106    }
4107
4108    @Override
4109    public int getUidForSharedUser(String sharedUserName) {
4110        if(sharedUserName == null) {
4111            return -1;
4112        }
4113        // reader
4114        synchronized (mPackages) {
4115            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4116            if (suid == null) {
4117                return -1;
4118            }
4119            return suid.userId;
4120        }
4121    }
4122
4123    @Override
4124    public int getFlagsForUid(int uid) {
4125        synchronized (mPackages) {
4126            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4127            if (obj instanceof SharedUserSetting) {
4128                final SharedUserSetting sus = (SharedUserSetting) obj;
4129                return sus.pkgFlags;
4130            } else if (obj instanceof PackageSetting) {
4131                final PackageSetting ps = (PackageSetting) obj;
4132                return ps.pkgFlags;
4133            }
4134        }
4135        return 0;
4136    }
4137
4138    @Override
4139    public int getPrivateFlagsForUid(int uid) {
4140        synchronized (mPackages) {
4141            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4142            if (obj instanceof SharedUserSetting) {
4143                final SharedUserSetting sus = (SharedUserSetting) obj;
4144                return sus.pkgPrivateFlags;
4145            } else if (obj instanceof PackageSetting) {
4146                final PackageSetting ps = (PackageSetting) obj;
4147                return ps.pkgPrivateFlags;
4148            }
4149        }
4150        return 0;
4151    }
4152
4153    @Override
4154    public boolean isUidPrivileged(int uid) {
4155        uid = UserHandle.getAppId(uid);
4156        // reader
4157        synchronized (mPackages) {
4158            Object obj = mSettings.getUserIdLPr(uid);
4159            if (obj instanceof SharedUserSetting) {
4160                final SharedUserSetting sus = (SharedUserSetting) obj;
4161                final Iterator<PackageSetting> it = sus.packages.iterator();
4162                while (it.hasNext()) {
4163                    if (it.next().isPrivileged()) {
4164                        return true;
4165                    }
4166                }
4167            } else if (obj instanceof PackageSetting) {
4168                final PackageSetting ps = (PackageSetting) obj;
4169                return ps.isPrivileged();
4170            }
4171        }
4172        return false;
4173    }
4174
4175    @Override
4176    public String[] getAppOpPermissionPackages(String permissionName) {
4177        synchronized (mPackages) {
4178            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4179            if (pkgs == null) {
4180                return null;
4181            }
4182            return pkgs.toArray(new String[pkgs.size()]);
4183        }
4184    }
4185
4186    @Override
4187    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4188            int flags, int userId) {
4189        if (!sUserManager.exists(userId)) return null;
4190        flags = augmentFlagsForUser(flags, userId);
4191        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4192        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4193        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4194    }
4195
4196    @Override
4197    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4198            IntentFilter filter, int match, ComponentName activity) {
4199        final int userId = UserHandle.getCallingUserId();
4200        if (DEBUG_PREFERRED) {
4201            Log.v(TAG, "setLastChosenActivity intent=" + intent
4202                + " resolvedType=" + resolvedType
4203                + " flags=" + flags
4204                + " filter=" + filter
4205                + " match=" + match
4206                + " activity=" + activity);
4207            filter.dump(new PrintStreamPrinter(System.out), "    ");
4208        }
4209        intent.setComponent(null);
4210        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4211        // Find any earlier preferred or last chosen entries and nuke them
4212        findPreferredActivity(intent, resolvedType,
4213                flags, query, 0, false, true, false, userId);
4214        // Add the new activity as the last chosen for this filter
4215        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4216                "Setting last chosen");
4217    }
4218
4219    @Override
4220    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4221        final int userId = UserHandle.getCallingUserId();
4222        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4223        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4224        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4225                false, false, false, userId);
4226    }
4227
4228    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4229            int flags, List<ResolveInfo> query, int userId) {
4230        if (query != null) {
4231            final int N = query.size();
4232            if (N == 1) {
4233                return query.get(0);
4234            } else if (N > 1) {
4235                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4236                // If there is more than one activity with the same priority,
4237                // then let the user decide between them.
4238                ResolveInfo r0 = query.get(0);
4239                ResolveInfo r1 = query.get(1);
4240                if (DEBUG_INTENT_MATCHING || debug) {
4241                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4242                            + r1.activityInfo.name + "=" + r1.priority);
4243                }
4244                // If the first activity has a higher priority, or a different
4245                // default, then it is always desireable to pick it.
4246                if (r0.priority != r1.priority
4247                        || r0.preferredOrder != r1.preferredOrder
4248                        || r0.isDefault != r1.isDefault) {
4249                    return query.get(0);
4250                }
4251                // If we have saved a preference for a preferred activity for
4252                // this Intent, use that.
4253                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4254                        flags, query, r0.priority, true, false, debug, userId);
4255                if (ri != null) {
4256                    return ri;
4257                }
4258                ri = new ResolveInfo(mResolveInfo);
4259                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4260                ri.activityInfo.applicationInfo = new ApplicationInfo(
4261                        ri.activityInfo.applicationInfo);
4262                if (userId != 0) {
4263                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4264                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4265                }
4266                // Make sure that the resolver is displayable in car mode
4267                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4268                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4269                return ri;
4270            }
4271        }
4272        return null;
4273    }
4274
4275    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4276            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4277        final int N = query.size();
4278        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4279                .get(userId);
4280        // Get the list of persistent preferred activities that handle the intent
4281        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4282        List<PersistentPreferredActivity> pprefs = ppir != null
4283                ? ppir.queryIntent(intent, resolvedType,
4284                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4285                : null;
4286        if (pprefs != null && pprefs.size() > 0) {
4287            final int M = pprefs.size();
4288            for (int i=0; i<M; i++) {
4289                final PersistentPreferredActivity ppa = pprefs.get(i);
4290                if (DEBUG_PREFERRED || debug) {
4291                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4292                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4293                            + "\n  component=" + ppa.mComponent);
4294                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4295                }
4296                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4297                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4298                if (DEBUG_PREFERRED || debug) {
4299                    Slog.v(TAG, "Found persistent preferred activity:");
4300                    if (ai != null) {
4301                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4302                    } else {
4303                        Slog.v(TAG, "  null");
4304                    }
4305                }
4306                if (ai == null) {
4307                    // This previously registered persistent preferred activity
4308                    // component is no longer known. Ignore it and do NOT remove it.
4309                    continue;
4310                }
4311                for (int j=0; j<N; j++) {
4312                    final ResolveInfo ri = query.get(j);
4313                    if (!ri.activityInfo.applicationInfo.packageName
4314                            .equals(ai.applicationInfo.packageName)) {
4315                        continue;
4316                    }
4317                    if (!ri.activityInfo.name.equals(ai.name)) {
4318                        continue;
4319                    }
4320                    //  Found a persistent preference that can handle the intent.
4321                    if (DEBUG_PREFERRED || debug) {
4322                        Slog.v(TAG, "Returning persistent preferred activity: " +
4323                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4324                    }
4325                    return ri;
4326                }
4327            }
4328        }
4329        return null;
4330    }
4331
4332    // TODO: handle preferred activities missing while user has amnesia
4333    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4334            List<ResolveInfo> query, int priority, boolean always,
4335            boolean removeMatches, boolean debug, int userId) {
4336        if (!sUserManager.exists(userId)) return null;
4337        flags = augmentFlagsForUser(flags, userId);
4338        // writer
4339        synchronized (mPackages) {
4340            if (intent.getSelector() != null) {
4341                intent = intent.getSelector();
4342            }
4343            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4344
4345            // Try to find a matching persistent preferred activity.
4346            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4347                    debug, userId);
4348
4349            // If a persistent preferred activity matched, use it.
4350            if (pri != null) {
4351                return pri;
4352            }
4353
4354            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4355            // Get the list of preferred activities that handle the intent
4356            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4357            List<PreferredActivity> prefs = pir != null
4358                    ? pir.queryIntent(intent, resolvedType,
4359                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4360                    : null;
4361            if (prefs != null && prefs.size() > 0) {
4362                boolean changed = false;
4363                try {
4364                    // First figure out how good the original match set is.
4365                    // We will only allow preferred activities that came
4366                    // from the same match quality.
4367                    int match = 0;
4368
4369                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4370
4371                    final int N = query.size();
4372                    for (int j=0; j<N; j++) {
4373                        final ResolveInfo ri = query.get(j);
4374                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4375                                + ": 0x" + Integer.toHexString(match));
4376                        if (ri.match > match) {
4377                            match = ri.match;
4378                        }
4379                    }
4380
4381                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4382                            + Integer.toHexString(match));
4383
4384                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4385                    final int M = prefs.size();
4386                    for (int i=0; i<M; i++) {
4387                        final PreferredActivity pa = prefs.get(i);
4388                        if (DEBUG_PREFERRED || debug) {
4389                            Slog.v(TAG, "Checking PreferredActivity ds="
4390                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4391                                    + "\n  component=" + pa.mPref.mComponent);
4392                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4393                        }
4394                        if (pa.mPref.mMatch != match) {
4395                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4396                                    + Integer.toHexString(pa.mPref.mMatch));
4397                            continue;
4398                        }
4399                        // If it's not an "always" type preferred activity and that's what we're
4400                        // looking for, skip it.
4401                        if (always && !pa.mPref.mAlways) {
4402                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4403                            continue;
4404                        }
4405                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4406                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4407                        if (DEBUG_PREFERRED || debug) {
4408                            Slog.v(TAG, "Found preferred activity:");
4409                            if (ai != null) {
4410                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4411                            } else {
4412                                Slog.v(TAG, "  null");
4413                            }
4414                        }
4415                        if (ai == null) {
4416                            // This previously registered preferred activity
4417                            // component is no longer known.  Most likely an update
4418                            // to the app was installed and in the new version this
4419                            // component no longer exists.  Clean it up by removing
4420                            // it from the preferred activities list, and skip it.
4421                            Slog.w(TAG, "Removing dangling preferred activity: "
4422                                    + pa.mPref.mComponent);
4423                            pir.removeFilter(pa);
4424                            changed = true;
4425                            continue;
4426                        }
4427                        for (int j=0; j<N; j++) {
4428                            final ResolveInfo ri = query.get(j);
4429                            if (!ri.activityInfo.applicationInfo.packageName
4430                                    .equals(ai.applicationInfo.packageName)) {
4431                                continue;
4432                            }
4433                            if (!ri.activityInfo.name.equals(ai.name)) {
4434                                continue;
4435                            }
4436
4437                            if (removeMatches) {
4438                                pir.removeFilter(pa);
4439                                changed = true;
4440                                if (DEBUG_PREFERRED) {
4441                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4442                                }
4443                                break;
4444                            }
4445
4446                            // Okay we found a previously set preferred or last chosen app.
4447                            // If the result set is different from when this
4448                            // was created, we need to clear it and re-ask the
4449                            // user their preference, if we're looking for an "always" type entry.
4450                            if (always && !pa.mPref.sameSet(query)) {
4451                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4452                                        + intent + " type " + resolvedType);
4453                                if (DEBUG_PREFERRED) {
4454                                    Slog.v(TAG, "Removing preferred activity since set changed "
4455                                            + pa.mPref.mComponent);
4456                                }
4457                                pir.removeFilter(pa);
4458                                // Re-add the filter as a "last chosen" entry (!always)
4459                                PreferredActivity lastChosen = new PreferredActivity(
4460                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4461                                pir.addFilter(lastChosen);
4462                                changed = true;
4463                                return null;
4464                            }
4465
4466                            // Yay! Either the set matched or we're looking for the last chosen
4467                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4468                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4469                            return ri;
4470                        }
4471                    }
4472                } finally {
4473                    if (changed) {
4474                        if (DEBUG_PREFERRED) {
4475                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4476                        }
4477                        scheduleWritePackageRestrictionsLocked(userId);
4478                    }
4479                }
4480            }
4481        }
4482        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4483        return null;
4484    }
4485
4486    /*
4487     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4488     */
4489    @Override
4490    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4491            int targetUserId) {
4492        mContext.enforceCallingOrSelfPermission(
4493                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4494        List<CrossProfileIntentFilter> matches =
4495                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4496        if (matches != null) {
4497            int size = matches.size();
4498            for (int i = 0; i < size; i++) {
4499                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4500            }
4501        }
4502        if (hasWebURI(intent)) {
4503            // cross-profile app linking works only towards the parent.
4504            final UserInfo parent = getProfileParent(sourceUserId);
4505            synchronized(mPackages) {
4506                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4507                        intent, resolvedType, 0, sourceUserId, parent.id);
4508                return xpDomainInfo != null;
4509            }
4510        }
4511        return false;
4512    }
4513
4514    private UserInfo getProfileParent(int userId) {
4515        final long identity = Binder.clearCallingIdentity();
4516        try {
4517            return sUserManager.getProfileParent(userId);
4518        } finally {
4519            Binder.restoreCallingIdentity(identity);
4520        }
4521    }
4522
4523    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4524            String resolvedType, int userId) {
4525        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4526        if (resolver != null) {
4527            return resolver.queryIntent(intent, resolvedType, false, userId);
4528        }
4529        return null;
4530    }
4531
4532    @Override
4533    public List<ResolveInfo> queryIntentActivities(Intent intent,
4534            String resolvedType, int flags, int userId) {
4535        if (!sUserManager.exists(userId)) return Collections.emptyList();
4536        flags = augmentFlagsForUser(flags, userId);
4537        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4538        ComponentName comp = intent.getComponent();
4539        if (comp == null) {
4540            if (intent.getSelector() != null) {
4541                intent = intent.getSelector();
4542                comp = intent.getComponent();
4543            }
4544        }
4545
4546        if (comp != null) {
4547            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4548            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4549            if (ai != null) {
4550                final ResolveInfo ri = new ResolveInfo();
4551                ri.activityInfo = ai;
4552                list.add(ri);
4553            }
4554            return list;
4555        }
4556
4557        // reader
4558        synchronized (mPackages) {
4559            final String pkgName = intent.getPackage();
4560            if (pkgName == null) {
4561                List<CrossProfileIntentFilter> matchingFilters =
4562                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4563                // Check for results that need to skip the current profile.
4564                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4565                        resolvedType, flags, userId);
4566                if (xpResolveInfo != null) {
4567                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4568                    result.add(xpResolveInfo);
4569                    return filterIfNotSystemUser(result, userId);
4570                }
4571
4572                // Check for results in the current profile.
4573                List<ResolveInfo> result = mActivities.queryIntent(
4574                        intent, resolvedType, flags, userId);
4575
4576                // Check for cross profile results.
4577                xpResolveInfo = queryCrossProfileIntents(
4578                        matchingFilters, intent, resolvedType, flags, userId);
4579                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4580                    result.add(xpResolveInfo);
4581                    Collections.sort(result, mResolvePrioritySorter);
4582                }
4583                result = filterIfNotSystemUser(result, userId);
4584                if (hasWebURI(intent)) {
4585                    CrossProfileDomainInfo xpDomainInfo = null;
4586                    final UserInfo parent = getProfileParent(userId);
4587                    if (parent != null) {
4588                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4589                                flags, userId, parent.id);
4590                    }
4591                    if (xpDomainInfo != null) {
4592                        if (xpResolveInfo != null) {
4593                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4594                            // in the result.
4595                            result.remove(xpResolveInfo);
4596                        }
4597                        if (result.size() == 0) {
4598                            result.add(xpDomainInfo.resolveInfo);
4599                            return result;
4600                        }
4601                    } else if (result.size() <= 1) {
4602                        return result;
4603                    }
4604                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4605                            xpDomainInfo, userId);
4606                    Collections.sort(result, mResolvePrioritySorter);
4607                }
4608                return result;
4609            }
4610            final PackageParser.Package pkg = mPackages.get(pkgName);
4611            if (pkg != null) {
4612                return filterIfNotSystemUser(
4613                        mActivities.queryIntentForPackage(
4614                                intent, resolvedType, flags, pkg.activities, userId),
4615                        userId);
4616            }
4617            return new ArrayList<ResolveInfo>();
4618        }
4619    }
4620
4621    private static class CrossProfileDomainInfo {
4622        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4623        ResolveInfo resolveInfo;
4624        /* Best domain verification status of the activities found in the other profile */
4625        int bestDomainVerificationStatus;
4626    }
4627
4628    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4629            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4630        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4631                sourceUserId)) {
4632            return null;
4633        }
4634        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4635                resolvedType, flags, parentUserId);
4636
4637        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4638            return null;
4639        }
4640        CrossProfileDomainInfo result = null;
4641        int size = resultTargetUser.size();
4642        for (int i = 0; i < size; i++) {
4643            ResolveInfo riTargetUser = resultTargetUser.get(i);
4644            // Intent filter verification is only for filters that specify a host. So don't return
4645            // those that handle all web uris.
4646            if (riTargetUser.handleAllWebDataURI) {
4647                continue;
4648            }
4649            String packageName = riTargetUser.activityInfo.packageName;
4650            PackageSetting ps = mSettings.mPackages.get(packageName);
4651            if (ps == null) {
4652                continue;
4653            }
4654            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4655            int status = (int)(verificationState >> 32);
4656            if (result == null) {
4657                result = new CrossProfileDomainInfo();
4658                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4659                        sourceUserId, parentUserId);
4660                result.bestDomainVerificationStatus = status;
4661            } else {
4662                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4663                        result.bestDomainVerificationStatus);
4664            }
4665        }
4666        // Don't consider matches with status NEVER across profiles.
4667        if (result != null && result.bestDomainVerificationStatus
4668                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4669            return null;
4670        }
4671        return result;
4672    }
4673
4674    /**
4675     * Verification statuses are ordered from the worse to the best, except for
4676     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4677     */
4678    private int bestDomainVerificationStatus(int status1, int status2) {
4679        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4680            return status2;
4681        }
4682        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4683            return status1;
4684        }
4685        return (int) MathUtils.max(status1, status2);
4686    }
4687
4688    private boolean isUserEnabled(int userId) {
4689        long callingId = Binder.clearCallingIdentity();
4690        try {
4691            UserInfo userInfo = sUserManager.getUserInfo(userId);
4692            return userInfo != null && userInfo.isEnabled();
4693        } finally {
4694            Binder.restoreCallingIdentity(callingId);
4695        }
4696    }
4697
4698    /**
4699     * Filter out activities with systemUserOnly flag set, when current user is not System.
4700     *
4701     * @return filtered list
4702     */
4703    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4704        if (userId == UserHandle.USER_SYSTEM) {
4705            return resolveInfos;
4706        }
4707        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4708            ResolveInfo info = resolveInfos.get(i);
4709            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4710                resolveInfos.remove(i);
4711            }
4712        }
4713        return resolveInfos;
4714    }
4715
4716    private static boolean hasWebURI(Intent intent) {
4717        if (intent.getData() == null) {
4718            return false;
4719        }
4720        final String scheme = intent.getScheme();
4721        if (TextUtils.isEmpty(scheme)) {
4722            return false;
4723        }
4724        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4725    }
4726
4727    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4728            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4729            int userId) {
4730        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4731
4732        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4733            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4734                    candidates.size());
4735        }
4736
4737        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4738        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4739        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4740        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4741        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4742        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4743
4744        synchronized (mPackages) {
4745            final int count = candidates.size();
4746            // First, try to use linked apps. Partition the candidates into four lists:
4747            // one for the final results, one for the "do not use ever", one for "undefined status"
4748            // and finally one for "browser app type".
4749            for (int n=0; n<count; n++) {
4750                ResolveInfo info = candidates.get(n);
4751                String packageName = info.activityInfo.packageName;
4752                PackageSetting ps = mSettings.mPackages.get(packageName);
4753                if (ps != null) {
4754                    // Add to the special match all list (Browser use case)
4755                    if (info.handleAllWebDataURI) {
4756                        matchAllList.add(info);
4757                        continue;
4758                    }
4759                    // Try to get the status from User settings first
4760                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4761                    int status = (int)(packedStatus >> 32);
4762                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4763                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4764                        if (DEBUG_DOMAIN_VERIFICATION) {
4765                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4766                                    + " : linkgen=" + linkGeneration);
4767                        }
4768                        // Use link-enabled generation as preferredOrder, i.e.
4769                        // prefer newly-enabled over earlier-enabled.
4770                        info.preferredOrder = linkGeneration;
4771                        alwaysList.add(info);
4772                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4773                        if (DEBUG_DOMAIN_VERIFICATION) {
4774                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4775                        }
4776                        neverList.add(info);
4777                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4778                        if (DEBUG_DOMAIN_VERIFICATION) {
4779                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4780                        }
4781                        alwaysAskList.add(info);
4782                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4783                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4784                        if (DEBUG_DOMAIN_VERIFICATION) {
4785                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4786                        }
4787                        undefinedList.add(info);
4788                    }
4789                }
4790            }
4791
4792            // We'll want to include browser possibilities in a few cases
4793            boolean includeBrowser = false;
4794
4795            // First try to add the "always" resolution(s) for the current user, if any
4796            if (alwaysList.size() > 0) {
4797                result.addAll(alwaysList);
4798            } else {
4799                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4800                result.addAll(undefinedList);
4801                // Maybe add one for the other profile.
4802                if (xpDomainInfo != null && (
4803                        xpDomainInfo.bestDomainVerificationStatus
4804                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4805                    result.add(xpDomainInfo.resolveInfo);
4806                }
4807                includeBrowser = true;
4808            }
4809
4810            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4811            // If there were 'always' entries their preferred order has been set, so we also
4812            // back that off to make the alternatives equivalent
4813            if (alwaysAskList.size() > 0) {
4814                for (ResolveInfo i : result) {
4815                    i.preferredOrder = 0;
4816                }
4817                result.addAll(alwaysAskList);
4818                includeBrowser = true;
4819            }
4820
4821            if (includeBrowser) {
4822                // Also add browsers (all of them or only the default one)
4823                if (DEBUG_DOMAIN_VERIFICATION) {
4824                    Slog.v(TAG, "   ...including browsers in candidate set");
4825                }
4826                if ((matchFlags & MATCH_ALL) != 0) {
4827                    result.addAll(matchAllList);
4828                } else {
4829                    // Browser/generic handling case.  If there's a default browser, go straight
4830                    // to that (but only if there is no other higher-priority match).
4831                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4832                    int maxMatchPrio = 0;
4833                    ResolveInfo defaultBrowserMatch = null;
4834                    final int numCandidates = matchAllList.size();
4835                    for (int n = 0; n < numCandidates; n++) {
4836                        ResolveInfo info = matchAllList.get(n);
4837                        // track the highest overall match priority...
4838                        if (info.priority > maxMatchPrio) {
4839                            maxMatchPrio = info.priority;
4840                        }
4841                        // ...and the highest-priority default browser match
4842                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4843                            if (defaultBrowserMatch == null
4844                                    || (defaultBrowserMatch.priority < info.priority)) {
4845                                if (debug) {
4846                                    Slog.v(TAG, "Considering default browser match " + info);
4847                                }
4848                                defaultBrowserMatch = info;
4849                            }
4850                        }
4851                    }
4852                    if (defaultBrowserMatch != null
4853                            && defaultBrowserMatch.priority >= maxMatchPrio
4854                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4855                    {
4856                        if (debug) {
4857                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4858                        }
4859                        result.add(defaultBrowserMatch);
4860                    } else {
4861                        result.addAll(matchAllList);
4862                    }
4863                }
4864
4865                // If there is nothing selected, add all candidates and remove the ones that the user
4866                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4867                if (result.size() == 0) {
4868                    result.addAll(candidates);
4869                    result.removeAll(neverList);
4870                }
4871            }
4872        }
4873        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4874            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4875                    result.size());
4876            for (ResolveInfo info : result) {
4877                Slog.v(TAG, "  + " + info.activityInfo);
4878            }
4879        }
4880        return result;
4881    }
4882
4883    // Returns a packed value as a long:
4884    //
4885    // high 'int'-sized word: link status: undefined/ask/never/always.
4886    // low 'int'-sized word: relative priority among 'always' results.
4887    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4888        long result = ps.getDomainVerificationStatusForUser(userId);
4889        // if none available, get the master status
4890        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4891            if (ps.getIntentFilterVerificationInfo() != null) {
4892                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4893            }
4894        }
4895        return result;
4896    }
4897
4898    private ResolveInfo querySkipCurrentProfileIntents(
4899            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4900            int flags, int sourceUserId) {
4901        if (matchingFilters != null) {
4902            int size = matchingFilters.size();
4903            for (int i = 0; i < size; i ++) {
4904                CrossProfileIntentFilter filter = matchingFilters.get(i);
4905                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4906                    // Checking if there are activities in the target user that can handle the
4907                    // intent.
4908                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4909                            resolvedType, flags, sourceUserId);
4910                    if (resolveInfo != null) {
4911                        return resolveInfo;
4912                    }
4913                }
4914            }
4915        }
4916        return null;
4917    }
4918
4919    // Return matching ResolveInfo if any for skip current profile intent filters.
4920    private ResolveInfo queryCrossProfileIntents(
4921            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4922            int flags, int sourceUserId) {
4923        if (matchingFilters != null) {
4924            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4925            // match the same intent. For performance reasons, it is better not to
4926            // run queryIntent twice for the same userId
4927            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4928            int size = matchingFilters.size();
4929            for (int i = 0; i < size; i++) {
4930                CrossProfileIntentFilter filter = matchingFilters.get(i);
4931                int targetUserId = filter.getTargetUserId();
4932                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4933                        && !alreadyTriedUserIds.get(targetUserId)) {
4934                    // Checking if there are activities in the target user that can handle the
4935                    // intent.
4936                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4937                            resolvedType, flags, sourceUserId);
4938                    if (resolveInfo != null) return resolveInfo;
4939                    alreadyTriedUserIds.put(targetUserId, true);
4940                }
4941            }
4942        }
4943        return null;
4944    }
4945
4946    /**
4947     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4948     * will forward the intent to the filter's target user.
4949     * Otherwise, returns null.
4950     */
4951    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4952            String resolvedType, int flags, int sourceUserId) {
4953        int targetUserId = filter.getTargetUserId();
4954        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4955                resolvedType, flags, targetUserId);
4956        if (resultTargetUser != null && !resultTargetUser.isEmpty()
4957                && isUserEnabled(targetUserId)) {
4958            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
4959        }
4960        return null;
4961    }
4962
4963    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
4964            int sourceUserId, int targetUserId) {
4965        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4966        long ident = Binder.clearCallingIdentity();
4967        boolean targetIsProfile;
4968        try {
4969            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
4970        } finally {
4971            Binder.restoreCallingIdentity(ident);
4972        }
4973        String className;
4974        if (targetIsProfile) {
4975            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4976        } else {
4977            className = FORWARD_INTENT_TO_PARENT;
4978        }
4979        ComponentName forwardingActivityComponentName = new ComponentName(
4980                mAndroidApplication.packageName, className);
4981        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4982                sourceUserId);
4983        if (!targetIsProfile) {
4984            forwardingActivityInfo.showUserIcon = targetUserId;
4985            forwardingResolveInfo.noResourceId = true;
4986        }
4987        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4988        forwardingResolveInfo.priority = 0;
4989        forwardingResolveInfo.preferredOrder = 0;
4990        forwardingResolveInfo.match = 0;
4991        forwardingResolveInfo.isDefault = true;
4992        forwardingResolveInfo.filter = filter;
4993        forwardingResolveInfo.targetUserId = targetUserId;
4994        return forwardingResolveInfo;
4995    }
4996
4997    @Override
4998    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4999            Intent[] specifics, String[] specificTypes, Intent intent,
5000            String resolvedType, int flags, int userId) {
5001        if (!sUserManager.exists(userId)) return Collections.emptyList();
5002        flags = augmentFlagsForUser(flags, userId);
5003        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5004                false, "query intent activity options");
5005        final String resultsAction = intent.getAction();
5006
5007        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5008                | PackageManager.GET_RESOLVED_FILTER, userId);
5009
5010        if (DEBUG_INTENT_MATCHING) {
5011            Log.v(TAG, "Query " + intent + ": " + results);
5012        }
5013
5014        int specificsPos = 0;
5015        int N;
5016
5017        // todo: note that the algorithm used here is O(N^2).  This
5018        // isn't a problem in our current environment, but if we start running
5019        // into situations where we have more than 5 or 10 matches then this
5020        // should probably be changed to something smarter...
5021
5022        // First we go through and resolve each of the specific items
5023        // that were supplied, taking care of removing any corresponding
5024        // duplicate items in the generic resolve list.
5025        if (specifics != null) {
5026            for (int i=0; i<specifics.length; i++) {
5027                final Intent sintent = specifics[i];
5028                if (sintent == null) {
5029                    continue;
5030                }
5031
5032                if (DEBUG_INTENT_MATCHING) {
5033                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5034                }
5035
5036                String action = sintent.getAction();
5037                if (resultsAction != null && resultsAction.equals(action)) {
5038                    // If this action was explicitly requested, then don't
5039                    // remove things that have it.
5040                    action = null;
5041                }
5042
5043                ResolveInfo ri = null;
5044                ActivityInfo ai = null;
5045
5046                ComponentName comp = sintent.getComponent();
5047                if (comp == null) {
5048                    ri = resolveIntent(
5049                        sintent,
5050                        specificTypes != null ? specificTypes[i] : null,
5051                            flags, userId);
5052                    if (ri == null) {
5053                        continue;
5054                    }
5055                    if (ri == mResolveInfo) {
5056                        // ACK!  Must do something better with this.
5057                    }
5058                    ai = ri.activityInfo;
5059                    comp = new ComponentName(ai.applicationInfo.packageName,
5060                            ai.name);
5061                } else {
5062                    ai = getActivityInfo(comp, flags, userId);
5063                    if (ai == null) {
5064                        continue;
5065                    }
5066                }
5067
5068                // Look for any generic query activities that are duplicates
5069                // of this specific one, and remove them from the results.
5070                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5071                N = results.size();
5072                int j;
5073                for (j=specificsPos; j<N; j++) {
5074                    ResolveInfo sri = results.get(j);
5075                    if ((sri.activityInfo.name.equals(comp.getClassName())
5076                            && sri.activityInfo.applicationInfo.packageName.equals(
5077                                    comp.getPackageName()))
5078                        || (action != null && sri.filter.matchAction(action))) {
5079                        results.remove(j);
5080                        if (DEBUG_INTENT_MATCHING) Log.v(
5081                            TAG, "Removing duplicate item from " + j
5082                            + " due to specific " + specificsPos);
5083                        if (ri == null) {
5084                            ri = sri;
5085                        }
5086                        j--;
5087                        N--;
5088                    }
5089                }
5090
5091                // Add this specific item to its proper place.
5092                if (ri == null) {
5093                    ri = new ResolveInfo();
5094                    ri.activityInfo = ai;
5095                }
5096                results.add(specificsPos, ri);
5097                ri.specificIndex = i;
5098                specificsPos++;
5099            }
5100        }
5101
5102        // Now we go through the remaining generic results and remove any
5103        // duplicate actions that are found here.
5104        N = results.size();
5105        for (int i=specificsPos; i<N-1; i++) {
5106            final ResolveInfo rii = results.get(i);
5107            if (rii.filter == null) {
5108                continue;
5109            }
5110
5111            // Iterate over all of the actions of this result's intent
5112            // filter...  typically this should be just one.
5113            final Iterator<String> it = rii.filter.actionsIterator();
5114            if (it == null) {
5115                continue;
5116            }
5117            while (it.hasNext()) {
5118                final String action = it.next();
5119                if (resultsAction != null && resultsAction.equals(action)) {
5120                    // If this action was explicitly requested, then don't
5121                    // remove things that have it.
5122                    continue;
5123                }
5124                for (int j=i+1; j<N; j++) {
5125                    final ResolveInfo rij = results.get(j);
5126                    if (rij.filter != null && rij.filter.hasAction(action)) {
5127                        results.remove(j);
5128                        if (DEBUG_INTENT_MATCHING) Log.v(
5129                            TAG, "Removing duplicate item from " + j
5130                            + " due to action " + action + " at " + i);
5131                        j--;
5132                        N--;
5133                    }
5134                }
5135            }
5136
5137            // If the caller didn't request filter information, drop it now
5138            // so we don't have to marshall/unmarshall it.
5139            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5140                rii.filter = null;
5141            }
5142        }
5143
5144        // Filter out the caller activity if so requested.
5145        if (caller != null) {
5146            N = results.size();
5147            for (int i=0; i<N; i++) {
5148                ActivityInfo ainfo = results.get(i).activityInfo;
5149                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5150                        && caller.getClassName().equals(ainfo.name)) {
5151                    results.remove(i);
5152                    break;
5153                }
5154            }
5155        }
5156
5157        // If the caller didn't request filter information,
5158        // drop them now so we don't have to
5159        // marshall/unmarshall it.
5160        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5161            N = results.size();
5162            for (int i=0; i<N; i++) {
5163                results.get(i).filter = null;
5164            }
5165        }
5166
5167        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5168        return results;
5169    }
5170
5171    @Override
5172    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5173            int userId) {
5174        if (!sUserManager.exists(userId)) return Collections.emptyList();
5175        flags = augmentFlagsForUser(flags, userId);
5176        ComponentName comp = intent.getComponent();
5177        if (comp == null) {
5178            if (intent.getSelector() != null) {
5179                intent = intent.getSelector();
5180                comp = intent.getComponent();
5181            }
5182        }
5183        if (comp != null) {
5184            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5185            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5186            if (ai != null) {
5187                ResolveInfo ri = new ResolveInfo();
5188                ri.activityInfo = ai;
5189                list.add(ri);
5190            }
5191            return list;
5192        }
5193
5194        // reader
5195        synchronized (mPackages) {
5196            String pkgName = intent.getPackage();
5197            if (pkgName == null) {
5198                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5199            }
5200            final PackageParser.Package pkg = mPackages.get(pkgName);
5201            if (pkg != null) {
5202                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5203                        userId);
5204            }
5205            return null;
5206        }
5207    }
5208
5209    @Override
5210    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5211        if (!sUserManager.exists(userId)) return null;
5212        flags = augmentFlagsForUser(flags, userId);
5213        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5214        if (query != null) {
5215            if (query.size() >= 1) {
5216                // If there is more than one service with the same priority,
5217                // just arbitrarily pick the first one.
5218                return query.get(0);
5219            }
5220        }
5221        return null;
5222    }
5223
5224    @Override
5225    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5226            int userId) {
5227        if (!sUserManager.exists(userId)) return Collections.emptyList();
5228        flags = augmentFlagsForUser(flags, userId);
5229        ComponentName comp = intent.getComponent();
5230        if (comp == null) {
5231            if (intent.getSelector() != null) {
5232                intent = intent.getSelector();
5233                comp = intent.getComponent();
5234            }
5235        }
5236        if (comp != null) {
5237            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5238            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5239            if (si != null) {
5240                final ResolveInfo ri = new ResolveInfo();
5241                ri.serviceInfo = si;
5242                list.add(ri);
5243            }
5244            return list;
5245        }
5246
5247        // reader
5248        synchronized (mPackages) {
5249            String pkgName = intent.getPackage();
5250            if (pkgName == null) {
5251                return mServices.queryIntent(intent, resolvedType, flags, userId);
5252            }
5253            final PackageParser.Package pkg = mPackages.get(pkgName);
5254            if (pkg != null) {
5255                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5256                        userId);
5257            }
5258            return null;
5259        }
5260    }
5261
5262    @Override
5263    public List<ResolveInfo> queryIntentContentProviders(
5264            Intent intent, String resolvedType, int flags, int userId) {
5265        if (!sUserManager.exists(userId)) return Collections.emptyList();
5266        flags = augmentFlagsForUser(flags, userId);
5267        ComponentName comp = intent.getComponent();
5268        if (comp == null) {
5269            if (intent.getSelector() != null) {
5270                intent = intent.getSelector();
5271                comp = intent.getComponent();
5272            }
5273        }
5274        if (comp != null) {
5275            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5276            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5277            if (pi != null) {
5278                final ResolveInfo ri = new ResolveInfo();
5279                ri.providerInfo = pi;
5280                list.add(ri);
5281            }
5282            return list;
5283        }
5284
5285        // reader
5286        synchronized (mPackages) {
5287            String pkgName = intent.getPackage();
5288            if (pkgName == null) {
5289                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5290            }
5291            final PackageParser.Package pkg = mPackages.get(pkgName);
5292            if (pkg != null) {
5293                return mProviders.queryIntentForPackage(
5294                        intent, resolvedType, flags, pkg.providers, userId);
5295            }
5296            return null;
5297        }
5298    }
5299
5300    @Override
5301    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5302        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5303
5304        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5305
5306        // writer
5307        synchronized (mPackages) {
5308            ArrayList<PackageInfo> list;
5309            if (listUninstalled) {
5310                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5311                for (PackageSetting ps : mSettings.mPackages.values()) {
5312                    PackageInfo pi;
5313                    if (ps.pkg != null) {
5314                        pi = generatePackageInfo(ps.pkg, flags, userId);
5315                    } else {
5316                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5317                    }
5318                    if (pi != null) {
5319                        list.add(pi);
5320                    }
5321                }
5322            } else {
5323                list = new ArrayList<PackageInfo>(mPackages.size());
5324                for (PackageParser.Package p : mPackages.values()) {
5325                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5326                    if (pi != null) {
5327                        list.add(pi);
5328                    }
5329                }
5330            }
5331
5332            return new ParceledListSlice<PackageInfo>(list);
5333        }
5334    }
5335
5336    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5337            String[] permissions, boolean[] tmp, int flags, int userId) {
5338        int numMatch = 0;
5339        final PermissionsState permissionsState = ps.getPermissionsState();
5340        for (int i=0; i<permissions.length; i++) {
5341            final String permission = permissions[i];
5342            if (permissionsState.hasPermission(permission, userId)) {
5343                tmp[i] = true;
5344                numMatch++;
5345            } else {
5346                tmp[i] = false;
5347            }
5348        }
5349        if (numMatch == 0) {
5350            return;
5351        }
5352        PackageInfo pi;
5353        if (ps.pkg != null) {
5354            pi = generatePackageInfo(ps.pkg, flags, userId);
5355        } else {
5356            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5357        }
5358        // The above might return null in cases of uninstalled apps or install-state
5359        // skew across users/profiles.
5360        if (pi != null) {
5361            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5362                if (numMatch == permissions.length) {
5363                    pi.requestedPermissions = permissions;
5364                } else {
5365                    pi.requestedPermissions = new String[numMatch];
5366                    numMatch = 0;
5367                    for (int i=0; i<permissions.length; i++) {
5368                        if (tmp[i]) {
5369                            pi.requestedPermissions[numMatch] = permissions[i];
5370                            numMatch++;
5371                        }
5372                    }
5373                }
5374            }
5375            list.add(pi);
5376        }
5377    }
5378
5379    @Override
5380    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5381            String[] permissions, int flags, int userId) {
5382        if (!sUserManager.exists(userId)) return null;
5383        flags = augmentFlagsForUser(flags, userId);
5384        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5385
5386        // writer
5387        synchronized (mPackages) {
5388            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5389            boolean[] tmpBools = new boolean[permissions.length];
5390            if (listUninstalled) {
5391                for (PackageSetting ps : mSettings.mPackages.values()) {
5392                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5393                }
5394            } else {
5395                for (PackageParser.Package pkg : mPackages.values()) {
5396                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5397                    if (ps != null) {
5398                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5399                                userId);
5400                    }
5401                }
5402            }
5403
5404            return new ParceledListSlice<PackageInfo>(list);
5405        }
5406    }
5407
5408    @Override
5409    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5410        if (!sUserManager.exists(userId)) return null;
5411        flags = augmentFlagsForUser(flags, userId);
5412        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5413
5414        // writer
5415        synchronized (mPackages) {
5416            ArrayList<ApplicationInfo> list;
5417            if (listUninstalled) {
5418                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5419                for (PackageSetting ps : mSettings.mPackages.values()) {
5420                    ApplicationInfo ai;
5421                    if (ps.pkg != null) {
5422                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5423                                ps.readUserState(userId), userId);
5424                    } else {
5425                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5426                    }
5427                    if (ai != null) {
5428                        list.add(ai);
5429                    }
5430                }
5431            } else {
5432                list = new ArrayList<ApplicationInfo>(mPackages.size());
5433                for (PackageParser.Package p : mPackages.values()) {
5434                    if (p.mExtras != null) {
5435                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5436                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5437                        if (ai != null) {
5438                            list.add(ai);
5439                        }
5440                    }
5441                }
5442            }
5443
5444            return new ParceledListSlice<ApplicationInfo>(list);
5445        }
5446    }
5447
5448    public List<ApplicationInfo> getPersistentApplications(int flags) {
5449        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5450
5451        // reader
5452        synchronized (mPackages) {
5453            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5454            final int userId = UserHandle.getCallingUserId();
5455            while (i.hasNext()) {
5456                final PackageParser.Package p = i.next();
5457                if (p.applicationInfo != null
5458                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5459                        && (!mSafeMode || isSystemApp(p))) {
5460                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5461                    if (ps != null) {
5462                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5463                                ps.readUserState(userId), userId);
5464                        if (ai != null) {
5465                            finalList.add(ai);
5466                        }
5467                    }
5468                }
5469            }
5470        }
5471
5472        return finalList;
5473    }
5474
5475    @Override
5476    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5477        if (!sUserManager.exists(userId)) return null;
5478        flags = augmentFlagsForUser(flags, userId);
5479        // reader
5480        synchronized (mPackages) {
5481            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5482            PackageSetting ps = provider != null
5483                    ? mSettings.mPackages.get(provider.owner.packageName)
5484                    : null;
5485            return ps != null
5486                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5487                    && (!mSafeMode || (provider.info.applicationInfo.flags
5488                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5489                    ? PackageParser.generateProviderInfo(provider, flags,
5490                            ps.readUserState(userId), userId)
5491                    : null;
5492        }
5493    }
5494
5495    /**
5496     * @deprecated
5497     */
5498    @Deprecated
5499    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5500        // reader
5501        synchronized (mPackages) {
5502            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5503                    .entrySet().iterator();
5504            final int userId = UserHandle.getCallingUserId();
5505            while (i.hasNext()) {
5506                Map.Entry<String, PackageParser.Provider> entry = i.next();
5507                PackageParser.Provider p = entry.getValue();
5508                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5509
5510                if (ps != null && p.syncable
5511                        && (!mSafeMode || (p.info.applicationInfo.flags
5512                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5513                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5514                            ps.readUserState(userId), userId);
5515                    if (info != null) {
5516                        outNames.add(entry.getKey());
5517                        outInfo.add(info);
5518                    }
5519                }
5520            }
5521        }
5522    }
5523
5524    @Override
5525    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5526            int uid, int flags) {
5527        final int userId = processName != null ? UserHandle.getUserId(uid)
5528                : UserHandle.getCallingUserId();
5529        if (!sUserManager.exists(userId)) return null;
5530        flags = augmentFlagsForUser(flags, userId);
5531
5532        ArrayList<ProviderInfo> finalList = null;
5533        // reader
5534        synchronized (mPackages) {
5535            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5536            while (i.hasNext()) {
5537                final PackageParser.Provider p = i.next();
5538                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5539                if (ps != null && p.info.authority != null
5540                        && (processName == null
5541                                || (p.info.processName.equals(processName)
5542                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5543                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5544                        && (!mSafeMode
5545                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5546                    if (finalList == null) {
5547                        finalList = new ArrayList<ProviderInfo>(3);
5548                    }
5549                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5550                            ps.readUserState(userId), userId);
5551                    if (info != null) {
5552                        finalList.add(info);
5553                    }
5554                }
5555            }
5556        }
5557
5558        if (finalList != null) {
5559            Collections.sort(finalList, mProviderInitOrderSorter);
5560            return new ParceledListSlice<ProviderInfo>(finalList);
5561        }
5562
5563        return null;
5564    }
5565
5566    @Override
5567    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5568            int flags) {
5569        // reader
5570        synchronized (mPackages) {
5571            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5572            return PackageParser.generateInstrumentationInfo(i, flags);
5573        }
5574    }
5575
5576    @Override
5577    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5578            int flags) {
5579        ArrayList<InstrumentationInfo> finalList =
5580            new ArrayList<InstrumentationInfo>();
5581
5582        // reader
5583        synchronized (mPackages) {
5584            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5585            while (i.hasNext()) {
5586                final PackageParser.Instrumentation p = i.next();
5587                if (targetPackage == null
5588                        || targetPackage.equals(p.info.targetPackage)) {
5589                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5590                            flags);
5591                    if (ii != null) {
5592                        finalList.add(ii);
5593                    }
5594                }
5595            }
5596        }
5597
5598        return finalList;
5599    }
5600
5601    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5602        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5603        if (overlays == null) {
5604            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5605            return;
5606        }
5607        for (PackageParser.Package opkg : overlays.values()) {
5608            // Not much to do if idmap fails: we already logged the error
5609            // and we certainly don't want to abort installation of pkg simply
5610            // because an overlay didn't fit properly. For these reasons,
5611            // ignore the return value of createIdmapForPackagePairLI.
5612            createIdmapForPackagePairLI(pkg, opkg);
5613        }
5614    }
5615
5616    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5617            PackageParser.Package opkg) {
5618        if (!opkg.mTrustedOverlay) {
5619            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5620                    opkg.baseCodePath + ": overlay not trusted");
5621            return false;
5622        }
5623        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5624        if (overlaySet == null) {
5625            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5626                    opkg.baseCodePath + " but target package has no known overlays");
5627            return false;
5628        }
5629        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5630        // TODO: generate idmap for split APKs
5631        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5632            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5633                    + opkg.baseCodePath);
5634            return false;
5635        }
5636        PackageParser.Package[] overlayArray =
5637            overlaySet.values().toArray(new PackageParser.Package[0]);
5638        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5639            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5640                return p1.mOverlayPriority - p2.mOverlayPriority;
5641            }
5642        };
5643        Arrays.sort(overlayArray, cmp);
5644
5645        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5646        int i = 0;
5647        for (PackageParser.Package p : overlayArray) {
5648            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5649        }
5650        return true;
5651    }
5652
5653    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5654        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5655        try {
5656            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5657        } finally {
5658            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5659        }
5660    }
5661
5662    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5663        final File[] files = dir.listFiles();
5664        if (ArrayUtils.isEmpty(files)) {
5665            Log.d(TAG, "No files in app dir " + dir);
5666            return;
5667        }
5668
5669        if (DEBUG_PACKAGE_SCANNING) {
5670            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5671                    + " flags=0x" + Integer.toHexString(parseFlags));
5672        }
5673
5674        for (File file : files) {
5675            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5676                    && !PackageInstallerService.isStageName(file.getName());
5677            if (!isPackage) {
5678                // Ignore entries which are not packages
5679                continue;
5680            }
5681            try {
5682                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5683                        scanFlags, currentTime, null);
5684            } catch (PackageManagerException e) {
5685                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5686
5687                // Delete invalid userdata apps
5688                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5689                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5690                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5691                    if (file.isDirectory()) {
5692                        mInstaller.rmPackageDir(file.getAbsolutePath());
5693                    } else {
5694                        file.delete();
5695                    }
5696                }
5697            }
5698        }
5699    }
5700
5701    private static File getSettingsProblemFile() {
5702        File dataDir = Environment.getDataDirectory();
5703        File systemDir = new File(dataDir, "system");
5704        File fname = new File(systemDir, "uiderrors.txt");
5705        return fname;
5706    }
5707
5708    static void reportSettingsProblem(int priority, String msg) {
5709        logCriticalInfo(priority, msg);
5710    }
5711
5712    static void logCriticalInfo(int priority, String msg) {
5713        Slog.println(priority, TAG, msg);
5714        EventLogTags.writePmCriticalInfo(msg);
5715        try {
5716            File fname = getSettingsProblemFile();
5717            FileOutputStream out = new FileOutputStream(fname, true);
5718            PrintWriter pw = new FastPrintWriter(out);
5719            SimpleDateFormat formatter = new SimpleDateFormat();
5720            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5721            pw.println(dateString + ": " + msg);
5722            pw.close();
5723            FileUtils.setPermissions(
5724                    fname.toString(),
5725                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5726                    -1, -1);
5727        } catch (java.io.IOException e) {
5728        }
5729    }
5730
5731    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5732            PackageParser.Package pkg, File srcFile, int parseFlags)
5733            throws PackageManagerException {
5734        if (ps != null
5735                && ps.codePath.equals(srcFile)
5736                && ps.timeStamp == srcFile.lastModified()
5737                && !isCompatSignatureUpdateNeeded(pkg)
5738                && !isRecoverSignatureUpdateNeeded(pkg)) {
5739            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5740            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5741            ArraySet<PublicKey> signingKs;
5742            synchronized (mPackages) {
5743                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5744            }
5745            if (ps.signatures.mSignatures != null
5746                    && ps.signatures.mSignatures.length != 0
5747                    && signingKs != null) {
5748                // Optimization: reuse the existing cached certificates
5749                // if the package appears to be unchanged.
5750                pkg.mSignatures = ps.signatures.mSignatures;
5751                pkg.mSigningKeys = signingKs;
5752                return;
5753            }
5754
5755            Slog.w(TAG, "PackageSetting for " + ps.name
5756                    + " is missing signatures.  Collecting certs again to recover them.");
5757        } else {
5758            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5759        }
5760
5761        try {
5762            pp.collectCertificates(pkg, parseFlags);
5763            pp.collectManifestDigest(pkg);
5764        } catch (PackageParserException e) {
5765            throw PackageManagerException.from(e);
5766        }
5767    }
5768
5769    /**
5770     *  Traces a package scan.
5771     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5772     */
5773    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5774            long currentTime, UserHandle user) throws PackageManagerException {
5775        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5776        try {
5777            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5778        } finally {
5779            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5780        }
5781    }
5782
5783    /**
5784     *  Scans a package and returns the newly parsed package.
5785     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5786     */
5787    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5788            long currentTime, UserHandle user) throws PackageManagerException {
5789        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5790        parseFlags |= mDefParseFlags;
5791        PackageParser pp = new PackageParser();
5792        pp.setSeparateProcesses(mSeparateProcesses);
5793        pp.setOnlyCoreApps(mOnlyCore);
5794        pp.setDisplayMetrics(mMetrics);
5795
5796        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5797            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5798        }
5799
5800        final PackageParser.Package pkg;
5801        try {
5802            pkg = pp.parsePackage(scanFile, parseFlags);
5803        } catch (PackageParserException e) {
5804            throw PackageManagerException.from(e);
5805        }
5806
5807        PackageSetting ps = null;
5808        PackageSetting updatedPkg;
5809        // reader
5810        synchronized (mPackages) {
5811            // Look to see if we already know about this package.
5812            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5813            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5814                // This package has been renamed to its original name.  Let's
5815                // use that.
5816                ps = mSettings.peekPackageLPr(oldName);
5817            }
5818            // If there was no original package, see one for the real package name.
5819            if (ps == null) {
5820                ps = mSettings.peekPackageLPr(pkg.packageName);
5821            }
5822            // Check to see if this package could be hiding/updating a system
5823            // package.  Must look for it either under the original or real
5824            // package name depending on our state.
5825            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5826            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5827        }
5828        boolean updatedPkgBetter = false;
5829        // First check if this is a system package that may involve an update
5830        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
5831            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5832            // it needs to drop FLAG_PRIVILEGED.
5833            if (locationIsPrivileged(scanFile)) {
5834                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5835            } else {
5836                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5837            }
5838
5839            if (ps != null && !ps.codePath.equals(scanFile)) {
5840                // The path has changed from what was last scanned...  check the
5841                // version of the new path against what we have stored to determine
5842                // what to do.
5843                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5844                if (pkg.mVersionCode <= ps.versionCode) {
5845                    // The system package has been updated and the code path does not match
5846                    // Ignore entry. Skip it.
5847                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5848                            + " ignored: updated version " + ps.versionCode
5849                            + " better than this " + pkg.mVersionCode);
5850                    if (!updatedPkg.codePath.equals(scanFile)) {
5851                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5852                                + ps.name + " changing from " + updatedPkg.codePathString
5853                                + " to " + scanFile);
5854                        updatedPkg.codePath = scanFile;
5855                        updatedPkg.codePathString = scanFile.toString();
5856                        updatedPkg.resourcePath = scanFile;
5857                        updatedPkg.resourcePathString = scanFile.toString();
5858                    }
5859                    updatedPkg.pkg = pkg;
5860                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5861                            "Package " + ps.name + " at " + scanFile
5862                                    + " ignored: updated version " + ps.versionCode
5863                                    + " better than this " + pkg.mVersionCode);
5864                } else {
5865                    // The current app on the system partition is better than
5866                    // what we have updated to on the data partition; switch
5867                    // back to the system partition version.
5868                    // At this point, its safely assumed that package installation for
5869                    // apps in system partition will go through. If not there won't be a working
5870                    // version of the app
5871                    // writer
5872                    synchronized (mPackages) {
5873                        // Just remove the loaded entries from package lists.
5874                        mPackages.remove(ps.name);
5875                    }
5876
5877                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5878                            + " reverting from " + ps.codePathString
5879                            + ": new version " + pkg.mVersionCode
5880                            + " better than installed " + ps.versionCode);
5881
5882                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5883                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5884                    synchronized (mInstallLock) {
5885                        args.cleanUpResourcesLI();
5886                    }
5887                    synchronized (mPackages) {
5888                        mSettings.enableSystemPackageLPw(ps.name);
5889                    }
5890                    updatedPkgBetter = true;
5891                }
5892            }
5893        }
5894
5895        if (updatedPkg != null) {
5896            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5897            // initially
5898            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5899
5900            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5901            // flag set initially
5902            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5903                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5904            }
5905        }
5906
5907        // Verify certificates against what was last scanned
5908        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5909
5910        /*
5911         * A new system app appeared, but we already had a non-system one of the
5912         * same name installed earlier.
5913         */
5914        boolean shouldHideSystemApp = false;
5915        if (updatedPkg == null && ps != null
5916                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5917            /*
5918             * Check to make sure the signatures match first. If they don't,
5919             * wipe the installed application and its data.
5920             */
5921            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5922                    != PackageManager.SIGNATURE_MATCH) {
5923                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5924                        + " signatures don't match existing userdata copy; removing");
5925                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5926                ps = null;
5927            } else {
5928                /*
5929                 * If the newly-added system app is an older version than the
5930                 * already installed version, hide it. It will be scanned later
5931                 * and re-added like an update.
5932                 */
5933                if (pkg.mVersionCode <= ps.versionCode) {
5934                    shouldHideSystemApp = true;
5935                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5936                            + " but new version " + pkg.mVersionCode + " better than installed "
5937                            + ps.versionCode + "; hiding system");
5938                } else {
5939                    /*
5940                     * The newly found system app is a newer version that the
5941                     * one previously installed. Simply remove the
5942                     * already-installed application and replace it with our own
5943                     * while keeping the application data.
5944                     */
5945                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5946                            + " reverting from " + ps.codePathString + ": new version "
5947                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5948                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5949                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5950                    synchronized (mInstallLock) {
5951                        args.cleanUpResourcesLI();
5952                    }
5953                }
5954            }
5955        }
5956
5957        // The apk is forward locked (not public) if its code and resources
5958        // are kept in different files. (except for app in either system or
5959        // vendor path).
5960        // TODO grab this value from PackageSettings
5961        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5962            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5963                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5964            }
5965        }
5966
5967        // TODO: extend to support forward-locked splits
5968        String resourcePath = null;
5969        String baseResourcePath = null;
5970        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5971            if (ps != null && ps.resourcePathString != null) {
5972                resourcePath = ps.resourcePathString;
5973                baseResourcePath = ps.resourcePathString;
5974            } else {
5975                // Should not happen at all. Just log an error.
5976                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5977            }
5978        } else {
5979            resourcePath = pkg.codePath;
5980            baseResourcePath = pkg.baseCodePath;
5981        }
5982
5983        // Set application objects path explicitly.
5984        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5985        pkg.applicationInfo.setCodePath(pkg.codePath);
5986        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5987        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5988        pkg.applicationInfo.setResourcePath(resourcePath);
5989        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5990        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5991
5992        // Note that we invoke the following method only if we are about to unpack an application
5993        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5994                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5995
5996        /*
5997         * If the system app should be overridden by a previously installed
5998         * data, hide the system app now and let the /data/app scan pick it up
5999         * again.
6000         */
6001        if (shouldHideSystemApp) {
6002            synchronized (mPackages) {
6003                mSettings.disableSystemPackageLPw(pkg.packageName);
6004            }
6005        }
6006
6007        return scannedPkg;
6008    }
6009
6010    private static String fixProcessName(String defProcessName,
6011            String processName, int uid) {
6012        if (processName == null) {
6013            return defProcessName;
6014        }
6015        return processName;
6016    }
6017
6018    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6019            throws PackageManagerException {
6020        if (pkgSetting.signatures.mSignatures != null) {
6021            // Already existing package. Make sure signatures match
6022            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6023                    == PackageManager.SIGNATURE_MATCH;
6024            if (!match) {
6025                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6026                        == PackageManager.SIGNATURE_MATCH;
6027            }
6028            if (!match) {
6029                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6030                        == PackageManager.SIGNATURE_MATCH;
6031            }
6032            if (!match) {
6033                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6034                        + pkg.packageName + " signatures do not match the "
6035                        + "previously installed version; ignoring!");
6036            }
6037        }
6038
6039        // Check for shared user signatures
6040        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6041            // Already existing package. Make sure signatures match
6042            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6043                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6044            if (!match) {
6045                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6046                        == PackageManager.SIGNATURE_MATCH;
6047            }
6048            if (!match) {
6049                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6050                        == PackageManager.SIGNATURE_MATCH;
6051            }
6052            if (!match) {
6053                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6054                        "Package " + pkg.packageName
6055                        + " has no signatures that match those in shared user "
6056                        + pkgSetting.sharedUser.name + "; ignoring!");
6057            }
6058        }
6059    }
6060
6061    /**
6062     * Enforces that only the system UID or root's UID can call a method exposed
6063     * via Binder.
6064     *
6065     * @param message used as message if SecurityException is thrown
6066     * @throws SecurityException if the caller is not system or root
6067     */
6068    private static final void enforceSystemOrRoot(String message) {
6069        final int uid = Binder.getCallingUid();
6070        if (uid != Process.SYSTEM_UID && uid != 0) {
6071            throw new SecurityException(message);
6072        }
6073    }
6074
6075    @Override
6076    public void performFstrimIfNeeded() {
6077        enforceSystemOrRoot("Only the system can request fstrim");
6078
6079        // Before everything else, see whether we need to fstrim.
6080        try {
6081            IMountService ms = PackageHelper.getMountService();
6082            if (ms != null) {
6083                final boolean isUpgrade = isUpgrade();
6084                boolean doTrim = isUpgrade;
6085                if (doTrim) {
6086                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6087                } else {
6088                    final long interval = android.provider.Settings.Global.getLong(
6089                            mContext.getContentResolver(),
6090                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6091                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6092                    if (interval > 0) {
6093                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6094                        if (timeSinceLast > interval) {
6095                            doTrim = true;
6096                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6097                                    + "; running immediately");
6098                        }
6099                    }
6100                }
6101                if (doTrim) {
6102                    if (!isFirstBoot()) {
6103                        try {
6104                            ActivityManagerNative.getDefault().showBootMessage(
6105                                    mContext.getResources().getString(
6106                                            R.string.android_upgrading_fstrim), true);
6107                        } catch (RemoteException e) {
6108                        }
6109                    }
6110                    ms.runMaintenance();
6111                }
6112            } else {
6113                Slog.e(TAG, "Mount service unavailable!");
6114            }
6115        } catch (RemoteException e) {
6116            // Can't happen; MountService is local
6117        }
6118    }
6119
6120    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6121        List<ResolveInfo> ris = null;
6122        try {
6123            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6124                    intent, null, 0, userId);
6125        } catch (RemoteException e) {
6126        }
6127        ArraySet<String> pkgNames = new ArraySet<String>();
6128        if (ris != null) {
6129            for (ResolveInfo ri : ris) {
6130                pkgNames.add(ri.activityInfo.packageName);
6131            }
6132        }
6133        return pkgNames;
6134    }
6135
6136    @Override
6137    public void notifyPackageUse(String packageName) {
6138        synchronized (mPackages) {
6139            PackageParser.Package p = mPackages.get(packageName);
6140            if (p == null) {
6141                return;
6142            }
6143            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6144        }
6145    }
6146
6147    @Override
6148    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6149        return performDexOptTraced(packageName, instructionSet);
6150    }
6151
6152    public boolean performDexOpt(String packageName, String instructionSet) {
6153        return performDexOptTraced(packageName, instructionSet);
6154    }
6155
6156    private boolean performDexOptTraced(String packageName, String instructionSet) {
6157        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6158        try {
6159            return performDexOptInternal(packageName, instructionSet);
6160        } finally {
6161            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6162        }
6163    }
6164
6165    private boolean performDexOptInternal(String packageName, String instructionSet) {
6166        PackageParser.Package p;
6167        final String targetInstructionSet;
6168        synchronized (mPackages) {
6169            p = mPackages.get(packageName);
6170            if (p == null) {
6171                return false;
6172            }
6173            mPackageUsage.write(false);
6174
6175            targetInstructionSet = instructionSet != null ? instructionSet :
6176                    getPrimaryInstructionSet(p.applicationInfo);
6177            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6178                return false;
6179            }
6180        }
6181        long callingId = Binder.clearCallingIdentity();
6182        try {
6183            synchronized (mInstallLock) {
6184                final String[] instructionSets = new String[] { targetInstructionSet };
6185                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6186                        true /* inclDependencies */);
6187                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6188            }
6189        } finally {
6190            Binder.restoreCallingIdentity(callingId);
6191        }
6192    }
6193
6194    public ArraySet<String> getPackagesThatNeedDexOpt() {
6195        ArraySet<String> pkgs = null;
6196        synchronized (mPackages) {
6197            for (PackageParser.Package p : mPackages.values()) {
6198                if (DEBUG_DEXOPT) {
6199                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6200                }
6201                if (!p.mDexOptPerformed.isEmpty()) {
6202                    continue;
6203                }
6204                if (pkgs == null) {
6205                    pkgs = new ArraySet<String>();
6206                }
6207                pkgs.add(p.packageName);
6208            }
6209        }
6210        return pkgs;
6211    }
6212
6213    public void shutdown() {
6214        mPackageUsage.write(true);
6215    }
6216
6217    @Override
6218    public void forceDexOpt(String packageName) {
6219        enforceSystemOrRoot("forceDexOpt");
6220
6221        PackageParser.Package pkg;
6222        synchronized (mPackages) {
6223            pkg = mPackages.get(packageName);
6224            if (pkg == null) {
6225                throw new IllegalArgumentException("Missing package: " + packageName);
6226            }
6227        }
6228
6229        synchronized (mInstallLock) {
6230            final String[] instructionSets = new String[] {
6231                    getPrimaryInstructionSet(pkg.applicationInfo) };
6232
6233            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6234
6235            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6236                    true /* inclDependencies */);
6237
6238            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6239            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6240                throw new IllegalStateException("Failed to dexopt: " + res);
6241            }
6242        }
6243    }
6244
6245    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6246        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6247            Slog.w(TAG, "Unable to update from " + oldPkg.name
6248                    + " to " + newPkg.packageName
6249                    + ": old package not in system partition");
6250            return false;
6251        } else if (mPackages.get(oldPkg.name) != null) {
6252            Slog.w(TAG, "Unable to update from " + oldPkg.name
6253                    + " to " + newPkg.packageName
6254                    + ": old package still exists");
6255            return false;
6256        }
6257        return true;
6258    }
6259
6260    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6261        int[] users = sUserManager.getUserIds();
6262        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6263        if (res < 0) {
6264            return res;
6265        }
6266        for (int user : users) {
6267            if (user != 0) {
6268                res = mInstaller.createUserData(volumeUuid, packageName,
6269                        UserHandle.getUid(user, uid), user, seinfo);
6270                if (res < 0) {
6271                    return res;
6272                }
6273            }
6274        }
6275        return res;
6276    }
6277
6278    private int removeDataDirsLI(String volumeUuid, String packageName) {
6279        int[] users = sUserManager.getUserIds();
6280        int res = 0;
6281        for (int user : users) {
6282            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6283            if (resInner < 0) {
6284                res = resInner;
6285            }
6286        }
6287
6288        return res;
6289    }
6290
6291    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6292        int[] users = sUserManager.getUserIds();
6293        int res = 0;
6294        for (int user : users) {
6295            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6296            if (resInner < 0) {
6297                res = resInner;
6298            }
6299        }
6300        return res;
6301    }
6302
6303    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6304            PackageParser.Package changingLib) {
6305        if (file.path != null) {
6306            usesLibraryFiles.add(file.path);
6307            return;
6308        }
6309        PackageParser.Package p = mPackages.get(file.apk);
6310        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6311            // If we are doing this while in the middle of updating a library apk,
6312            // then we need to make sure to use that new apk for determining the
6313            // dependencies here.  (We haven't yet finished committing the new apk
6314            // to the package manager state.)
6315            if (p == null || p.packageName.equals(changingLib.packageName)) {
6316                p = changingLib;
6317            }
6318        }
6319        if (p != null) {
6320            usesLibraryFiles.addAll(p.getAllCodePaths());
6321        }
6322    }
6323
6324    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6325            PackageParser.Package changingLib) throws PackageManagerException {
6326        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6327            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6328            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6329            for (int i=0; i<N; i++) {
6330                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6331                if (file == null) {
6332                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6333                            "Package " + pkg.packageName + " requires unavailable shared library "
6334                            + pkg.usesLibraries.get(i) + "; failing!");
6335                }
6336                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6337            }
6338            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6339            for (int i=0; i<N; i++) {
6340                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6341                if (file == null) {
6342                    Slog.w(TAG, "Package " + pkg.packageName
6343                            + " desires unavailable shared library "
6344                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6345                } else {
6346                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6347                }
6348            }
6349            N = usesLibraryFiles.size();
6350            if (N > 0) {
6351                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6352            } else {
6353                pkg.usesLibraryFiles = null;
6354            }
6355        }
6356    }
6357
6358    private static boolean hasString(List<String> list, List<String> which) {
6359        if (list == null) {
6360            return false;
6361        }
6362        for (int i=list.size()-1; i>=0; i--) {
6363            for (int j=which.size()-1; j>=0; j--) {
6364                if (which.get(j).equals(list.get(i))) {
6365                    return true;
6366                }
6367            }
6368        }
6369        return false;
6370    }
6371
6372    private void updateAllSharedLibrariesLPw() {
6373        for (PackageParser.Package pkg : mPackages.values()) {
6374            try {
6375                updateSharedLibrariesLPw(pkg, null);
6376            } catch (PackageManagerException e) {
6377                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6378            }
6379        }
6380    }
6381
6382    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6383            PackageParser.Package changingPkg) {
6384        ArrayList<PackageParser.Package> res = null;
6385        for (PackageParser.Package pkg : mPackages.values()) {
6386            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6387                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6388                if (res == null) {
6389                    res = new ArrayList<PackageParser.Package>();
6390                }
6391                res.add(pkg);
6392                try {
6393                    updateSharedLibrariesLPw(pkg, changingPkg);
6394                } catch (PackageManagerException e) {
6395                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6396                }
6397            }
6398        }
6399        return res;
6400    }
6401
6402    /**
6403     * Derive the value of the {@code cpuAbiOverride} based on the provided
6404     * value and an optional stored value from the package settings.
6405     */
6406    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6407        String cpuAbiOverride = null;
6408
6409        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6410            cpuAbiOverride = null;
6411        } else if (abiOverride != null) {
6412            cpuAbiOverride = abiOverride;
6413        } else if (settings != null) {
6414            cpuAbiOverride = settings.cpuAbiOverrideString;
6415        }
6416
6417        return cpuAbiOverride;
6418    }
6419
6420    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6421            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6422        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6423        try {
6424            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6425        } finally {
6426            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6427        }
6428    }
6429
6430    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6431            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6432        boolean success = false;
6433        try {
6434            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6435                    currentTime, user);
6436            success = true;
6437            return res;
6438        } finally {
6439            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6440                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6441            }
6442        }
6443    }
6444
6445    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6446            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6447        final File scanFile = new File(pkg.codePath);
6448        if (pkg.applicationInfo.getCodePath() == null ||
6449                pkg.applicationInfo.getResourcePath() == null) {
6450            // Bail out. The resource and code paths haven't been set.
6451            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6452                    "Code and resource paths haven't been set correctly");
6453        }
6454
6455        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6456            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6457        } else {
6458            // Only allow system apps to be flagged as core apps.
6459            pkg.coreApp = false;
6460        }
6461
6462        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6463            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6464        }
6465
6466        if (mCustomResolverComponentName != null &&
6467                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6468            setUpCustomResolverActivity(pkg);
6469        }
6470
6471        if (pkg.packageName.equals("android")) {
6472            synchronized (mPackages) {
6473                if (mAndroidApplication != null) {
6474                    Slog.w(TAG, "*************************************************");
6475                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6476                    Slog.w(TAG, " file=" + scanFile);
6477                    Slog.w(TAG, "*************************************************");
6478                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6479                            "Core android package being redefined.  Skipping.");
6480                }
6481
6482                // Set up information for our fall-back user intent resolution activity.
6483                mPlatformPackage = pkg;
6484                pkg.mVersionCode = mSdkVersion;
6485                mAndroidApplication = pkg.applicationInfo;
6486
6487                if (!mResolverReplaced) {
6488                    mResolveActivity.applicationInfo = mAndroidApplication;
6489                    mResolveActivity.name = ResolverActivity.class.getName();
6490                    mResolveActivity.packageName = mAndroidApplication.packageName;
6491                    mResolveActivity.processName = "system:ui";
6492                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6493                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6494                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6495                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6496                    mResolveActivity.exported = true;
6497                    mResolveActivity.enabled = true;
6498                    mResolveInfo.activityInfo = mResolveActivity;
6499                    mResolveInfo.priority = 0;
6500                    mResolveInfo.preferredOrder = 0;
6501                    mResolveInfo.match = 0;
6502                    mResolveComponentName = new ComponentName(
6503                            mAndroidApplication.packageName, mResolveActivity.name);
6504                }
6505            }
6506        }
6507
6508        if (DEBUG_PACKAGE_SCANNING) {
6509            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6510                Log.d(TAG, "Scanning package " + pkg.packageName);
6511        }
6512
6513        if (mPackages.containsKey(pkg.packageName)
6514                || mSharedLibraries.containsKey(pkg.packageName)) {
6515            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6516                    "Application package " + pkg.packageName
6517                    + " already installed.  Skipping duplicate.");
6518        }
6519
6520        // If we're only installing presumed-existing packages, require that the
6521        // scanned APK is both already known and at the path previously established
6522        // for it.  Previously unknown packages we pick up normally, but if we have an
6523        // a priori expectation about this package's install presence, enforce it.
6524        // With a singular exception for new system packages. When an OTA contains
6525        // a new system package, we allow the codepath to change from a system location
6526        // to the user-installed location. If we don't allow this change, any newer,
6527        // user-installed version of the application will be ignored.
6528        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6529            if (mExpectingBetter.containsKey(pkg.packageName)) {
6530                logCriticalInfo(Log.WARN,
6531                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6532            } else {
6533                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6534                if (known != null) {
6535                    if (DEBUG_PACKAGE_SCANNING) {
6536                        Log.d(TAG, "Examining " + pkg.codePath
6537                                + " and requiring known paths " + known.codePathString
6538                                + " & " + known.resourcePathString);
6539                    }
6540                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6541                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6542                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6543                                "Application package " + pkg.packageName
6544                                + " found at " + pkg.applicationInfo.getCodePath()
6545                                + " but expected at " + known.codePathString + "; ignoring.");
6546                    }
6547                }
6548            }
6549        }
6550
6551        // Initialize package source and resource directories
6552        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6553        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6554
6555        SharedUserSetting suid = null;
6556        PackageSetting pkgSetting = null;
6557
6558        if (!isSystemApp(pkg)) {
6559            // Only system apps can use these features.
6560            pkg.mOriginalPackages = null;
6561            pkg.mRealPackage = null;
6562            pkg.mAdoptPermissions = null;
6563        }
6564
6565        // writer
6566        synchronized (mPackages) {
6567            if (pkg.mSharedUserId != null) {
6568                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6569                if (suid == null) {
6570                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6571                            "Creating application package " + pkg.packageName
6572                            + " for shared user failed");
6573                }
6574                if (DEBUG_PACKAGE_SCANNING) {
6575                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6576                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6577                                + "): packages=" + suid.packages);
6578                }
6579            }
6580
6581            // Check if we are renaming from an original package name.
6582            PackageSetting origPackage = null;
6583            String realName = null;
6584            if (pkg.mOriginalPackages != null) {
6585                // This package may need to be renamed to a previously
6586                // installed name.  Let's check on that...
6587                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6588                if (pkg.mOriginalPackages.contains(renamed)) {
6589                    // This package had originally been installed as the
6590                    // original name, and we have already taken care of
6591                    // transitioning to the new one.  Just update the new
6592                    // one to continue using the old name.
6593                    realName = pkg.mRealPackage;
6594                    if (!pkg.packageName.equals(renamed)) {
6595                        // Callers into this function may have already taken
6596                        // care of renaming the package; only do it here if
6597                        // it is not already done.
6598                        pkg.setPackageName(renamed);
6599                    }
6600
6601                } else {
6602                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6603                        if ((origPackage = mSettings.peekPackageLPr(
6604                                pkg.mOriginalPackages.get(i))) != null) {
6605                            // We do have the package already installed under its
6606                            // original name...  should we use it?
6607                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6608                                // New package is not compatible with original.
6609                                origPackage = null;
6610                                continue;
6611                            } else if (origPackage.sharedUser != null) {
6612                                // Make sure uid is compatible between packages.
6613                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6614                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6615                                            + " to " + pkg.packageName + ": old uid "
6616                                            + origPackage.sharedUser.name
6617                                            + " differs from " + pkg.mSharedUserId);
6618                                    origPackage = null;
6619                                    continue;
6620                                }
6621                            } else {
6622                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6623                                        + pkg.packageName + " to old name " + origPackage.name);
6624                            }
6625                            break;
6626                        }
6627                    }
6628                }
6629            }
6630
6631            if (mTransferedPackages.contains(pkg.packageName)) {
6632                Slog.w(TAG, "Package " + pkg.packageName
6633                        + " was transferred to another, but its .apk remains");
6634            }
6635
6636            // Just create the setting, don't add it yet. For already existing packages
6637            // the PkgSetting exists already and doesn't have to be created.
6638            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6639                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6640                    pkg.applicationInfo.primaryCpuAbi,
6641                    pkg.applicationInfo.secondaryCpuAbi,
6642                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6643                    user, false);
6644            if (pkgSetting == null) {
6645                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6646                        "Creating application package " + pkg.packageName + " failed");
6647            }
6648
6649            if (pkgSetting.origPackage != null) {
6650                // If we are first transitioning from an original package,
6651                // fix up the new package's name now.  We need to do this after
6652                // looking up the package under its new name, so getPackageLP
6653                // can take care of fiddling things correctly.
6654                pkg.setPackageName(origPackage.name);
6655
6656                // File a report about this.
6657                String msg = "New package " + pkgSetting.realName
6658                        + " renamed to replace old package " + pkgSetting.name;
6659                reportSettingsProblem(Log.WARN, msg);
6660
6661                // Make a note of it.
6662                mTransferedPackages.add(origPackage.name);
6663
6664                // No longer need to retain this.
6665                pkgSetting.origPackage = null;
6666            }
6667
6668            if (realName != null) {
6669                // Make a note of it.
6670                mTransferedPackages.add(pkg.packageName);
6671            }
6672
6673            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6674                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6675            }
6676
6677            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6678                // Check all shared libraries and map to their actual file path.
6679                // We only do this here for apps not on a system dir, because those
6680                // are the only ones that can fail an install due to this.  We
6681                // will take care of the system apps by updating all of their
6682                // library paths after the scan is done.
6683                updateSharedLibrariesLPw(pkg, null);
6684            }
6685
6686            if (mFoundPolicyFile) {
6687                SELinuxMMAC.assignSeinfoValue(pkg);
6688            }
6689
6690            pkg.applicationInfo.uid = pkgSetting.appId;
6691            pkg.mExtras = pkgSetting;
6692            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6693                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6694                    // We just determined the app is signed correctly, so bring
6695                    // over the latest parsed certs.
6696                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6697                } else {
6698                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6699                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6700                                "Package " + pkg.packageName + " upgrade keys do not match the "
6701                                + "previously installed version");
6702                    } else {
6703                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6704                        String msg = "System package " + pkg.packageName
6705                            + " signature changed; retaining data.";
6706                        reportSettingsProblem(Log.WARN, msg);
6707                    }
6708                }
6709            } else {
6710                try {
6711                    verifySignaturesLP(pkgSetting, pkg);
6712                    // We just determined the app is signed correctly, so bring
6713                    // over the latest parsed certs.
6714                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6715                } catch (PackageManagerException e) {
6716                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6717                        throw e;
6718                    }
6719                    // The signature has changed, but this package is in the system
6720                    // image...  let's recover!
6721                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6722                    // However...  if this package is part of a shared user, but it
6723                    // doesn't match the signature of the shared user, let's fail.
6724                    // What this means is that you can't change the signatures
6725                    // associated with an overall shared user, which doesn't seem all
6726                    // that unreasonable.
6727                    if (pkgSetting.sharedUser != null) {
6728                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6729                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6730                            throw new PackageManagerException(
6731                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6732                                            "Signature mismatch for shared user : "
6733                                            + pkgSetting.sharedUser);
6734                        }
6735                    }
6736                    // File a report about this.
6737                    String msg = "System package " + pkg.packageName
6738                        + " signature changed; retaining data.";
6739                    reportSettingsProblem(Log.WARN, msg);
6740                }
6741            }
6742            // Verify that this new package doesn't have any content providers
6743            // that conflict with existing packages.  Only do this if the
6744            // package isn't already installed, since we don't want to break
6745            // things that are installed.
6746            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6747                final int N = pkg.providers.size();
6748                int i;
6749                for (i=0; i<N; i++) {
6750                    PackageParser.Provider p = pkg.providers.get(i);
6751                    if (p.info.authority != null) {
6752                        String names[] = p.info.authority.split(";");
6753                        for (int j = 0; j < names.length; j++) {
6754                            if (mProvidersByAuthority.containsKey(names[j])) {
6755                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6756                                final String otherPackageName =
6757                                        ((other != null && other.getComponentName() != null) ?
6758                                                other.getComponentName().getPackageName() : "?");
6759                                throw new PackageManagerException(
6760                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6761                                                "Can't install because provider name " + names[j]
6762                                                + " (in package " + pkg.applicationInfo.packageName
6763                                                + ") is already used by " + otherPackageName);
6764                            }
6765                        }
6766                    }
6767                }
6768            }
6769
6770            if (pkg.mAdoptPermissions != null) {
6771                // This package wants to adopt ownership of permissions from
6772                // another package.
6773                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6774                    final String origName = pkg.mAdoptPermissions.get(i);
6775                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6776                    if (orig != null) {
6777                        if (verifyPackageUpdateLPr(orig, pkg)) {
6778                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6779                                    + pkg.packageName);
6780                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6781                        }
6782                    }
6783                }
6784            }
6785        }
6786
6787        final String pkgName = pkg.packageName;
6788
6789        final long scanFileTime = scanFile.lastModified();
6790        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6791        pkg.applicationInfo.processName = fixProcessName(
6792                pkg.applicationInfo.packageName,
6793                pkg.applicationInfo.processName,
6794                pkg.applicationInfo.uid);
6795
6796        if (pkg != mPlatformPackage) {
6797            // This is a normal package, need to make its data directory.
6798            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
6799                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
6800
6801            boolean uidError = false;
6802            if (dataPath.exists()) {
6803                int currentUid = 0;
6804                try {
6805                    StructStat stat = Os.stat(dataPath.getPath());
6806                    currentUid = stat.st_uid;
6807                } catch (ErrnoException e) {
6808                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6809                }
6810
6811                // If we have mismatched owners for the data path, we have a problem.
6812                if (currentUid != pkg.applicationInfo.uid) {
6813                    boolean recovered = false;
6814                    if (currentUid == 0) {
6815                        // The directory somehow became owned by root.  Wow.
6816                        // This is probably because the system was stopped while
6817                        // installd was in the middle of messing with its libs
6818                        // directory.  Ask installd to fix that.
6819                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6820                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6821                        if (ret >= 0) {
6822                            recovered = true;
6823                            String msg = "Package " + pkg.packageName
6824                                    + " unexpectedly changed to uid 0; recovered to " +
6825                                    + pkg.applicationInfo.uid;
6826                            reportSettingsProblem(Log.WARN, msg);
6827                        }
6828                    }
6829                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6830                            || (scanFlags&SCAN_BOOTING) != 0)) {
6831                        // If this is a system app, we can at least delete its
6832                        // current data so the application will still work.
6833                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6834                        if (ret >= 0) {
6835                            // TODO: Kill the processes first
6836                            // Old data gone!
6837                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6838                                    ? "System package " : "Third party package ";
6839                            String msg = prefix + pkg.packageName
6840                                    + " has changed from uid: "
6841                                    + currentUid + " to "
6842                                    + pkg.applicationInfo.uid + "; old data erased";
6843                            reportSettingsProblem(Log.WARN, msg);
6844                            recovered = true;
6845
6846                            // And now re-install the app.
6847                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6848                                    pkg.applicationInfo.seinfo);
6849                            if (ret == -1) {
6850                                // Ack should not happen!
6851                                msg = prefix + pkg.packageName
6852                                        + " could not have data directory re-created after delete.";
6853                                reportSettingsProblem(Log.WARN, msg);
6854                                throw new PackageManagerException(
6855                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6856                            }
6857                        }
6858                        if (!recovered) {
6859                            mHasSystemUidErrors = true;
6860                        }
6861                    } else if (!recovered) {
6862                        // If we allow this install to proceed, we will be broken.
6863                        // Abort, abort!
6864                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6865                                "scanPackageLI");
6866                    }
6867                    if (!recovered) {
6868                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6869                            + pkg.applicationInfo.uid + "/fs_"
6870                            + currentUid;
6871                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6872                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6873                        String msg = "Package " + pkg.packageName
6874                                + " has mismatched uid: "
6875                                + currentUid + " on disk, "
6876                                + pkg.applicationInfo.uid + " in settings";
6877                        // writer
6878                        synchronized (mPackages) {
6879                            mSettings.mReadMessages.append(msg);
6880                            mSettings.mReadMessages.append('\n');
6881                            uidError = true;
6882                            if (!pkgSetting.uidError) {
6883                                reportSettingsProblem(Log.ERROR, msg);
6884                            }
6885                        }
6886                    }
6887                }
6888
6889                if (mShouldRestoreconData) {
6890                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6891                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6892                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6893                }
6894            } else {
6895                if (DEBUG_PACKAGE_SCANNING) {
6896                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6897                        Log.v(TAG, "Want this data dir: " + dataPath);
6898                }
6899                //invoke installer to do the actual installation
6900                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6901                        pkg.applicationInfo.seinfo);
6902                if (ret < 0) {
6903                    // Error from installer
6904                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6905                            "Unable to create data dirs [errorCode=" + ret + "]");
6906                }
6907            }
6908
6909            // Get all of our default paths setup
6910            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
6911
6912            pkgSetting.uidError = uidError;
6913        }
6914
6915        final String path = scanFile.getPath();
6916        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6917
6918        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6919            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6920
6921            // Some system apps still use directory structure for native libraries
6922            // in which case we might end up not detecting abi solely based on apk
6923            // structure. Try to detect abi based on directory structure.
6924            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6925                    pkg.applicationInfo.primaryCpuAbi == null) {
6926                setBundledAppAbisAndRoots(pkg, pkgSetting);
6927                setNativeLibraryPaths(pkg);
6928            }
6929
6930        } else {
6931            if ((scanFlags & SCAN_MOVE) != 0) {
6932                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6933                // but we already have this packages package info in the PackageSetting. We just
6934                // use that and derive the native library path based on the new codepath.
6935                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6936                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6937            }
6938
6939            // Set native library paths again. For moves, the path will be updated based on the
6940            // ABIs we've determined above. For non-moves, the path will be updated based on the
6941            // ABIs we determined during compilation, but the path will depend on the final
6942            // package path (after the rename away from the stage path).
6943            setNativeLibraryPaths(pkg);
6944        }
6945
6946        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6947        final int[] userIds = sUserManager.getUserIds();
6948        synchronized (mInstallLock) {
6949            // Make sure all user data directories are ready to roll; we're okay
6950            // if they already exist
6951            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6952                for (int userId : userIds) {
6953                    if (userId != UserHandle.USER_SYSTEM) {
6954                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6955                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6956                                pkg.applicationInfo.seinfo);
6957                    }
6958                }
6959            }
6960
6961            // Create a native library symlink only if we have native libraries
6962            // and if the native libraries are 32 bit libraries. We do not provide
6963            // this symlink for 64 bit libraries.
6964            if (pkg.applicationInfo.primaryCpuAbi != null &&
6965                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6966                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
6967                try {
6968                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6969                    for (int userId : userIds) {
6970                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6971                                nativeLibPath, userId) < 0) {
6972                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6973                                    "Failed linking native library dir (user=" + userId + ")");
6974                        }
6975                    }
6976                } finally {
6977                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6978                }
6979            }
6980        }
6981
6982        // This is a special case for the "system" package, where the ABI is
6983        // dictated by the zygote configuration (and init.rc). We should keep track
6984        // of this ABI so that we can deal with "normal" applications that run under
6985        // the same UID correctly.
6986        if (mPlatformPackage == pkg) {
6987            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6988                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6989        }
6990
6991        // If there's a mismatch between the abi-override in the package setting
6992        // and the abiOverride specified for the install. Warn about this because we
6993        // would've already compiled the app without taking the package setting into
6994        // account.
6995        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6996            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6997                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6998                        " for package: " + pkg.packageName);
6999            }
7000        }
7001
7002        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7003        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7004        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7005
7006        // Copy the derived override back to the parsed package, so that we can
7007        // update the package settings accordingly.
7008        pkg.cpuAbiOverride = cpuAbiOverride;
7009
7010        if (DEBUG_ABI_SELECTION) {
7011            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7012                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7013                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7014        }
7015
7016        // Push the derived path down into PackageSettings so we know what to
7017        // clean up at uninstall time.
7018        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7019
7020        if (DEBUG_ABI_SELECTION) {
7021            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7022                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7023                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7024        }
7025
7026        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7027            // We don't do this here during boot because we can do it all
7028            // at once after scanning all existing packages.
7029            //
7030            // We also do this *before* we perform dexopt on this package, so that
7031            // we can avoid redundant dexopts, and also to make sure we've got the
7032            // code and package path correct.
7033            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7034                    pkg, true /* boot complete */);
7035        }
7036
7037        if (mFactoryTest && pkg.requestedPermissions.contains(
7038                android.Manifest.permission.FACTORY_TEST)) {
7039            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7040        }
7041
7042        ArrayList<PackageParser.Package> clientLibPkgs = null;
7043
7044        // writer
7045        synchronized (mPackages) {
7046            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7047                // Only system apps can add new shared libraries.
7048                if (pkg.libraryNames != null) {
7049                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7050                        String name = pkg.libraryNames.get(i);
7051                        boolean allowed = false;
7052                        if (pkg.isUpdatedSystemApp()) {
7053                            // New library entries can only be added through the
7054                            // system image.  This is important to get rid of a lot
7055                            // of nasty edge cases: for example if we allowed a non-
7056                            // system update of the app to add a library, then uninstalling
7057                            // the update would make the library go away, and assumptions
7058                            // we made such as through app install filtering would now
7059                            // have allowed apps on the device which aren't compatible
7060                            // with it.  Better to just have the restriction here, be
7061                            // conservative, and create many fewer cases that can negatively
7062                            // impact the user experience.
7063                            final PackageSetting sysPs = mSettings
7064                                    .getDisabledSystemPkgLPr(pkg.packageName);
7065                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7066                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7067                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7068                                        allowed = true;
7069                                        break;
7070                                    }
7071                                }
7072                            }
7073                        } else {
7074                            allowed = true;
7075                        }
7076                        if (allowed) {
7077                            if (!mSharedLibraries.containsKey(name)) {
7078                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7079                            } else if (!name.equals(pkg.packageName)) {
7080                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7081                                        + name + " already exists; skipping");
7082                            }
7083                        } else {
7084                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7085                                    + name + " that is not declared on system image; skipping");
7086                        }
7087                    }
7088                    if ((scanFlags & SCAN_BOOTING) == 0) {
7089                        // If we are not booting, we need to update any applications
7090                        // that are clients of our shared library.  If we are booting,
7091                        // this will all be done once the scan is complete.
7092                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7093                    }
7094                }
7095            }
7096        }
7097
7098        // Request the ActivityManager to kill the process(only for existing packages)
7099        // so that we do not end up in a confused state while the user is still using the older
7100        // version of the application while the new one gets installed.
7101        if ((scanFlags & SCAN_REPLACING) != 0) {
7102            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7103
7104            killApplication(pkg.applicationInfo.packageName,
7105                        pkg.applicationInfo.uid, "replace pkg");
7106
7107            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7108        }
7109
7110        // Also need to kill any apps that are dependent on the library.
7111        if (clientLibPkgs != null) {
7112            for (int i=0; i<clientLibPkgs.size(); i++) {
7113                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7114                killApplication(clientPkg.applicationInfo.packageName,
7115                        clientPkg.applicationInfo.uid, "update lib");
7116            }
7117        }
7118
7119        // Make sure we're not adding any bogus keyset info
7120        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7121        ksms.assertScannedPackageValid(pkg);
7122
7123        // writer
7124        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7125
7126        boolean createIdmapFailed = false;
7127        synchronized (mPackages) {
7128            // We don't expect installation to fail beyond this point
7129
7130            // Add the new setting to mSettings
7131            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7132            // Add the new setting to mPackages
7133            mPackages.put(pkg.applicationInfo.packageName, pkg);
7134            // Make sure we don't accidentally delete its data.
7135            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7136            while (iter.hasNext()) {
7137                PackageCleanItem item = iter.next();
7138                if (pkgName.equals(item.packageName)) {
7139                    iter.remove();
7140                }
7141            }
7142
7143            // Take care of first install / last update times.
7144            if (currentTime != 0) {
7145                if (pkgSetting.firstInstallTime == 0) {
7146                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7147                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7148                    pkgSetting.lastUpdateTime = currentTime;
7149                }
7150            } else if (pkgSetting.firstInstallTime == 0) {
7151                // We need *something*.  Take time time stamp of the file.
7152                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7153            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7154                if (scanFileTime != pkgSetting.timeStamp) {
7155                    // A package on the system image has changed; consider this
7156                    // to be an update.
7157                    pkgSetting.lastUpdateTime = scanFileTime;
7158                }
7159            }
7160
7161            // Add the package's KeySets to the global KeySetManagerService
7162            ksms.addScannedPackageLPw(pkg);
7163
7164            int N = pkg.providers.size();
7165            StringBuilder r = null;
7166            int i;
7167            for (i=0; i<N; i++) {
7168                PackageParser.Provider p = pkg.providers.get(i);
7169                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7170                        p.info.processName, pkg.applicationInfo.uid);
7171                mProviders.addProvider(p);
7172                p.syncable = p.info.isSyncable;
7173                if (p.info.authority != null) {
7174                    String names[] = p.info.authority.split(";");
7175                    p.info.authority = null;
7176                    for (int j = 0; j < names.length; j++) {
7177                        if (j == 1 && p.syncable) {
7178                            // We only want the first authority for a provider to possibly be
7179                            // syncable, so if we already added this provider using a different
7180                            // authority clear the syncable flag. We copy the provider before
7181                            // changing it because the mProviders object contains a reference
7182                            // to a provider that we don't want to change.
7183                            // Only do this for the second authority since the resulting provider
7184                            // object can be the same for all future authorities for this provider.
7185                            p = new PackageParser.Provider(p);
7186                            p.syncable = false;
7187                        }
7188                        if (!mProvidersByAuthority.containsKey(names[j])) {
7189                            mProvidersByAuthority.put(names[j], p);
7190                            if (p.info.authority == null) {
7191                                p.info.authority = names[j];
7192                            } else {
7193                                p.info.authority = p.info.authority + ";" + names[j];
7194                            }
7195                            if (DEBUG_PACKAGE_SCANNING) {
7196                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7197                                    Log.d(TAG, "Registered content provider: " + names[j]
7198                                            + ", className = " + p.info.name + ", isSyncable = "
7199                                            + p.info.isSyncable);
7200                            }
7201                        } else {
7202                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7203                            Slog.w(TAG, "Skipping provider name " + names[j] +
7204                                    " (in package " + pkg.applicationInfo.packageName +
7205                                    "): name already used by "
7206                                    + ((other != null && other.getComponentName() != null)
7207                                            ? other.getComponentName().getPackageName() : "?"));
7208                        }
7209                    }
7210                }
7211                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7212                    if (r == null) {
7213                        r = new StringBuilder(256);
7214                    } else {
7215                        r.append(' ');
7216                    }
7217                    r.append(p.info.name);
7218                }
7219            }
7220            if (r != null) {
7221                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7222            }
7223
7224            N = pkg.services.size();
7225            r = null;
7226            for (i=0; i<N; i++) {
7227                PackageParser.Service s = pkg.services.get(i);
7228                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7229                        s.info.processName, pkg.applicationInfo.uid);
7230                mServices.addService(s);
7231                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7232                    if (r == null) {
7233                        r = new StringBuilder(256);
7234                    } else {
7235                        r.append(' ');
7236                    }
7237                    r.append(s.info.name);
7238                }
7239            }
7240            if (r != null) {
7241                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7242            }
7243
7244            N = pkg.receivers.size();
7245            r = null;
7246            for (i=0; i<N; i++) {
7247                PackageParser.Activity a = pkg.receivers.get(i);
7248                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7249                        a.info.processName, pkg.applicationInfo.uid);
7250                mReceivers.addActivity(a, "receiver");
7251                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7252                    if (r == null) {
7253                        r = new StringBuilder(256);
7254                    } else {
7255                        r.append(' ');
7256                    }
7257                    r.append(a.info.name);
7258                }
7259            }
7260            if (r != null) {
7261                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7262            }
7263
7264            N = pkg.activities.size();
7265            r = null;
7266            for (i=0; i<N; i++) {
7267                PackageParser.Activity a = pkg.activities.get(i);
7268                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7269                        a.info.processName, pkg.applicationInfo.uid);
7270                mActivities.addActivity(a, "activity");
7271                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7272                    if (r == null) {
7273                        r = new StringBuilder(256);
7274                    } else {
7275                        r.append(' ');
7276                    }
7277                    r.append(a.info.name);
7278                }
7279            }
7280            if (r != null) {
7281                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7282            }
7283
7284            N = pkg.permissionGroups.size();
7285            r = null;
7286            for (i=0; i<N; i++) {
7287                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7288                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7289                if (cur == null) {
7290                    mPermissionGroups.put(pg.info.name, pg);
7291                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7292                        if (r == null) {
7293                            r = new StringBuilder(256);
7294                        } else {
7295                            r.append(' ');
7296                        }
7297                        r.append(pg.info.name);
7298                    }
7299                } else {
7300                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7301                            + pg.info.packageName + " ignored: original from "
7302                            + cur.info.packageName);
7303                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7304                        if (r == null) {
7305                            r = new StringBuilder(256);
7306                        } else {
7307                            r.append(' ');
7308                        }
7309                        r.append("DUP:");
7310                        r.append(pg.info.name);
7311                    }
7312                }
7313            }
7314            if (r != null) {
7315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7316            }
7317
7318            N = pkg.permissions.size();
7319            r = null;
7320            for (i=0; i<N; i++) {
7321                PackageParser.Permission p = pkg.permissions.get(i);
7322
7323                // Assume by default that we did not install this permission into the system.
7324                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7325
7326                // Now that permission groups have a special meaning, we ignore permission
7327                // groups for legacy apps to prevent unexpected behavior. In particular,
7328                // permissions for one app being granted to someone just becuase they happen
7329                // to be in a group defined by another app (before this had no implications).
7330                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7331                    p.group = mPermissionGroups.get(p.info.group);
7332                    // Warn for a permission in an unknown group.
7333                    if (p.info.group != null && p.group == null) {
7334                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7335                                + p.info.packageName + " in an unknown group " + p.info.group);
7336                    }
7337                }
7338
7339                ArrayMap<String, BasePermission> permissionMap =
7340                        p.tree ? mSettings.mPermissionTrees
7341                                : mSettings.mPermissions;
7342                BasePermission bp = permissionMap.get(p.info.name);
7343
7344                // Allow system apps to redefine non-system permissions
7345                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7346                    final boolean currentOwnerIsSystem = (bp.perm != null
7347                            && isSystemApp(bp.perm.owner));
7348                    if (isSystemApp(p.owner)) {
7349                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7350                            // It's a built-in permission and no owner, take ownership now
7351                            bp.packageSetting = pkgSetting;
7352                            bp.perm = p;
7353                            bp.uid = pkg.applicationInfo.uid;
7354                            bp.sourcePackage = p.info.packageName;
7355                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7356                        } else if (!currentOwnerIsSystem) {
7357                            String msg = "New decl " + p.owner + " of permission  "
7358                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7359                            reportSettingsProblem(Log.WARN, msg);
7360                            bp = null;
7361                        }
7362                    }
7363                }
7364
7365                if (bp == null) {
7366                    bp = new BasePermission(p.info.name, p.info.packageName,
7367                            BasePermission.TYPE_NORMAL);
7368                    permissionMap.put(p.info.name, bp);
7369                }
7370
7371                if (bp.perm == null) {
7372                    if (bp.sourcePackage == null
7373                            || bp.sourcePackage.equals(p.info.packageName)) {
7374                        BasePermission tree = findPermissionTreeLP(p.info.name);
7375                        if (tree == null
7376                                || tree.sourcePackage.equals(p.info.packageName)) {
7377                            bp.packageSetting = pkgSetting;
7378                            bp.perm = p;
7379                            bp.uid = pkg.applicationInfo.uid;
7380                            bp.sourcePackage = p.info.packageName;
7381                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7382                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7383                                if (r == null) {
7384                                    r = new StringBuilder(256);
7385                                } else {
7386                                    r.append(' ');
7387                                }
7388                                r.append(p.info.name);
7389                            }
7390                        } else {
7391                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7392                                    + p.info.packageName + " ignored: base tree "
7393                                    + tree.name + " is from package "
7394                                    + tree.sourcePackage);
7395                        }
7396                    } else {
7397                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7398                                + p.info.packageName + " ignored: original from "
7399                                + bp.sourcePackage);
7400                    }
7401                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7402                    if (r == null) {
7403                        r = new StringBuilder(256);
7404                    } else {
7405                        r.append(' ');
7406                    }
7407                    r.append("DUP:");
7408                    r.append(p.info.name);
7409                }
7410                if (bp.perm == p) {
7411                    bp.protectionLevel = p.info.protectionLevel;
7412                }
7413            }
7414
7415            if (r != null) {
7416                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7417            }
7418
7419            N = pkg.instrumentation.size();
7420            r = null;
7421            for (i=0; i<N; i++) {
7422                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7423                a.info.packageName = pkg.applicationInfo.packageName;
7424                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7425                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7426                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7427                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7428                a.info.dataDir = pkg.applicationInfo.dataDir;
7429                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7430                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7431
7432                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7433                // need other information about the application, like the ABI and what not ?
7434                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7435                mInstrumentation.put(a.getComponentName(), a);
7436                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7437                    if (r == null) {
7438                        r = new StringBuilder(256);
7439                    } else {
7440                        r.append(' ');
7441                    }
7442                    r.append(a.info.name);
7443                }
7444            }
7445            if (r != null) {
7446                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7447            }
7448
7449            if (pkg.protectedBroadcasts != null) {
7450                N = pkg.protectedBroadcasts.size();
7451                for (i=0; i<N; i++) {
7452                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7453                }
7454            }
7455
7456            pkgSetting.setTimeStamp(scanFileTime);
7457
7458            // Create idmap files for pairs of (packages, overlay packages).
7459            // Note: "android", ie framework-res.apk, is handled by native layers.
7460            if (pkg.mOverlayTarget != null) {
7461                // This is an overlay package.
7462                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7463                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7464                        mOverlays.put(pkg.mOverlayTarget,
7465                                new ArrayMap<String, PackageParser.Package>());
7466                    }
7467                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7468                    map.put(pkg.packageName, pkg);
7469                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7470                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7471                        createIdmapFailed = true;
7472                    }
7473                }
7474            } else if (mOverlays.containsKey(pkg.packageName) &&
7475                    !pkg.packageName.equals("android")) {
7476                // This is a regular package, with one or more known overlay packages.
7477                createIdmapsForPackageLI(pkg);
7478            }
7479        }
7480
7481        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7482
7483        if (createIdmapFailed) {
7484            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7485                    "scanPackageLI failed to createIdmap");
7486        }
7487        return pkg;
7488    }
7489
7490    /**
7491     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7492     * is derived purely on the basis of the contents of {@code scanFile} and
7493     * {@code cpuAbiOverride}.
7494     *
7495     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7496     */
7497    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7498                                 String cpuAbiOverride, boolean extractLibs)
7499            throws PackageManagerException {
7500        // TODO: We can probably be smarter about this stuff. For installed apps,
7501        // we can calculate this information at install time once and for all. For
7502        // system apps, we can probably assume that this information doesn't change
7503        // after the first boot scan. As things stand, we do lots of unnecessary work.
7504
7505        // Give ourselves some initial paths; we'll come back for another
7506        // pass once we've determined ABI below.
7507        setNativeLibraryPaths(pkg);
7508
7509        // We would never need to extract libs for forward-locked and external packages,
7510        // since the container service will do it for us. We shouldn't attempt to
7511        // extract libs from system app when it was not updated.
7512        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7513                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7514            extractLibs = false;
7515        }
7516
7517        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7518        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7519
7520        NativeLibraryHelper.Handle handle = null;
7521        try {
7522            handle = NativeLibraryHelper.Handle.create(pkg);
7523            // TODO(multiArch): This can be null for apps that didn't go through the
7524            // usual installation process. We can calculate it again, like we
7525            // do during install time.
7526            //
7527            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7528            // unnecessary.
7529            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7530
7531            // Null out the abis so that they can be recalculated.
7532            pkg.applicationInfo.primaryCpuAbi = null;
7533            pkg.applicationInfo.secondaryCpuAbi = null;
7534            if (isMultiArch(pkg.applicationInfo)) {
7535                // Warn if we've set an abiOverride for multi-lib packages..
7536                // By definition, we need to copy both 32 and 64 bit libraries for
7537                // such packages.
7538                if (pkg.cpuAbiOverride != null
7539                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7540                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7541                }
7542
7543                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7544                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7545                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7546                    if (extractLibs) {
7547                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7548                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7549                                useIsaSpecificSubdirs);
7550                    } else {
7551                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7552                    }
7553                }
7554
7555                maybeThrowExceptionForMultiArchCopy(
7556                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7557
7558                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7559                    if (extractLibs) {
7560                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7561                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7562                                useIsaSpecificSubdirs);
7563                    } else {
7564                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7565                    }
7566                }
7567
7568                maybeThrowExceptionForMultiArchCopy(
7569                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7570
7571                if (abi64 >= 0) {
7572                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7573                }
7574
7575                if (abi32 >= 0) {
7576                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7577                    if (abi64 >= 0) {
7578                        pkg.applicationInfo.secondaryCpuAbi = abi;
7579                    } else {
7580                        pkg.applicationInfo.primaryCpuAbi = abi;
7581                    }
7582                }
7583            } else {
7584                String[] abiList = (cpuAbiOverride != null) ?
7585                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7586
7587                // Enable gross and lame hacks for apps that are built with old
7588                // SDK tools. We must scan their APKs for renderscript bitcode and
7589                // not launch them if it's present. Don't bother checking on devices
7590                // that don't have 64 bit support.
7591                boolean needsRenderScriptOverride = false;
7592                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7593                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7594                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7595                    needsRenderScriptOverride = true;
7596                }
7597
7598                final int copyRet;
7599                if (extractLibs) {
7600                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7601                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7602                } else {
7603                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7604                }
7605
7606                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7607                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7608                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7609                }
7610
7611                if (copyRet >= 0) {
7612                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7613                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7614                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7615                } else if (needsRenderScriptOverride) {
7616                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7617                }
7618            }
7619        } catch (IOException ioe) {
7620            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7621        } finally {
7622            IoUtils.closeQuietly(handle);
7623        }
7624
7625        // Now that we've calculated the ABIs and determined if it's an internal app,
7626        // we will go ahead and populate the nativeLibraryPath.
7627        setNativeLibraryPaths(pkg);
7628    }
7629
7630    /**
7631     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7632     * i.e, so that all packages can be run inside a single process if required.
7633     *
7634     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7635     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7636     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7637     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7638     * updating a package that belongs to a shared user.
7639     *
7640     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7641     * adds unnecessary complexity.
7642     */
7643    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7644            PackageParser.Package scannedPackage, boolean bootComplete) {
7645        String requiredInstructionSet = null;
7646        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7647            requiredInstructionSet = VMRuntime.getInstructionSet(
7648                     scannedPackage.applicationInfo.primaryCpuAbi);
7649        }
7650
7651        PackageSetting requirer = null;
7652        for (PackageSetting ps : packagesForUser) {
7653            // If packagesForUser contains scannedPackage, we skip it. This will happen
7654            // when scannedPackage is an update of an existing package. Without this check,
7655            // we will never be able to change the ABI of any package belonging to a shared
7656            // user, even if it's compatible with other packages.
7657            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7658                if (ps.primaryCpuAbiString == null) {
7659                    continue;
7660                }
7661
7662                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7663                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7664                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7665                    // this but there's not much we can do.
7666                    String errorMessage = "Instruction set mismatch, "
7667                            + ((requirer == null) ? "[caller]" : requirer)
7668                            + " requires " + requiredInstructionSet + " whereas " + ps
7669                            + " requires " + instructionSet;
7670                    Slog.w(TAG, errorMessage);
7671                }
7672
7673                if (requiredInstructionSet == null) {
7674                    requiredInstructionSet = instructionSet;
7675                    requirer = ps;
7676                }
7677            }
7678        }
7679
7680        if (requiredInstructionSet != null) {
7681            String adjustedAbi;
7682            if (requirer != null) {
7683                // requirer != null implies that either scannedPackage was null or that scannedPackage
7684                // did not require an ABI, in which case we have to adjust scannedPackage to match
7685                // the ABI of the set (which is the same as requirer's ABI)
7686                adjustedAbi = requirer.primaryCpuAbiString;
7687                if (scannedPackage != null) {
7688                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7689                }
7690            } else {
7691                // requirer == null implies that we're updating all ABIs in the set to
7692                // match scannedPackage.
7693                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7694            }
7695
7696            for (PackageSetting ps : packagesForUser) {
7697                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7698                    if (ps.primaryCpuAbiString != null) {
7699                        continue;
7700                    }
7701
7702                    ps.primaryCpuAbiString = adjustedAbi;
7703                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7704                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7705                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7706                        mInstaller.rmdex(ps.codePathString,
7707                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7708                    }
7709                }
7710            }
7711        }
7712    }
7713
7714    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7715        synchronized (mPackages) {
7716            mResolverReplaced = true;
7717            // Set up information for custom user intent resolution activity.
7718            mResolveActivity.applicationInfo = pkg.applicationInfo;
7719            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7720            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7721            mResolveActivity.processName = pkg.applicationInfo.packageName;
7722            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7723            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7724                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7725            mResolveActivity.theme = 0;
7726            mResolveActivity.exported = true;
7727            mResolveActivity.enabled = true;
7728            mResolveInfo.activityInfo = mResolveActivity;
7729            mResolveInfo.priority = 0;
7730            mResolveInfo.preferredOrder = 0;
7731            mResolveInfo.match = 0;
7732            mResolveComponentName = mCustomResolverComponentName;
7733            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7734                    mResolveComponentName);
7735        }
7736    }
7737
7738    private static String calculateBundledApkRoot(final String codePathString) {
7739        final File codePath = new File(codePathString);
7740        final File codeRoot;
7741        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7742            codeRoot = Environment.getRootDirectory();
7743        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7744            codeRoot = Environment.getOemDirectory();
7745        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7746            codeRoot = Environment.getVendorDirectory();
7747        } else {
7748            // Unrecognized code path; take its top real segment as the apk root:
7749            // e.g. /something/app/blah.apk => /something
7750            try {
7751                File f = codePath.getCanonicalFile();
7752                File parent = f.getParentFile();    // non-null because codePath is a file
7753                File tmp;
7754                while ((tmp = parent.getParentFile()) != null) {
7755                    f = parent;
7756                    parent = tmp;
7757                }
7758                codeRoot = f;
7759                Slog.w(TAG, "Unrecognized code path "
7760                        + codePath + " - using " + codeRoot);
7761            } catch (IOException e) {
7762                // Can't canonicalize the code path -- shenanigans?
7763                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7764                return Environment.getRootDirectory().getPath();
7765            }
7766        }
7767        return codeRoot.getPath();
7768    }
7769
7770    /**
7771     * Derive and set the location of native libraries for the given package,
7772     * which varies depending on where and how the package was installed.
7773     */
7774    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7775        final ApplicationInfo info = pkg.applicationInfo;
7776        final String codePath = pkg.codePath;
7777        final File codeFile = new File(codePath);
7778        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7779        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7780
7781        info.nativeLibraryRootDir = null;
7782        info.nativeLibraryRootRequiresIsa = false;
7783        info.nativeLibraryDir = null;
7784        info.secondaryNativeLibraryDir = null;
7785
7786        if (isApkFile(codeFile)) {
7787            // Monolithic install
7788            if (bundledApp) {
7789                // If "/system/lib64/apkname" exists, assume that is the per-package
7790                // native library directory to use; otherwise use "/system/lib/apkname".
7791                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7792                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7793                        getPrimaryInstructionSet(info));
7794
7795                // This is a bundled system app so choose the path based on the ABI.
7796                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7797                // is just the default path.
7798                final String apkName = deriveCodePathName(codePath);
7799                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7800                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7801                        apkName).getAbsolutePath();
7802
7803                if (info.secondaryCpuAbi != null) {
7804                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7805                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7806                            secondaryLibDir, apkName).getAbsolutePath();
7807                }
7808            } else if (asecApp) {
7809                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7810                        .getAbsolutePath();
7811            } else {
7812                final String apkName = deriveCodePathName(codePath);
7813                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7814                        .getAbsolutePath();
7815            }
7816
7817            info.nativeLibraryRootRequiresIsa = false;
7818            info.nativeLibraryDir = info.nativeLibraryRootDir;
7819        } else {
7820            // Cluster install
7821            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7822            info.nativeLibraryRootRequiresIsa = true;
7823
7824            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7825                    getPrimaryInstructionSet(info)).getAbsolutePath();
7826
7827            if (info.secondaryCpuAbi != null) {
7828                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7829                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7830            }
7831        }
7832    }
7833
7834    /**
7835     * Calculate the abis and roots for a bundled app. These can uniquely
7836     * be determined from the contents of the system partition, i.e whether
7837     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7838     * of this information, and instead assume that the system was built
7839     * sensibly.
7840     */
7841    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7842                                           PackageSetting pkgSetting) {
7843        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7844
7845        // If "/system/lib64/apkname" exists, assume that is the per-package
7846        // native library directory to use; otherwise use "/system/lib/apkname".
7847        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7848        setBundledAppAbi(pkg, apkRoot, apkName);
7849        // pkgSetting might be null during rescan following uninstall of updates
7850        // to a bundled app, so accommodate that possibility.  The settings in
7851        // that case will be established later from the parsed package.
7852        //
7853        // If the settings aren't null, sync them up with what we've just derived.
7854        // note that apkRoot isn't stored in the package settings.
7855        if (pkgSetting != null) {
7856            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7857            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7858        }
7859    }
7860
7861    /**
7862     * Deduces the ABI of a bundled app and sets the relevant fields on the
7863     * parsed pkg object.
7864     *
7865     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7866     *        under which system libraries are installed.
7867     * @param apkName the name of the installed package.
7868     */
7869    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7870        final File codeFile = new File(pkg.codePath);
7871
7872        final boolean has64BitLibs;
7873        final boolean has32BitLibs;
7874        if (isApkFile(codeFile)) {
7875            // Monolithic install
7876            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7877            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7878        } else {
7879            // Cluster install
7880            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7881            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7882                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7883                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7884                has64BitLibs = (new File(rootDir, isa)).exists();
7885            } else {
7886                has64BitLibs = false;
7887            }
7888            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7889                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7890                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7891                has32BitLibs = (new File(rootDir, isa)).exists();
7892            } else {
7893                has32BitLibs = false;
7894            }
7895        }
7896
7897        if (has64BitLibs && !has32BitLibs) {
7898            // The package has 64 bit libs, but not 32 bit libs. Its primary
7899            // ABI should be 64 bit. We can safely assume here that the bundled
7900            // native libraries correspond to the most preferred ABI in the list.
7901
7902            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7903            pkg.applicationInfo.secondaryCpuAbi = null;
7904        } else if (has32BitLibs && !has64BitLibs) {
7905            // The package has 32 bit libs but not 64 bit libs. Its primary
7906            // ABI should be 32 bit.
7907
7908            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7909            pkg.applicationInfo.secondaryCpuAbi = null;
7910        } else if (has32BitLibs && has64BitLibs) {
7911            // The application has both 64 and 32 bit bundled libraries. We check
7912            // here that the app declares multiArch support, and warn if it doesn't.
7913            //
7914            // We will be lenient here and record both ABIs. The primary will be the
7915            // ABI that's higher on the list, i.e, a device that's configured to prefer
7916            // 64 bit apps will see a 64 bit primary ABI,
7917
7918            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7919                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7920            }
7921
7922            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7923                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7924                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7925            } else {
7926                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7927                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7928            }
7929        } else {
7930            pkg.applicationInfo.primaryCpuAbi = null;
7931            pkg.applicationInfo.secondaryCpuAbi = null;
7932        }
7933    }
7934
7935    private void killApplication(String pkgName, int appId, String reason) {
7936        // Request the ActivityManager to kill the process(only for existing packages)
7937        // so that we do not end up in a confused state while the user is still using the older
7938        // version of the application while the new one gets installed.
7939        IActivityManager am = ActivityManagerNative.getDefault();
7940        if (am != null) {
7941            try {
7942                am.killApplicationWithAppId(pkgName, appId, reason);
7943            } catch (RemoteException e) {
7944            }
7945        }
7946    }
7947
7948    void removePackageLI(PackageSetting ps, boolean chatty) {
7949        if (DEBUG_INSTALL) {
7950            if (chatty)
7951                Log.d(TAG, "Removing package " + ps.name);
7952        }
7953
7954        // writer
7955        synchronized (mPackages) {
7956            mPackages.remove(ps.name);
7957            final PackageParser.Package pkg = ps.pkg;
7958            if (pkg != null) {
7959                cleanPackageDataStructuresLILPw(pkg, chatty);
7960            }
7961        }
7962    }
7963
7964    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7965        if (DEBUG_INSTALL) {
7966            if (chatty)
7967                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7968        }
7969
7970        // writer
7971        synchronized (mPackages) {
7972            mPackages.remove(pkg.applicationInfo.packageName);
7973            cleanPackageDataStructuresLILPw(pkg, chatty);
7974        }
7975    }
7976
7977    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7978        int N = pkg.providers.size();
7979        StringBuilder r = null;
7980        int i;
7981        for (i=0; i<N; i++) {
7982            PackageParser.Provider p = pkg.providers.get(i);
7983            mProviders.removeProvider(p);
7984            if (p.info.authority == null) {
7985
7986                /* There was another ContentProvider with this authority when
7987                 * this app was installed so this authority is null,
7988                 * Ignore it as we don't have to unregister the provider.
7989                 */
7990                continue;
7991            }
7992            String names[] = p.info.authority.split(";");
7993            for (int j = 0; j < names.length; j++) {
7994                if (mProvidersByAuthority.get(names[j]) == p) {
7995                    mProvidersByAuthority.remove(names[j]);
7996                    if (DEBUG_REMOVE) {
7997                        if (chatty)
7998                            Log.d(TAG, "Unregistered content provider: " + names[j]
7999                                    + ", className = " + p.info.name + ", isSyncable = "
8000                                    + p.info.isSyncable);
8001                    }
8002                }
8003            }
8004            if (DEBUG_REMOVE && chatty) {
8005                if (r == null) {
8006                    r = new StringBuilder(256);
8007                } else {
8008                    r.append(' ');
8009                }
8010                r.append(p.info.name);
8011            }
8012        }
8013        if (r != null) {
8014            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8015        }
8016
8017        N = pkg.services.size();
8018        r = null;
8019        for (i=0; i<N; i++) {
8020            PackageParser.Service s = pkg.services.get(i);
8021            mServices.removeService(s);
8022            if (chatty) {
8023                if (r == null) {
8024                    r = new StringBuilder(256);
8025                } else {
8026                    r.append(' ');
8027                }
8028                r.append(s.info.name);
8029            }
8030        }
8031        if (r != null) {
8032            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8033        }
8034
8035        N = pkg.receivers.size();
8036        r = null;
8037        for (i=0; i<N; i++) {
8038            PackageParser.Activity a = pkg.receivers.get(i);
8039            mReceivers.removeActivity(a, "receiver");
8040            if (DEBUG_REMOVE && chatty) {
8041                if (r == null) {
8042                    r = new StringBuilder(256);
8043                } else {
8044                    r.append(' ');
8045                }
8046                r.append(a.info.name);
8047            }
8048        }
8049        if (r != null) {
8050            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8051        }
8052
8053        N = pkg.activities.size();
8054        r = null;
8055        for (i=0; i<N; i++) {
8056            PackageParser.Activity a = pkg.activities.get(i);
8057            mActivities.removeActivity(a, "activity");
8058            if (DEBUG_REMOVE && chatty) {
8059                if (r == null) {
8060                    r = new StringBuilder(256);
8061                } else {
8062                    r.append(' ');
8063                }
8064                r.append(a.info.name);
8065            }
8066        }
8067        if (r != null) {
8068            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8069        }
8070
8071        N = pkg.permissions.size();
8072        r = null;
8073        for (i=0; i<N; i++) {
8074            PackageParser.Permission p = pkg.permissions.get(i);
8075            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8076            if (bp == null) {
8077                bp = mSettings.mPermissionTrees.get(p.info.name);
8078            }
8079            if (bp != null && bp.perm == p) {
8080                bp.perm = null;
8081                if (DEBUG_REMOVE && chatty) {
8082                    if (r == null) {
8083                        r = new StringBuilder(256);
8084                    } else {
8085                        r.append(' ');
8086                    }
8087                    r.append(p.info.name);
8088                }
8089            }
8090            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8091                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8092                if (appOpPerms != null) {
8093                    appOpPerms.remove(pkg.packageName);
8094                }
8095            }
8096        }
8097        if (r != null) {
8098            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8099        }
8100
8101        N = pkg.requestedPermissions.size();
8102        r = null;
8103        for (i=0; i<N; i++) {
8104            String perm = pkg.requestedPermissions.get(i);
8105            BasePermission bp = mSettings.mPermissions.get(perm);
8106            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8107                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8108                if (appOpPerms != null) {
8109                    appOpPerms.remove(pkg.packageName);
8110                    if (appOpPerms.isEmpty()) {
8111                        mAppOpPermissionPackages.remove(perm);
8112                    }
8113                }
8114            }
8115        }
8116        if (r != null) {
8117            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8118        }
8119
8120        N = pkg.instrumentation.size();
8121        r = null;
8122        for (i=0; i<N; i++) {
8123            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8124            mInstrumentation.remove(a.getComponentName());
8125            if (DEBUG_REMOVE && chatty) {
8126                if (r == null) {
8127                    r = new StringBuilder(256);
8128                } else {
8129                    r.append(' ');
8130                }
8131                r.append(a.info.name);
8132            }
8133        }
8134        if (r != null) {
8135            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8136        }
8137
8138        r = null;
8139        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8140            // Only system apps can hold shared libraries.
8141            if (pkg.libraryNames != null) {
8142                for (i=0; i<pkg.libraryNames.size(); i++) {
8143                    String name = pkg.libraryNames.get(i);
8144                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8145                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8146                        mSharedLibraries.remove(name);
8147                        if (DEBUG_REMOVE && chatty) {
8148                            if (r == null) {
8149                                r = new StringBuilder(256);
8150                            } else {
8151                                r.append(' ');
8152                            }
8153                            r.append(name);
8154                        }
8155                    }
8156                }
8157            }
8158        }
8159        if (r != null) {
8160            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8161        }
8162    }
8163
8164    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8165        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8166            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8167                return true;
8168            }
8169        }
8170        return false;
8171    }
8172
8173    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8174    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8175    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8176
8177    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8178            int flags) {
8179        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8180        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8181    }
8182
8183    private void updatePermissionsLPw(String changingPkg,
8184            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8185        // Make sure there are no dangling permission trees.
8186        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8187        while (it.hasNext()) {
8188            final BasePermission bp = it.next();
8189            if (bp.packageSetting == null) {
8190                // We may not yet have parsed the package, so just see if
8191                // we still know about its settings.
8192                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8193            }
8194            if (bp.packageSetting == null) {
8195                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8196                        + " from package " + bp.sourcePackage);
8197                it.remove();
8198            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8199                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8200                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8201                            + " from package " + bp.sourcePackage);
8202                    flags |= UPDATE_PERMISSIONS_ALL;
8203                    it.remove();
8204                }
8205            }
8206        }
8207
8208        // Make sure all dynamic permissions have been assigned to a package,
8209        // and make sure there are no dangling permissions.
8210        it = mSettings.mPermissions.values().iterator();
8211        while (it.hasNext()) {
8212            final BasePermission bp = it.next();
8213            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8214                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8215                        + bp.name + " pkg=" + bp.sourcePackage
8216                        + " info=" + bp.pendingInfo);
8217                if (bp.packageSetting == null && bp.pendingInfo != null) {
8218                    final BasePermission tree = findPermissionTreeLP(bp.name);
8219                    if (tree != null && tree.perm != null) {
8220                        bp.packageSetting = tree.packageSetting;
8221                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8222                                new PermissionInfo(bp.pendingInfo));
8223                        bp.perm.info.packageName = tree.perm.info.packageName;
8224                        bp.perm.info.name = bp.name;
8225                        bp.uid = tree.uid;
8226                    }
8227                }
8228            }
8229            if (bp.packageSetting == null) {
8230                // We may not yet have parsed the package, so just see if
8231                // we still know about its settings.
8232                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8233            }
8234            if (bp.packageSetting == null) {
8235                Slog.w(TAG, "Removing dangling permission: " + bp.name
8236                        + " from package " + bp.sourcePackage);
8237                it.remove();
8238            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8239                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8240                    Slog.i(TAG, "Removing old permission: " + bp.name
8241                            + " from package " + bp.sourcePackage);
8242                    flags |= UPDATE_PERMISSIONS_ALL;
8243                    it.remove();
8244                }
8245            }
8246        }
8247
8248        // Now update the permissions for all packages, in particular
8249        // replace the granted permissions of the system packages.
8250        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8251            for (PackageParser.Package pkg : mPackages.values()) {
8252                if (pkg != pkgInfo) {
8253                    // Only replace for packages on requested volume
8254                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8255                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8256                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8257                    grantPermissionsLPw(pkg, replace, changingPkg);
8258                }
8259            }
8260        }
8261
8262        if (pkgInfo != null) {
8263            // Only replace for packages on requested volume
8264            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8265            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8266                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8267            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8268        }
8269    }
8270
8271    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8272            String packageOfInterest) {
8273        // IMPORTANT: There are two types of permissions: install and runtime.
8274        // Install time permissions are granted when the app is installed to
8275        // all device users and users added in the future. Runtime permissions
8276        // are granted at runtime explicitly to specific users. Normal and signature
8277        // protected permissions are install time permissions. Dangerous permissions
8278        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8279        // otherwise they are runtime permissions. This function does not manage
8280        // runtime permissions except for the case an app targeting Lollipop MR1
8281        // being upgraded to target a newer SDK, in which case dangerous permissions
8282        // are transformed from install time to runtime ones.
8283
8284        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8285        if (ps == null) {
8286            return;
8287        }
8288
8289        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8290
8291        PermissionsState permissionsState = ps.getPermissionsState();
8292        PermissionsState origPermissions = permissionsState;
8293
8294        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8295
8296        boolean runtimePermissionsRevoked = false;
8297        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8298
8299        boolean changedInstallPermission = false;
8300
8301        if (replace) {
8302            ps.installPermissionsFixed = false;
8303            if (!ps.isSharedUser()) {
8304                origPermissions = new PermissionsState(permissionsState);
8305                permissionsState.reset();
8306            } else {
8307                // We need to know only about runtime permission changes since the
8308                // calling code always writes the install permissions state but
8309                // the runtime ones are written only if changed. The only cases of
8310                // changed runtime permissions here are promotion of an install to
8311                // runtime and revocation of a runtime from a shared user.
8312                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8313                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8314                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8315                    runtimePermissionsRevoked = true;
8316                }
8317            }
8318        }
8319
8320        permissionsState.setGlobalGids(mGlobalGids);
8321
8322        final int N = pkg.requestedPermissions.size();
8323        for (int i=0; i<N; i++) {
8324            final String name = pkg.requestedPermissions.get(i);
8325            final BasePermission bp = mSettings.mPermissions.get(name);
8326
8327            if (DEBUG_INSTALL) {
8328                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8329            }
8330
8331            if (bp == null || bp.packageSetting == null) {
8332                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8333                    Slog.w(TAG, "Unknown permission " + name
8334                            + " in package " + pkg.packageName);
8335                }
8336                continue;
8337            }
8338
8339            final String perm = bp.name;
8340            boolean allowedSig = false;
8341            int grant = GRANT_DENIED;
8342
8343            // Keep track of app op permissions.
8344            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8345                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8346                if (pkgs == null) {
8347                    pkgs = new ArraySet<>();
8348                    mAppOpPermissionPackages.put(bp.name, pkgs);
8349                }
8350                pkgs.add(pkg.packageName);
8351            }
8352
8353            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8354            switch (level) {
8355                case PermissionInfo.PROTECTION_NORMAL: {
8356                    // For all apps normal permissions are install time ones.
8357                    grant = GRANT_INSTALL;
8358                } break;
8359
8360                case PermissionInfo.PROTECTION_DANGEROUS: {
8361                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8362                        // For legacy apps dangerous permissions are install time ones.
8363                        grant = GRANT_INSTALL_LEGACY;
8364                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8365                        // For legacy apps that became modern, install becomes runtime.
8366                        grant = GRANT_UPGRADE;
8367                    } else if (mPromoteSystemApps
8368                            && isSystemApp(ps)
8369                            && mExistingSystemPackages.contains(ps.name)) {
8370                        // For legacy system apps, install becomes runtime.
8371                        // We cannot check hasInstallPermission() for system apps since those
8372                        // permissions were granted implicitly and not persisted pre-M.
8373                        grant = GRANT_UPGRADE;
8374                    } else {
8375                        // For modern apps keep runtime permissions unchanged.
8376                        grant = GRANT_RUNTIME;
8377                    }
8378                } break;
8379
8380                case PermissionInfo.PROTECTION_SIGNATURE: {
8381                    // For all apps signature permissions are install time ones.
8382                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8383                    if (allowedSig) {
8384                        grant = GRANT_INSTALL;
8385                    }
8386                } break;
8387            }
8388
8389            if (DEBUG_INSTALL) {
8390                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8391            }
8392
8393            if (grant != GRANT_DENIED) {
8394                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8395                    // If this is an existing, non-system package, then
8396                    // we can't add any new permissions to it.
8397                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8398                        // Except...  if this is a permission that was added
8399                        // to the platform (note: need to only do this when
8400                        // updating the platform).
8401                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8402                            grant = GRANT_DENIED;
8403                        }
8404                    }
8405                }
8406
8407                switch (grant) {
8408                    case GRANT_INSTALL: {
8409                        // Revoke this as runtime permission to handle the case of
8410                        // a runtime permission being downgraded to an install one.
8411                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8412                            if (origPermissions.getRuntimePermissionState(
8413                                    bp.name, userId) != null) {
8414                                // Revoke the runtime permission and clear the flags.
8415                                origPermissions.revokeRuntimePermission(bp, userId);
8416                                origPermissions.updatePermissionFlags(bp, userId,
8417                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8418                                // If we revoked a permission permission, we have to write.
8419                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8420                                        changedRuntimePermissionUserIds, userId);
8421                            }
8422                        }
8423                        // Grant an install permission.
8424                        if (permissionsState.grantInstallPermission(bp) !=
8425                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8426                            changedInstallPermission = true;
8427                        }
8428                    } break;
8429
8430                    case GRANT_INSTALL_LEGACY: {
8431                        // Grant an install permission.
8432                        if (permissionsState.grantInstallPermission(bp) !=
8433                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8434                            changedInstallPermission = true;
8435                        }
8436                    } break;
8437
8438                    case GRANT_RUNTIME: {
8439                        // Grant previously granted runtime permissions.
8440                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8441                            PermissionState permissionState = origPermissions
8442                                    .getRuntimePermissionState(bp.name, userId);
8443                            final int flags = permissionState != null
8444                                    ? permissionState.getFlags() : 0;
8445                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8446                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8447                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8448                                    // If we cannot put the permission as it was, we have to write.
8449                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8450                                            changedRuntimePermissionUserIds, userId);
8451                                }
8452                            }
8453                            // Propagate the permission flags.
8454                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8455                        }
8456                    } break;
8457
8458                    case GRANT_UPGRADE: {
8459                        // Grant runtime permissions for a previously held install permission.
8460                        PermissionState permissionState = origPermissions
8461                                .getInstallPermissionState(bp.name);
8462                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8463
8464                        if (origPermissions.revokeInstallPermission(bp)
8465                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8466                            // We will be transferring the permission flags, so clear them.
8467                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8468                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8469                            changedInstallPermission = true;
8470                        }
8471
8472                        // If the permission is not to be promoted to runtime we ignore it and
8473                        // also its other flags as they are not applicable to install permissions.
8474                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8475                            for (int userId : currentUserIds) {
8476                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8477                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8478                                    // Transfer the permission flags.
8479                                    permissionsState.updatePermissionFlags(bp, userId,
8480                                            flags, flags);
8481                                    // If we granted the permission, we have to write.
8482                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8483                                            changedRuntimePermissionUserIds, userId);
8484                                }
8485                            }
8486                        }
8487                    } break;
8488
8489                    default: {
8490                        if (packageOfInterest == null
8491                                || packageOfInterest.equals(pkg.packageName)) {
8492                            Slog.w(TAG, "Not granting permission " + perm
8493                                    + " to package " + pkg.packageName
8494                                    + " because it was previously installed without");
8495                        }
8496                    } break;
8497                }
8498            } else {
8499                if (permissionsState.revokeInstallPermission(bp) !=
8500                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8501                    // Also drop the permission flags.
8502                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8503                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8504                    changedInstallPermission = true;
8505                    Slog.i(TAG, "Un-granting permission " + perm
8506                            + " from package " + pkg.packageName
8507                            + " (protectionLevel=" + bp.protectionLevel
8508                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8509                            + ")");
8510                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8511                    // Don't print warning for app op permissions, since it is fine for them
8512                    // not to be granted, there is a UI for the user to decide.
8513                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8514                        Slog.w(TAG, "Not granting permission " + perm
8515                                + " to package " + pkg.packageName
8516                                + " (protectionLevel=" + bp.protectionLevel
8517                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8518                                + ")");
8519                    }
8520                }
8521            }
8522        }
8523
8524        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8525                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8526            // This is the first that we have heard about this package, so the
8527            // permissions we have now selected are fixed until explicitly
8528            // changed.
8529            ps.installPermissionsFixed = true;
8530        }
8531
8532        // Persist the runtime permissions state for users with changes. If permissions
8533        // were revoked because no app in the shared user declares them we have to
8534        // write synchronously to avoid losing runtime permissions state.
8535        for (int userId : changedRuntimePermissionUserIds) {
8536            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8537        }
8538
8539        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8540    }
8541
8542    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8543        boolean allowed = false;
8544        final int NP = PackageParser.NEW_PERMISSIONS.length;
8545        for (int ip=0; ip<NP; ip++) {
8546            final PackageParser.NewPermissionInfo npi
8547                    = PackageParser.NEW_PERMISSIONS[ip];
8548            if (npi.name.equals(perm)
8549                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8550                allowed = true;
8551                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8552                        + pkg.packageName);
8553                break;
8554            }
8555        }
8556        return allowed;
8557    }
8558
8559    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8560            BasePermission bp, PermissionsState origPermissions) {
8561        boolean allowed;
8562        allowed = (compareSignatures(
8563                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8564                        == PackageManager.SIGNATURE_MATCH)
8565                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8566                        == PackageManager.SIGNATURE_MATCH);
8567        if (!allowed && (bp.protectionLevel
8568                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8569            if (isSystemApp(pkg)) {
8570                // For updated system applications, a system permission
8571                // is granted only if it had been defined by the original application.
8572                if (pkg.isUpdatedSystemApp()) {
8573                    final PackageSetting sysPs = mSettings
8574                            .getDisabledSystemPkgLPr(pkg.packageName);
8575                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8576                        // If the original was granted this permission, we take
8577                        // that grant decision as read and propagate it to the
8578                        // update.
8579                        if (sysPs.isPrivileged()) {
8580                            allowed = true;
8581                        }
8582                    } else {
8583                        // The system apk may have been updated with an older
8584                        // version of the one on the data partition, but which
8585                        // granted a new system permission that it didn't have
8586                        // before.  In this case we do want to allow the app to
8587                        // now get the new permission if the ancestral apk is
8588                        // privileged to get it.
8589                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8590                            for (int j=0;
8591                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8592                                if (perm.equals(
8593                                        sysPs.pkg.requestedPermissions.get(j))) {
8594                                    allowed = true;
8595                                    break;
8596                                }
8597                            }
8598                        }
8599                    }
8600                } else {
8601                    allowed = isPrivilegedApp(pkg);
8602                }
8603            }
8604        }
8605        if (!allowed) {
8606            if (!allowed && (bp.protectionLevel
8607                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8608                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8609                // If this was a previously normal/dangerous permission that got moved
8610                // to a system permission as part of the runtime permission redesign, then
8611                // we still want to blindly grant it to old apps.
8612                allowed = true;
8613            }
8614            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8615                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8616                // If this permission is to be granted to the system installer and
8617                // this app is an installer, then it gets the permission.
8618                allowed = true;
8619            }
8620            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8621                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8622                // If this permission is to be granted to the system verifier and
8623                // this app is a verifier, then it gets the permission.
8624                allowed = true;
8625            }
8626            if (!allowed && (bp.protectionLevel
8627                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8628                    && isSystemApp(pkg)) {
8629                // Any pre-installed system app is allowed to get this permission.
8630                allowed = true;
8631            }
8632            if (!allowed && (bp.protectionLevel
8633                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8634                // For development permissions, a development permission
8635                // is granted only if it was already granted.
8636                allowed = origPermissions.hasInstallPermission(perm);
8637            }
8638        }
8639        return allowed;
8640    }
8641
8642    final class ActivityIntentResolver
8643            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8644        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8645                boolean defaultOnly, int userId) {
8646            if (!sUserManager.exists(userId)) return null;
8647            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8648            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8649        }
8650
8651        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8652                int userId) {
8653            if (!sUserManager.exists(userId)) return null;
8654            mFlags = flags;
8655            return super.queryIntent(intent, resolvedType,
8656                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8657        }
8658
8659        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8660                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8661            if (!sUserManager.exists(userId)) return null;
8662            if (packageActivities == null) {
8663                return null;
8664            }
8665            mFlags = flags;
8666            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8667            final int N = packageActivities.size();
8668            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8669                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8670
8671            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8672            for (int i = 0; i < N; ++i) {
8673                intentFilters = packageActivities.get(i).intents;
8674                if (intentFilters != null && intentFilters.size() > 0) {
8675                    PackageParser.ActivityIntentInfo[] array =
8676                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8677                    intentFilters.toArray(array);
8678                    listCut.add(array);
8679                }
8680            }
8681            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8682        }
8683
8684        public final void addActivity(PackageParser.Activity a, String type) {
8685            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8686            mActivities.put(a.getComponentName(), a);
8687            if (DEBUG_SHOW_INFO)
8688                Log.v(
8689                TAG, "  " + type + " " +
8690                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8691            if (DEBUG_SHOW_INFO)
8692                Log.v(TAG, "    Class=" + a.info.name);
8693            final int NI = a.intents.size();
8694            for (int j=0; j<NI; j++) {
8695                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8696                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8697                    intent.setPriority(0);
8698                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8699                            + a.className + " with priority > 0, forcing to 0");
8700                }
8701                if (DEBUG_SHOW_INFO) {
8702                    Log.v(TAG, "    IntentFilter:");
8703                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8704                }
8705                if (!intent.debugCheck()) {
8706                    Log.w(TAG, "==> For Activity " + a.info.name);
8707                }
8708                addFilter(intent);
8709            }
8710        }
8711
8712        public final void removeActivity(PackageParser.Activity a, String type) {
8713            mActivities.remove(a.getComponentName());
8714            if (DEBUG_SHOW_INFO) {
8715                Log.v(TAG, "  " + type + " "
8716                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8717                                : a.info.name) + ":");
8718                Log.v(TAG, "    Class=" + a.info.name);
8719            }
8720            final int NI = a.intents.size();
8721            for (int j=0; j<NI; j++) {
8722                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8723                if (DEBUG_SHOW_INFO) {
8724                    Log.v(TAG, "    IntentFilter:");
8725                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8726                }
8727                removeFilter(intent);
8728            }
8729        }
8730
8731        @Override
8732        protected boolean allowFilterResult(
8733                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8734            ActivityInfo filterAi = filter.activity.info;
8735            for (int i=dest.size()-1; i>=0; i--) {
8736                ActivityInfo destAi = dest.get(i).activityInfo;
8737                if (destAi.name == filterAi.name
8738                        && destAi.packageName == filterAi.packageName) {
8739                    return false;
8740                }
8741            }
8742            return true;
8743        }
8744
8745        @Override
8746        protected ActivityIntentInfo[] newArray(int size) {
8747            return new ActivityIntentInfo[size];
8748        }
8749
8750        @Override
8751        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8752            if (!sUserManager.exists(userId)) return true;
8753            PackageParser.Package p = filter.activity.owner;
8754            if (p != null) {
8755                PackageSetting ps = (PackageSetting)p.mExtras;
8756                if (ps != null) {
8757                    // System apps are never considered stopped for purposes of
8758                    // filtering, because there may be no way for the user to
8759                    // actually re-launch them.
8760                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8761                            && ps.getStopped(userId);
8762                }
8763            }
8764            return false;
8765        }
8766
8767        @Override
8768        protected boolean isPackageForFilter(String packageName,
8769                PackageParser.ActivityIntentInfo info) {
8770            return packageName.equals(info.activity.owner.packageName);
8771        }
8772
8773        @Override
8774        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8775                int match, int userId) {
8776            if (!sUserManager.exists(userId)) return null;
8777            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
8778                return null;
8779            }
8780            final PackageParser.Activity activity = info.activity;
8781            if (mSafeMode && (activity.info.applicationInfo.flags
8782                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8783                return null;
8784            }
8785            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8786            if (ps == null) {
8787                return null;
8788            }
8789            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8790                    ps.readUserState(userId), userId);
8791            if (ai == null) {
8792                return null;
8793            }
8794            final ResolveInfo res = new ResolveInfo();
8795            res.activityInfo = ai;
8796            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8797                res.filter = info;
8798            }
8799            if (info != null) {
8800                res.handleAllWebDataURI = info.handleAllWebDataURI();
8801            }
8802            res.priority = info.getPriority();
8803            res.preferredOrder = activity.owner.mPreferredOrder;
8804            //System.out.println("Result: " + res.activityInfo.className +
8805            //                   " = " + res.priority);
8806            res.match = match;
8807            res.isDefault = info.hasDefault;
8808            res.labelRes = info.labelRes;
8809            res.nonLocalizedLabel = info.nonLocalizedLabel;
8810            if (userNeedsBadging(userId)) {
8811                res.noResourceId = true;
8812            } else {
8813                res.icon = info.icon;
8814            }
8815            res.iconResourceId = info.icon;
8816            res.system = res.activityInfo.applicationInfo.isSystemApp();
8817            return res;
8818        }
8819
8820        @Override
8821        protected void sortResults(List<ResolveInfo> results) {
8822            Collections.sort(results, mResolvePrioritySorter);
8823        }
8824
8825        @Override
8826        protected void dumpFilter(PrintWriter out, String prefix,
8827                PackageParser.ActivityIntentInfo filter) {
8828            out.print(prefix); out.print(
8829                    Integer.toHexString(System.identityHashCode(filter.activity)));
8830                    out.print(' ');
8831                    filter.activity.printComponentShortName(out);
8832                    out.print(" filter ");
8833                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8834        }
8835
8836        @Override
8837        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8838            return filter.activity;
8839        }
8840
8841        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8842            PackageParser.Activity activity = (PackageParser.Activity)label;
8843            out.print(prefix); out.print(
8844                    Integer.toHexString(System.identityHashCode(activity)));
8845                    out.print(' ');
8846                    activity.printComponentShortName(out);
8847            if (count > 1) {
8848                out.print(" ("); out.print(count); out.print(" filters)");
8849            }
8850            out.println();
8851        }
8852
8853//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8854//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8855//            final List<ResolveInfo> retList = Lists.newArrayList();
8856//            while (i.hasNext()) {
8857//                final ResolveInfo resolveInfo = i.next();
8858//                if (isEnabledLP(resolveInfo.activityInfo)) {
8859//                    retList.add(resolveInfo);
8860//                }
8861//            }
8862//            return retList;
8863//        }
8864
8865        // Keys are String (activity class name), values are Activity.
8866        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8867                = new ArrayMap<ComponentName, PackageParser.Activity>();
8868        private int mFlags;
8869    }
8870
8871    private final class ServiceIntentResolver
8872            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8873        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8874                boolean defaultOnly, int userId) {
8875            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8876            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8877        }
8878
8879        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8880                int userId) {
8881            if (!sUserManager.exists(userId)) return null;
8882            mFlags = flags;
8883            return super.queryIntent(intent, resolvedType,
8884                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8885        }
8886
8887        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8888                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8889            if (!sUserManager.exists(userId)) return null;
8890            if (packageServices == null) {
8891                return null;
8892            }
8893            mFlags = flags;
8894            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8895            final int N = packageServices.size();
8896            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8897                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8898
8899            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8900            for (int i = 0; i < N; ++i) {
8901                intentFilters = packageServices.get(i).intents;
8902                if (intentFilters != null && intentFilters.size() > 0) {
8903                    PackageParser.ServiceIntentInfo[] array =
8904                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8905                    intentFilters.toArray(array);
8906                    listCut.add(array);
8907                }
8908            }
8909            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8910        }
8911
8912        public final void addService(PackageParser.Service s) {
8913            mServices.put(s.getComponentName(), s);
8914            if (DEBUG_SHOW_INFO) {
8915                Log.v(TAG, "  "
8916                        + (s.info.nonLocalizedLabel != null
8917                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8918                Log.v(TAG, "    Class=" + s.info.name);
8919            }
8920            final int NI = s.intents.size();
8921            int j;
8922            for (j=0; j<NI; j++) {
8923                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8924                if (DEBUG_SHOW_INFO) {
8925                    Log.v(TAG, "    IntentFilter:");
8926                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8927                }
8928                if (!intent.debugCheck()) {
8929                    Log.w(TAG, "==> For Service " + s.info.name);
8930                }
8931                addFilter(intent);
8932            }
8933        }
8934
8935        public final void removeService(PackageParser.Service s) {
8936            mServices.remove(s.getComponentName());
8937            if (DEBUG_SHOW_INFO) {
8938                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8939                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8940                Log.v(TAG, "    Class=" + s.info.name);
8941            }
8942            final int NI = s.intents.size();
8943            int j;
8944            for (j=0; j<NI; j++) {
8945                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8946                if (DEBUG_SHOW_INFO) {
8947                    Log.v(TAG, "    IntentFilter:");
8948                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8949                }
8950                removeFilter(intent);
8951            }
8952        }
8953
8954        @Override
8955        protected boolean allowFilterResult(
8956                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8957            ServiceInfo filterSi = filter.service.info;
8958            for (int i=dest.size()-1; i>=0; i--) {
8959                ServiceInfo destAi = dest.get(i).serviceInfo;
8960                if (destAi.name == filterSi.name
8961                        && destAi.packageName == filterSi.packageName) {
8962                    return false;
8963                }
8964            }
8965            return true;
8966        }
8967
8968        @Override
8969        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8970            return new PackageParser.ServiceIntentInfo[size];
8971        }
8972
8973        @Override
8974        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8975            if (!sUserManager.exists(userId)) return true;
8976            PackageParser.Package p = filter.service.owner;
8977            if (p != null) {
8978                PackageSetting ps = (PackageSetting)p.mExtras;
8979                if (ps != null) {
8980                    // System apps are never considered stopped for purposes of
8981                    // filtering, because there may be no way for the user to
8982                    // actually re-launch them.
8983                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8984                            && ps.getStopped(userId);
8985                }
8986            }
8987            return false;
8988        }
8989
8990        @Override
8991        protected boolean isPackageForFilter(String packageName,
8992                PackageParser.ServiceIntentInfo info) {
8993            return packageName.equals(info.service.owner.packageName);
8994        }
8995
8996        @Override
8997        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8998                int match, int userId) {
8999            if (!sUserManager.exists(userId)) return null;
9000            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9001            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9002                return null;
9003            }
9004            final PackageParser.Service service = info.service;
9005            if (mSafeMode && (service.info.applicationInfo.flags
9006                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9007                return null;
9008            }
9009            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9010            if (ps == null) {
9011                return null;
9012            }
9013            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9014                    ps.readUserState(userId), userId);
9015            if (si == null) {
9016                return null;
9017            }
9018            final ResolveInfo res = new ResolveInfo();
9019            res.serviceInfo = si;
9020            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9021                res.filter = filter;
9022            }
9023            res.priority = info.getPriority();
9024            res.preferredOrder = service.owner.mPreferredOrder;
9025            res.match = match;
9026            res.isDefault = info.hasDefault;
9027            res.labelRes = info.labelRes;
9028            res.nonLocalizedLabel = info.nonLocalizedLabel;
9029            res.icon = info.icon;
9030            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9031            return res;
9032        }
9033
9034        @Override
9035        protected void sortResults(List<ResolveInfo> results) {
9036            Collections.sort(results, mResolvePrioritySorter);
9037        }
9038
9039        @Override
9040        protected void dumpFilter(PrintWriter out, String prefix,
9041                PackageParser.ServiceIntentInfo filter) {
9042            out.print(prefix); out.print(
9043                    Integer.toHexString(System.identityHashCode(filter.service)));
9044                    out.print(' ');
9045                    filter.service.printComponentShortName(out);
9046                    out.print(" filter ");
9047                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9048        }
9049
9050        @Override
9051        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9052            return filter.service;
9053        }
9054
9055        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9056            PackageParser.Service service = (PackageParser.Service)label;
9057            out.print(prefix); out.print(
9058                    Integer.toHexString(System.identityHashCode(service)));
9059                    out.print(' ');
9060                    service.printComponentShortName(out);
9061            if (count > 1) {
9062                out.print(" ("); out.print(count); out.print(" filters)");
9063            }
9064            out.println();
9065        }
9066
9067//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9068//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9069//            final List<ResolveInfo> retList = Lists.newArrayList();
9070//            while (i.hasNext()) {
9071//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9072//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9073//                    retList.add(resolveInfo);
9074//                }
9075//            }
9076//            return retList;
9077//        }
9078
9079        // Keys are String (activity class name), values are Activity.
9080        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9081                = new ArrayMap<ComponentName, PackageParser.Service>();
9082        private int mFlags;
9083    };
9084
9085    private final class ProviderIntentResolver
9086            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9087        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9088                boolean defaultOnly, int userId) {
9089            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9090            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9091        }
9092
9093        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9094                int userId) {
9095            if (!sUserManager.exists(userId))
9096                return null;
9097            mFlags = flags;
9098            return super.queryIntent(intent, resolvedType,
9099                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9100        }
9101
9102        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9103                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9104            if (!sUserManager.exists(userId))
9105                return null;
9106            if (packageProviders == null) {
9107                return null;
9108            }
9109            mFlags = flags;
9110            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9111            final int N = packageProviders.size();
9112            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9113                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9114
9115            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9116            for (int i = 0; i < N; ++i) {
9117                intentFilters = packageProviders.get(i).intents;
9118                if (intentFilters != null && intentFilters.size() > 0) {
9119                    PackageParser.ProviderIntentInfo[] array =
9120                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9121                    intentFilters.toArray(array);
9122                    listCut.add(array);
9123                }
9124            }
9125            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9126        }
9127
9128        public final void addProvider(PackageParser.Provider p) {
9129            if (mProviders.containsKey(p.getComponentName())) {
9130                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9131                return;
9132            }
9133
9134            mProviders.put(p.getComponentName(), p);
9135            if (DEBUG_SHOW_INFO) {
9136                Log.v(TAG, "  "
9137                        + (p.info.nonLocalizedLabel != null
9138                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9139                Log.v(TAG, "    Class=" + p.info.name);
9140            }
9141            final int NI = p.intents.size();
9142            int j;
9143            for (j = 0; j < NI; j++) {
9144                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9145                if (DEBUG_SHOW_INFO) {
9146                    Log.v(TAG, "    IntentFilter:");
9147                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9148                }
9149                if (!intent.debugCheck()) {
9150                    Log.w(TAG, "==> For Provider " + p.info.name);
9151                }
9152                addFilter(intent);
9153            }
9154        }
9155
9156        public final void removeProvider(PackageParser.Provider p) {
9157            mProviders.remove(p.getComponentName());
9158            if (DEBUG_SHOW_INFO) {
9159                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9160                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9161                Log.v(TAG, "    Class=" + p.info.name);
9162            }
9163            final int NI = p.intents.size();
9164            int j;
9165            for (j = 0; j < NI; j++) {
9166                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9167                if (DEBUG_SHOW_INFO) {
9168                    Log.v(TAG, "    IntentFilter:");
9169                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9170                }
9171                removeFilter(intent);
9172            }
9173        }
9174
9175        @Override
9176        protected boolean allowFilterResult(
9177                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9178            ProviderInfo filterPi = filter.provider.info;
9179            for (int i = dest.size() - 1; i >= 0; i--) {
9180                ProviderInfo destPi = dest.get(i).providerInfo;
9181                if (destPi.name == filterPi.name
9182                        && destPi.packageName == filterPi.packageName) {
9183                    return false;
9184                }
9185            }
9186            return true;
9187        }
9188
9189        @Override
9190        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9191            return new PackageParser.ProviderIntentInfo[size];
9192        }
9193
9194        @Override
9195        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9196            if (!sUserManager.exists(userId))
9197                return true;
9198            PackageParser.Package p = filter.provider.owner;
9199            if (p != null) {
9200                PackageSetting ps = (PackageSetting) p.mExtras;
9201                if (ps != null) {
9202                    // System apps are never considered stopped for purposes of
9203                    // filtering, because there may be no way for the user to
9204                    // actually re-launch them.
9205                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9206                            && ps.getStopped(userId);
9207                }
9208            }
9209            return false;
9210        }
9211
9212        @Override
9213        protected boolean isPackageForFilter(String packageName,
9214                PackageParser.ProviderIntentInfo info) {
9215            return packageName.equals(info.provider.owner.packageName);
9216        }
9217
9218        @Override
9219        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9220                int match, int userId) {
9221            if (!sUserManager.exists(userId))
9222                return null;
9223            final PackageParser.ProviderIntentInfo info = filter;
9224            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9225                return null;
9226            }
9227            final PackageParser.Provider provider = info.provider;
9228            if (mSafeMode && (provider.info.applicationInfo.flags
9229                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9230                return null;
9231            }
9232            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9233            if (ps == null) {
9234                return null;
9235            }
9236            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9237                    ps.readUserState(userId), userId);
9238            if (pi == null) {
9239                return null;
9240            }
9241            final ResolveInfo res = new ResolveInfo();
9242            res.providerInfo = pi;
9243            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9244                res.filter = filter;
9245            }
9246            res.priority = info.getPriority();
9247            res.preferredOrder = provider.owner.mPreferredOrder;
9248            res.match = match;
9249            res.isDefault = info.hasDefault;
9250            res.labelRes = info.labelRes;
9251            res.nonLocalizedLabel = info.nonLocalizedLabel;
9252            res.icon = info.icon;
9253            res.system = res.providerInfo.applicationInfo.isSystemApp();
9254            return res;
9255        }
9256
9257        @Override
9258        protected void sortResults(List<ResolveInfo> results) {
9259            Collections.sort(results, mResolvePrioritySorter);
9260        }
9261
9262        @Override
9263        protected void dumpFilter(PrintWriter out, String prefix,
9264                PackageParser.ProviderIntentInfo filter) {
9265            out.print(prefix);
9266            out.print(
9267                    Integer.toHexString(System.identityHashCode(filter.provider)));
9268            out.print(' ');
9269            filter.provider.printComponentShortName(out);
9270            out.print(" filter ");
9271            out.println(Integer.toHexString(System.identityHashCode(filter)));
9272        }
9273
9274        @Override
9275        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9276            return filter.provider;
9277        }
9278
9279        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9280            PackageParser.Provider provider = (PackageParser.Provider)label;
9281            out.print(prefix); out.print(
9282                    Integer.toHexString(System.identityHashCode(provider)));
9283                    out.print(' ');
9284                    provider.printComponentShortName(out);
9285            if (count > 1) {
9286                out.print(" ("); out.print(count); out.print(" filters)");
9287            }
9288            out.println();
9289        }
9290
9291        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9292                = new ArrayMap<ComponentName, PackageParser.Provider>();
9293        private int mFlags;
9294    };
9295
9296    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9297            new Comparator<ResolveInfo>() {
9298        public int compare(ResolveInfo r1, ResolveInfo r2) {
9299            int v1 = r1.priority;
9300            int v2 = r2.priority;
9301            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9302            if (v1 != v2) {
9303                return (v1 > v2) ? -1 : 1;
9304            }
9305            v1 = r1.preferredOrder;
9306            v2 = r2.preferredOrder;
9307            if (v1 != v2) {
9308                return (v1 > v2) ? -1 : 1;
9309            }
9310            if (r1.isDefault != r2.isDefault) {
9311                return r1.isDefault ? -1 : 1;
9312            }
9313            v1 = r1.match;
9314            v2 = r2.match;
9315            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9316            if (v1 != v2) {
9317                return (v1 > v2) ? -1 : 1;
9318            }
9319            if (r1.system != r2.system) {
9320                return r1.system ? -1 : 1;
9321            }
9322            return 0;
9323        }
9324    };
9325
9326    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9327            new Comparator<ProviderInfo>() {
9328        public int compare(ProviderInfo p1, ProviderInfo p2) {
9329            final int v1 = p1.initOrder;
9330            final int v2 = p2.initOrder;
9331            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9332        }
9333    };
9334
9335    final void sendPackageBroadcast(final String action, final String pkg,
9336            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9337            final int[] userIds) {
9338        mHandler.post(new Runnable() {
9339            @Override
9340            public void run() {
9341                try {
9342                    final IActivityManager am = ActivityManagerNative.getDefault();
9343                    if (am == null) return;
9344                    final int[] resolvedUserIds;
9345                    if (userIds == null) {
9346                        resolvedUserIds = am.getRunningUserIds();
9347                    } else {
9348                        resolvedUserIds = userIds;
9349                    }
9350                    for (int id : resolvedUserIds) {
9351                        final Intent intent = new Intent(action,
9352                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9353                        if (extras != null) {
9354                            intent.putExtras(extras);
9355                        }
9356                        if (targetPkg != null) {
9357                            intent.setPackage(targetPkg);
9358                        }
9359                        // Modify the UID when posting to other users
9360                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9361                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9362                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9363                            intent.putExtra(Intent.EXTRA_UID, uid);
9364                        }
9365                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9366                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9367                        if (DEBUG_BROADCASTS) {
9368                            RuntimeException here = new RuntimeException("here");
9369                            here.fillInStackTrace();
9370                            Slog.d(TAG, "Sending to user " + id + ": "
9371                                    + intent.toShortString(false, true, false, false)
9372                                    + " " + intent.getExtras(), here);
9373                        }
9374                        am.broadcastIntent(null, intent, null, finishedReceiver,
9375                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9376                                null, finishedReceiver != null, false, id);
9377                    }
9378                } catch (RemoteException ex) {
9379                }
9380            }
9381        });
9382    }
9383
9384    /**
9385     * Check if the external storage media is available. This is true if there
9386     * is a mounted external storage medium or if the external storage is
9387     * emulated.
9388     */
9389    private boolean isExternalMediaAvailable() {
9390        return mMediaMounted || Environment.isExternalStorageEmulated();
9391    }
9392
9393    @Override
9394    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9395        // writer
9396        synchronized (mPackages) {
9397            if (!isExternalMediaAvailable()) {
9398                // If the external storage is no longer mounted at this point,
9399                // the caller may not have been able to delete all of this
9400                // packages files and can not delete any more.  Bail.
9401                return null;
9402            }
9403            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9404            if (lastPackage != null) {
9405                pkgs.remove(lastPackage);
9406            }
9407            if (pkgs.size() > 0) {
9408                return pkgs.get(0);
9409            }
9410        }
9411        return null;
9412    }
9413
9414    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9415        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9416                userId, andCode ? 1 : 0, packageName);
9417        if (mSystemReady) {
9418            msg.sendToTarget();
9419        } else {
9420            if (mPostSystemReadyMessages == null) {
9421                mPostSystemReadyMessages = new ArrayList<>();
9422            }
9423            mPostSystemReadyMessages.add(msg);
9424        }
9425    }
9426
9427    void startCleaningPackages() {
9428        // reader
9429        synchronized (mPackages) {
9430            if (!isExternalMediaAvailable()) {
9431                return;
9432            }
9433            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9434                return;
9435            }
9436        }
9437        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9438        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9439        IActivityManager am = ActivityManagerNative.getDefault();
9440        if (am != null) {
9441            try {
9442                am.startService(null, intent, null, mContext.getOpPackageName(),
9443                        UserHandle.USER_SYSTEM);
9444            } catch (RemoteException e) {
9445            }
9446        }
9447    }
9448
9449    @Override
9450    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9451            int installFlags, String installerPackageName, VerificationParams verificationParams,
9452            String packageAbiOverride) {
9453        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9454                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9455    }
9456
9457    @Override
9458    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9459            int installFlags, String installerPackageName, VerificationParams verificationParams,
9460            String packageAbiOverride, int userId) {
9461        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9462
9463        final int callingUid = Binder.getCallingUid();
9464        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9465
9466        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9467            try {
9468                if (observer != null) {
9469                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9470                }
9471            } catch (RemoteException re) {
9472            }
9473            return;
9474        }
9475
9476        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9477            installFlags |= PackageManager.INSTALL_FROM_ADB;
9478
9479        } else {
9480            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9481            // about installerPackageName.
9482
9483            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9484            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9485        }
9486
9487        UserHandle user;
9488        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9489            user = UserHandle.ALL;
9490        } else {
9491            user = new UserHandle(userId);
9492        }
9493
9494        // Only system components can circumvent runtime permissions when installing.
9495        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9496                && mContext.checkCallingOrSelfPermission(Manifest.permission
9497                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9498            throw new SecurityException("You need the "
9499                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9500                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9501        }
9502
9503        verificationParams.setInstallerUid(callingUid);
9504
9505        final File originFile = new File(originPath);
9506        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9507
9508        final Message msg = mHandler.obtainMessage(INIT_COPY);
9509        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9510                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9511        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9512        msg.obj = params;
9513
9514        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9515                System.identityHashCode(msg.obj));
9516        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9517                System.identityHashCode(msg.obj));
9518
9519        mHandler.sendMessage(msg);
9520    }
9521
9522    void installStage(String packageName, File stagedDir, String stagedCid,
9523            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9524            String installerPackageName, int installerUid, UserHandle user) {
9525        final VerificationParams verifParams = new VerificationParams(
9526                null, sessionParams.originatingUri, sessionParams.referrerUri,
9527                sessionParams.originatingUid, null);
9528        verifParams.setInstallerUid(installerUid);
9529
9530        final OriginInfo origin;
9531        if (stagedDir != null) {
9532            origin = OriginInfo.fromStagedFile(stagedDir);
9533        } else {
9534            origin = OriginInfo.fromStagedContainer(stagedCid);
9535        }
9536
9537        final Message msg = mHandler.obtainMessage(INIT_COPY);
9538        final InstallParams params = new InstallParams(origin, null, observer,
9539                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9540                verifParams, user, sessionParams.abiOverride,
9541                sessionParams.grantedRuntimePermissions);
9542        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9543        msg.obj = params;
9544
9545        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9546                System.identityHashCode(msg.obj));
9547        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9548                System.identityHashCode(msg.obj));
9549
9550        mHandler.sendMessage(msg);
9551    }
9552
9553    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9554        Bundle extras = new Bundle(1);
9555        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9556
9557        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9558                packageName, extras, null, null, new int[] {userId});
9559        try {
9560            IActivityManager am = ActivityManagerNative.getDefault();
9561            final boolean isSystem =
9562                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9563            if (isSystem && am.isUserRunning(userId, 0)) {
9564                // The just-installed/enabled app is bundled on the system, so presumed
9565                // to be able to run automatically without needing an explicit launch.
9566                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9567                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9568                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9569                        .setPackage(packageName);
9570                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9571                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9572            }
9573        } catch (RemoteException e) {
9574            // shouldn't happen
9575            Slog.w(TAG, "Unable to bootstrap installed package", e);
9576        }
9577    }
9578
9579    @Override
9580    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9581            int userId) {
9582        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9583        PackageSetting pkgSetting;
9584        final int uid = Binder.getCallingUid();
9585        enforceCrossUserPermission(uid, userId, true, true,
9586                "setApplicationHiddenSetting for user " + userId);
9587
9588        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9589            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9590            return false;
9591        }
9592
9593        long callingId = Binder.clearCallingIdentity();
9594        try {
9595            boolean sendAdded = false;
9596            boolean sendRemoved = false;
9597            // writer
9598            synchronized (mPackages) {
9599                pkgSetting = mSettings.mPackages.get(packageName);
9600                if (pkgSetting == null) {
9601                    return false;
9602                }
9603                if (pkgSetting.getHidden(userId) != hidden) {
9604                    pkgSetting.setHidden(hidden, userId);
9605                    mSettings.writePackageRestrictionsLPr(userId);
9606                    if (hidden) {
9607                        sendRemoved = true;
9608                    } else {
9609                        sendAdded = true;
9610                    }
9611                }
9612            }
9613            if (sendAdded) {
9614                sendPackageAddedForUser(packageName, pkgSetting, userId);
9615                return true;
9616            }
9617            if (sendRemoved) {
9618                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9619                        "hiding pkg");
9620                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9621                return true;
9622            }
9623        } finally {
9624            Binder.restoreCallingIdentity(callingId);
9625        }
9626        return false;
9627    }
9628
9629    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9630            int userId) {
9631        final PackageRemovedInfo info = new PackageRemovedInfo();
9632        info.removedPackage = packageName;
9633        info.removedUsers = new int[] {userId};
9634        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9635        info.sendBroadcast(false, false, false);
9636    }
9637
9638    /**
9639     * Returns true if application is not found or there was an error. Otherwise it returns
9640     * the hidden state of the package for the given user.
9641     */
9642    @Override
9643    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9644        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9645        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9646                false, "getApplicationHidden for user " + userId);
9647        PackageSetting pkgSetting;
9648        long callingId = Binder.clearCallingIdentity();
9649        try {
9650            // writer
9651            synchronized (mPackages) {
9652                pkgSetting = mSettings.mPackages.get(packageName);
9653                if (pkgSetting == null) {
9654                    return true;
9655                }
9656                return pkgSetting.getHidden(userId);
9657            }
9658        } finally {
9659            Binder.restoreCallingIdentity(callingId);
9660        }
9661    }
9662
9663    /**
9664     * @hide
9665     */
9666    @Override
9667    public int installExistingPackageAsUser(String packageName, int userId) {
9668        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9669                null);
9670        PackageSetting pkgSetting;
9671        final int uid = Binder.getCallingUid();
9672        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9673                + userId);
9674        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9675            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9676        }
9677
9678        long callingId = Binder.clearCallingIdentity();
9679        try {
9680            boolean sendAdded = false;
9681
9682            // writer
9683            synchronized (mPackages) {
9684                pkgSetting = mSettings.mPackages.get(packageName);
9685                if (pkgSetting == null) {
9686                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9687                }
9688                if (!pkgSetting.getInstalled(userId)) {
9689                    pkgSetting.setInstalled(true, userId);
9690                    pkgSetting.setHidden(false, userId);
9691                    mSettings.writePackageRestrictionsLPr(userId);
9692                    sendAdded = true;
9693                }
9694            }
9695
9696            if (sendAdded) {
9697                sendPackageAddedForUser(packageName, pkgSetting, userId);
9698            }
9699        } finally {
9700            Binder.restoreCallingIdentity(callingId);
9701        }
9702
9703        return PackageManager.INSTALL_SUCCEEDED;
9704    }
9705
9706    boolean isUserRestricted(int userId, String restrictionKey) {
9707        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9708        if (restrictions.getBoolean(restrictionKey, false)) {
9709            Log.w(TAG, "User is restricted: " + restrictionKey);
9710            return true;
9711        }
9712        return false;
9713    }
9714
9715    @Override
9716    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9717        mContext.enforceCallingOrSelfPermission(
9718                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9719                "Only package verification agents can verify applications");
9720
9721        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9722        final PackageVerificationResponse response = new PackageVerificationResponse(
9723                verificationCode, Binder.getCallingUid());
9724        msg.arg1 = id;
9725        msg.obj = response;
9726        mHandler.sendMessage(msg);
9727    }
9728
9729    @Override
9730    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9731            long millisecondsToDelay) {
9732        mContext.enforceCallingOrSelfPermission(
9733                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9734                "Only package verification agents can extend verification timeouts");
9735
9736        final PackageVerificationState state = mPendingVerification.get(id);
9737        final PackageVerificationResponse response = new PackageVerificationResponse(
9738                verificationCodeAtTimeout, Binder.getCallingUid());
9739
9740        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9741            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9742        }
9743        if (millisecondsToDelay < 0) {
9744            millisecondsToDelay = 0;
9745        }
9746        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9747                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9748            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9749        }
9750
9751        if ((state != null) && !state.timeoutExtended()) {
9752            state.extendTimeout();
9753
9754            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9755            msg.arg1 = id;
9756            msg.obj = response;
9757            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9758        }
9759    }
9760
9761    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9762            int verificationCode, UserHandle user) {
9763        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9764        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9765        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9766        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9767        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9768
9769        mContext.sendBroadcastAsUser(intent, user,
9770                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9771    }
9772
9773    private ComponentName matchComponentForVerifier(String packageName,
9774            List<ResolveInfo> receivers) {
9775        ActivityInfo targetReceiver = null;
9776
9777        final int NR = receivers.size();
9778        for (int i = 0; i < NR; i++) {
9779            final ResolveInfo info = receivers.get(i);
9780            if (info.activityInfo == null) {
9781                continue;
9782            }
9783
9784            if (packageName.equals(info.activityInfo.packageName)) {
9785                targetReceiver = info.activityInfo;
9786                break;
9787            }
9788        }
9789
9790        if (targetReceiver == null) {
9791            return null;
9792        }
9793
9794        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9795    }
9796
9797    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9798            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9799        if (pkgInfo.verifiers.length == 0) {
9800            return null;
9801        }
9802
9803        final int N = pkgInfo.verifiers.length;
9804        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9805        for (int i = 0; i < N; i++) {
9806            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9807
9808            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9809                    receivers);
9810            if (comp == null) {
9811                continue;
9812            }
9813
9814            final int verifierUid = getUidForVerifier(verifierInfo);
9815            if (verifierUid == -1) {
9816                continue;
9817            }
9818
9819            if (DEBUG_VERIFY) {
9820                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9821                        + " with the correct signature");
9822            }
9823            sufficientVerifiers.add(comp);
9824            verificationState.addSufficientVerifier(verifierUid);
9825        }
9826
9827        return sufficientVerifiers;
9828    }
9829
9830    private int getUidForVerifier(VerifierInfo verifierInfo) {
9831        synchronized (mPackages) {
9832            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9833            if (pkg == null) {
9834                return -1;
9835            } else if (pkg.mSignatures.length != 1) {
9836                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9837                        + " has more than one signature; ignoring");
9838                return -1;
9839            }
9840
9841            /*
9842             * If the public key of the package's signature does not match
9843             * our expected public key, then this is a different package and
9844             * we should skip.
9845             */
9846
9847            final byte[] expectedPublicKey;
9848            try {
9849                final Signature verifierSig = pkg.mSignatures[0];
9850                final PublicKey publicKey = verifierSig.getPublicKey();
9851                expectedPublicKey = publicKey.getEncoded();
9852            } catch (CertificateException e) {
9853                return -1;
9854            }
9855
9856            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9857
9858            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9859                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9860                        + " does not have the expected public key; ignoring");
9861                return -1;
9862            }
9863
9864            return pkg.applicationInfo.uid;
9865        }
9866    }
9867
9868    @Override
9869    public void finishPackageInstall(int token) {
9870        enforceSystemOrRoot("Only the system is allowed to finish installs");
9871
9872        if (DEBUG_INSTALL) {
9873            Slog.v(TAG, "BM finishing package install for " + token);
9874        }
9875        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
9876
9877        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9878        mHandler.sendMessage(msg);
9879    }
9880
9881    /**
9882     * Get the verification agent timeout.
9883     *
9884     * @return verification timeout in milliseconds
9885     */
9886    private long getVerificationTimeout() {
9887        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9888                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9889                DEFAULT_VERIFICATION_TIMEOUT);
9890    }
9891
9892    /**
9893     * Get the default verification agent response code.
9894     *
9895     * @return default verification response code
9896     */
9897    private int getDefaultVerificationResponse() {
9898        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9899                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9900                DEFAULT_VERIFICATION_RESPONSE);
9901    }
9902
9903    /**
9904     * Check whether or not package verification has been enabled.
9905     *
9906     * @return true if verification should be performed
9907     */
9908    private boolean isVerificationEnabled(int userId, int installFlags) {
9909        if (!DEFAULT_VERIFY_ENABLE) {
9910            return false;
9911        }
9912        // TODO: fix b/25118622; don't bypass verification
9913        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
9914            return false;
9915        }
9916
9917        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9918
9919        // Check if installing from ADB
9920        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9921            // Do not run verification in a test harness environment
9922            if (ActivityManager.isRunningInTestHarness()) {
9923                return false;
9924            }
9925            if (ensureVerifyAppsEnabled) {
9926                return true;
9927            }
9928            // Check if the developer does not want package verification for ADB installs
9929            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9930                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9931                return false;
9932            }
9933        }
9934
9935        if (ensureVerifyAppsEnabled) {
9936            return true;
9937        }
9938
9939        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9940                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9941    }
9942
9943    @Override
9944    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9945            throws RemoteException {
9946        mContext.enforceCallingOrSelfPermission(
9947                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9948                "Only intentfilter verification agents can verify applications");
9949
9950        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9951        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9952                Binder.getCallingUid(), verificationCode, failedDomains);
9953        msg.arg1 = id;
9954        msg.obj = response;
9955        mHandler.sendMessage(msg);
9956    }
9957
9958    @Override
9959    public int getIntentVerificationStatus(String packageName, int userId) {
9960        synchronized (mPackages) {
9961            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9962        }
9963    }
9964
9965    @Override
9966    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9967        mContext.enforceCallingOrSelfPermission(
9968                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9969
9970        boolean result = false;
9971        synchronized (mPackages) {
9972            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9973        }
9974        if (result) {
9975            scheduleWritePackageRestrictionsLocked(userId);
9976        }
9977        return result;
9978    }
9979
9980    @Override
9981    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9982        synchronized (mPackages) {
9983            return mSettings.getIntentFilterVerificationsLPr(packageName);
9984        }
9985    }
9986
9987    @Override
9988    public List<IntentFilter> getAllIntentFilters(String packageName) {
9989        if (TextUtils.isEmpty(packageName)) {
9990            return Collections.<IntentFilter>emptyList();
9991        }
9992        synchronized (mPackages) {
9993            PackageParser.Package pkg = mPackages.get(packageName);
9994            if (pkg == null || pkg.activities == null) {
9995                return Collections.<IntentFilter>emptyList();
9996            }
9997            final int count = pkg.activities.size();
9998            ArrayList<IntentFilter> result = new ArrayList<>();
9999            for (int n=0; n<count; n++) {
10000                PackageParser.Activity activity = pkg.activities.get(n);
10001                if (activity.intents != null || activity.intents.size() > 0) {
10002                    result.addAll(activity.intents);
10003                }
10004            }
10005            return result;
10006        }
10007    }
10008
10009    @Override
10010    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10011        mContext.enforceCallingOrSelfPermission(
10012                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10013
10014        synchronized (mPackages) {
10015            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10016            if (packageName != null) {
10017                result |= updateIntentVerificationStatus(packageName,
10018                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10019                        userId);
10020                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10021                        packageName, userId);
10022            }
10023            return result;
10024        }
10025    }
10026
10027    @Override
10028    public String getDefaultBrowserPackageName(int userId) {
10029        synchronized (mPackages) {
10030            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10031        }
10032    }
10033
10034    /**
10035     * Get the "allow unknown sources" setting.
10036     *
10037     * @return the current "allow unknown sources" setting
10038     */
10039    private int getUnknownSourcesSettings() {
10040        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10041                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10042                -1);
10043    }
10044
10045    @Override
10046    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10047        final int uid = Binder.getCallingUid();
10048        // writer
10049        synchronized (mPackages) {
10050            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10051            if (targetPackageSetting == null) {
10052                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10053            }
10054
10055            PackageSetting installerPackageSetting;
10056            if (installerPackageName != null) {
10057                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10058                if (installerPackageSetting == null) {
10059                    throw new IllegalArgumentException("Unknown installer package: "
10060                            + installerPackageName);
10061                }
10062            } else {
10063                installerPackageSetting = null;
10064            }
10065
10066            Signature[] callerSignature;
10067            Object obj = mSettings.getUserIdLPr(uid);
10068            if (obj != null) {
10069                if (obj instanceof SharedUserSetting) {
10070                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10071                } else if (obj instanceof PackageSetting) {
10072                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10073                } else {
10074                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10075                }
10076            } else {
10077                throw new SecurityException("Unknown calling uid " + uid);
10078            }
10079
10080            // Verify: can't set installerPackageName to a package that is
10081            // not signed with the same cert as the caller.
10082            if (installerPackageSetting != null) {
10083                if (compareSignatures(callerSignature,
10084                        installerPackageSetting.signatures.mSignatures)
10085                        != PackageManager.SIGNATURE_MATCH) {
10086                    throw new SecurityException(
10087                            "Caller does not have same cert as new installer package "
10088                            + installerPackageName);
10089                }
10090            }
10091
10092            // Verify: if target already has an installer package, it must
10093            // be signed with the same cert as the caller.
10094            if (targetPackageSetting.installerPackageName != null) {
10095                PackageSetting setting = mSettings.mPackages.get(
10096                        targetPackageSetting.installerPackageName);
10097                // If the currently set package isn't valid, then it's always
10098                // okay to change it.
10099                if (setting != null) {
10100                    if (compareSignatures(callerSignature,
10101                            setting.signatures.mSignatures)
10102                            != PackageManager.SIGNATURE_MATCH) {
10103                        throw new SecurityException(
10104                                "Caller does not have same cert as old installer package "
10105                                + targetPackageSetting.installerPackageName);
10106                    }
10107                }
10108            }
10109
10110            // Okay!
10111            targetPackageSetting.installerPackageName = installerPackageName;
10112            scheduleWriteSettingsLocked();
10113        }
10114    }
10115
10116    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10117        // Queue up an async operation since the package installation may take a little while.
10118        mHandler.post(new Runnable() {
10119            public void run() {
10120                mHandler.removeCallbacks(this);
10121                 // Result object to be returned
10122                PackageInstalledInfo res = new PackageInstalledInfo();
10123                res.returnCode = currentStatus;
10124                res.uid = -1;
10125                res.pkg = null;
10126                res.removedInfo = new PackageRemovedInfo();
10127                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10128                    args.doPreInstall(res.returnCode);
10129                    synchronized (mInstallLock) {
10130                        installPackageTracedLI(args, res);
10131                    }
10132                    args.doPostInstall(res.returnCode, res.uid);
10133                }
10134
10135                // A restore should be performed at this point if (a) the install
10136                // succeeded, (b) the operation is not an update, and (c) the new
10137                // package has not opted out of backup participation.
10138                final boolean update = res.removedInfo.removedPackage != null;
10139                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10140                boolean doRestore = !update
10141                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10142
10143                // Set up the post-install work request bookkeeping.  This will be used
10144                // and cleaned up by the post-install event handling regardless of whether
10145                // there's a restore pass performed.  Token values are >= 1.
10146                int token;
10147                if (mNextInstallToken < 0) mNextInstallToken = 1;
10148                token = mNextInstallToken++;
10149
10150                PostInstallData data = new PostInstallData(args, res);
10151                mRunningInstalls.put(token, data);
10152                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10153
10154                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10155                    // Pass responsibility to the Backup Manager.  It will perform a
10156                    // restore if appropriate, then pass responsibility back to the
10157                    // Package Manager to run the post-install observer callbacks
10158                    // and broadcasts.
10159                    IBackupManager bm = IBackupManager.Stub.asInterface(
10160                            ServiceManager.getService(Context.BACKUP_SERVICE));
10161                    if (bm != null) {
10162                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10163                                + " to BM for possible restore");
10164                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10165                        try {
10166                            // TODO: http://b/22388012
10167                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10168                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10169                            } else {
10170                                doRestore = false;
10171                            }
10172                        } catch (RemoteException e) {
10173                            // can't happen; the backup manager is local
10174                        } catch (Exception e) {
10175                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10176                            doRestore = false;
10177                        }
10178                    } else {
10179                        Slog.e(TAG, "Backup Manager not found!");
10180                        doRestore = false;
10181                    }
10182                }
10183
10184                if (!doRestore) {
10185                    // No restore possible, or the Backup Manager was mysteriously not
10186                    // available -- just fire the post-install work request directly.
10187                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10188
10189                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10190
10191                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10192                    mHandler.sendMessage(msg);
10193                }
10194            }
10195        });
10196    }
10197
10198    private abstract class HandlerParams {
10199        private static final int MAX_RETRIES = 4;
10200
10201        /**
10202         * Number of times startCopy() has been attempted and had a non-fatal
10203         * error.
10204         */
10205        private int mRetries = 0;
10206
10207        /** User handle for the user requesting the information or installation. */
10208        private final UserHandle mUser;
10209        String traceMethod;
10210        int traceCookie;
10211
10212        HandlerParams(UserHandle user) {
10213            mUser = user;
10214        }
10215
10216        UserHandle getUser() {
10217            return mUser;
10218        }
10219
10220        HandlerParams setTraceMethod(String traceMethod) {
10221            this.traceMethod = traceMethod;
10222            return this;
10223        }
10224
10225        HandlerParams setTraceCookie(int traceCookie) {
10226            this.traceCookie = traceCookie;
10227            return this;
10228        }
10229
10230        final boolean startCopy() {
10231            boolean res;
10232            try {
10233                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10234
10235                if (++mRetries > MAX_RETRIES) {
10236                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10237                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10238                    handleServiceError();
10239                    return false;
10240                } else {
10241                    handleStartCopy();
10242                    res = true;
10243                }
10244            } catch (RemoteException e) {
10245                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10246                mHandler.sendEmptyMessage(MCS_RECONNECT);
10247                res = false;
10248            }
10249            handleReturnCode();
10250            return res;
10251        }
10252
10253        final void serviceError() {
10254            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10255            handleServiceError();
10256            handleReturnCode();
10257        }
10258
10259        abstract void handleStartCopy() throws RemoteException;
10260        abstract void handleServiceError();
10261        abstract void handleReturnCode();
10262    }
10263
10264    class MeasureParams extends HandlerParams {
10265        private final PackageStats mStats;
10266        private boolean mSuccess;
10267
10268        private final IPackageStatsObserver mObserver;
10269
10270        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10271            super(new UserHandle(stats.userHandle));
10272            mObserver = observer;
10273            mStats = stats;
10274        }
10275
10276        @Override
10277        public String toString() {
10278            return "MeasureParams{"
10279                + Integer.toHexString(System.identityHashCode(this))
10280                + " " + mStats.packageName + "}";
10281        }
10282
10283        @Override
10284        void handleStartCopy() throws RemoteException {
10285            synchronized (mInstallLock) {
10286                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10287            }
10288
10289            if (mSuccess) {
10290                final boolean mounted;
10291                if (Environment.isExternalStorageEmulated()) {
10292                    mounted = true;
10293                } else {
10294                    final String status = Environment.getExternalStorageState();
10295                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10296                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10297                }
10298
10299                if (mounted) {
10300                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10301
10302                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10303                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10304
10305                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10306                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10307
10308                    // Always subtract cache size, since it's a subdirectory
10309                    mStats.externalDataSize -= mStats.externalCacheSize;
10310
10311                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10312                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10313
10314                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10315                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10316                }
10317            }
10318        }
10319
10320        @Override
10321        void handleReturnCode() {
10322            if (mObserver != null) {
10323                try {
10324                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10325                } catch (RemoteException e) {
10326                    Slog.i(TAG, "Observer no longer exists.");
10327                }
10328            }
10329        }
10330
10331        @Override
10332        void handleServiceError() {
10333            Slog.e(TAG, "Could not measure application " + mStats.packageName
10334                            + " external storage");
10335        }
10336    }
10337
10338    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10339            throws RemoteException {
10340        long result = 0;
10341        for (File path : paths) {
10342            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10343        }
10344        return result;
10345    }
10346
10347    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10348        for (File path : paths) {
10349            try {
10350                mcs.clearDirectory(path.getAbsolutePath());
10351            } catch (RemoteException e) {
10352            }
10353        }
10354    }
10355
10356    static class OriginInfo {
10357        /**
10358         * Location where install is coming from, before it has been
10359         * copied/renamed into place. This could be a single monolithic APK
10360         * file, or a cluster directory. This location may be untrusted.
10361         */
10362        final File file;
10363        final String cid;
10364
10365        /**
10366         * Flag indicating that {@link #file} or {@link #cid} has already been
10367         * staged, meaning downstream users don't need to defensively copy the
10368         * contents.
10369         */
10370        final boolean staged;
10371
10372        /**
10373         * Flag indicating that {@link #file} or {@link #cid} is an already
10374         * installed app that is being moved.
10375         */
10376        final boolean existing;
10377
10378        final String resolvedPath;
10379        final File resolvedFile;
10380
10381        static OriginInfo fromNothing() {
10382            return new OriginInfo(null, null, false, false);
10383        }
10384
10385        static OriginInfo fromUntrustedFile(File file) {
10386            return new OriginInfo(file, null, false, false);
10387        }
10388
10389        static OriginInfo fromExistingFile(File file) {
10390            return new OriginInfo(file, null, false, true);
10391        }
10392
10393        static OriginInfo fromStagedFile(File file) {
10394            return new OriginInfo(file, null, true, false);
10395        }
10396
10397        static OriginInfo fromStagedContainer(String cid) {
10398            return new OriginInfo(null, cid, true, false);
10399        }
10400
10401        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10402            this.file = file;
10403            this.cid = cid;
10404            this.staged = staged;
10405            this.existing = existing;
10406
10407            if (cid != null) {
10408                resolvedPath = PackageHelper.getSdDir(cid);
10409                resolvedFile = new File(resolvedPath);
10410            } else if (file != null) {
10411                resolvedPath = file.getAbsolutePath();
10412                resolvedFile = file;
10413            } else {
10414                resolvedPath = null;
10415                resolvedFile = null;
10416            }
10417        }
10418    }
10419
10420    class MoveInfo {
10421        final int moveId;
10422        final String fromUuid;
10423        final String toUuid;
10424        final String packageName;
10425        final String dataAppName;
10426        final int appId;
10427        final String seinfo;
10428
10429        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10430                String dataAppName, int appId, String seinfo) {
10431            this.moveId = moveId;
10432            this.fromUuid = fromUuid;
10433            this.toUuid = toUuid;
10434            this.packageName = packageName;
10435            this.dataAppName = dataAppName;
10436            this.appId = appId;
10437            this.seinfo = seinfo;
10438        }
10439    }
10440
10441    class InstallParams extends HandlerParams {
10442        final OriginInfo origin;
10443        final MoveInfo move;
10444        final IPackageInstallObserver2 observer;
10445        int installFlags;
10446        final String installerPackageName;
10447        final String volumeUuid;
10448        final VerificationParams verificationParams;
10449        private InstallArgs mArgs;
10450        private int mRet;
10451        final String packageAbiOverride;
10452        final String[] grantedRuntimePermissions;
10453
10454        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10455                int installFlags, String installerPackageName, String volumeUuid,
10456                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10457                String[] grantedPermissions) {
10458            super(user);
10459            this.origin = origin;
10460            this.move = move;
10461            this.observer = observer;
10462            this.installFlags = installFlags;
10463            this.installerPackageName = installerPackageName;
10464            this.volumeUuid = volumeUuid;
10465            this.verificationParams = verificationParams;
10466            this.packageAbiOverride = packageAbiOverride;
10467            this.grantedRuntimePermissions = grantedPermissions;
10468        }
10469
10470        @Override
10471        public String toString() {
10472            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10473                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10474        }
10475
10476        public ManifestDigest getManifestDigest() {
10477            if (verificationParams == null) {
10478                return null;
10479            }
10480            return verificationParams.getManifestDigest();
10481        }
10482
10483        private int installLocationPolicy(PackageInfoLite pkgLite) {
10484            String packageName = pkgLite.packageName;
10485            int installLocation = pkgLite.installLocation;
10486            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10487            // reader
10488            synchronized (mPackages) {
10489                PackageParser.Package pkg = mPackages.get(packageName);
10490                if (pkg != null) {
10491                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10492                        // Check for downgrading.
10493                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10494                            try {
10495                                checkDowngrade(pkg, pkgLite);
10496                            } catch (PackageManagerException e) {
10497                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10498                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10499                            }
10500                        }
10501                        // Check for updated system application.
10502                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10503                            if (onSd) {
10504                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10505                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10506                            }
10507                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10508                        } else {
10509                            if (onSd) {
10510                                // Install flag overrides everything.
10511                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10512                            }
10513                            // If current upgrade specifies particular preference
10514                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10515                                // Application explicitly specified internal.
10516                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10517                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10518                                // App explictly prefers external. Let policy decide
10519                            } else {
10520                                // Prefer previous location
10521                                if (isExternal(pkg)) {
10522                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10523                                }
10524                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10525                            }
10526                        }
10527                    } else {
10528                        // Invalid install. Return error code
10529                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10530                    }
10531                }
10532            }
10533            // All the special cases have been taken care of.
10534            // Return result based on recommended install location.
10535            if (onSd) {
10536                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10537            }
10538            return pkgLite.recommendedInstallLocation;
10539        }
10540
10541        /*
10542         * Invoke remote method to get package information and install
10543         * location values. Override install location based on default
10544         * policy if needed and then create install arguments based
10545         * on the install location.
10546         */
10547        public void handleStartCopy() throws RemoteException {
10548            int ret = PackageManager.INSTALL_SUCCEEDED;
10549
10550            // If we're already staged, we've firmly committed to an install location
10551            if (origin.staged) {
10552                if (origin.file != null) {
10553                    installFlags |= PackageManager.INSTALL_INTERNAL;
10554                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10555                } else if (origin.cid != null) {
10556                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10557                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10558                } else {
10559                    throw new IllegalStateException("Invalid stage location");
10560                }
10561            }
10562
10563            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10564            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10565            PackageInfoLite pkgLite = null;
10566
10567            if (onInt && onSd) {
10568                // Check if both bits are set.
10569                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10570                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10571            } else {
10572                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10573                        packageAbiOverride);
10574
10575                /*
10576                 * If we have too little free space, try to free cache
10577                 * before giving up.
10578                 */
10579                if (!origin.staged && pkgLite.recommendedInstallLocation
10580                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10581                    // TODO: focus freeing disk space on the target device
10582                    final StorageManager storage = StorageManager.from(mContext);
10583                    final long lowThreshold = storage.getStorageLowBytes(
10584                            Environment.getDataDirectory());
10585
10586                    final long sizeBytes = mContainerService.calculateInstalledSize(
10587                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10588
10589                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10590                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10591                                installFlags, packageAbiOverride);
10592                    }
10593
10594                    /*
10595                     * The cache free must have deleted the file we
10596                     * downloaded to install.
10597                     *
10598                     * TODO: fix the "freeCache" call to not delete
10599                     *       the file we care about.
10600                     */
10601                    if (pkgLite.recommendedInstallLocation
10602                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10603                        pkgLite.recommendedInstallLocation
10604                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10605                    }
10606                }
10607            }
10608
10609            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10610                int loc = pkgLite.recommendedInstallLocation;
10611                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10612                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10613                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10614                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10615                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10616                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10617                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10618                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10619                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10620                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10621                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10622                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10623                } else {
10624                    // Override with defaults if needed.
10625                    loc = installLocationPolicy(pkgLite);
10626                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10627                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10628                    } else if (!onSd && !onInt) {
10629                        // Override install location with flags
10630                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10631                            // Set the flag to install on external media.
10632                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10633                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10634                        } else {
10635                            // Make sure the flag for installing on external
10636                            // media is unset
10637                            installFlags |= PackageManager.INSTALL_INTERNAL;
10638                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10639                        }
10640                    }
10641                }
10642            }
10643
10644            final InstallArgs args = createInstallArgs(this);
10645            mArgs = args;
10646
10647            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10648                // TODO: http://b/22976637
10649                // Apps installed for "all" users use the device owner to verify the app
10650                UserHandle verifierUser = getUser();
10651                if (verifierUser == UserHandle.ALL) {
10652                    verifierUser = UserHandle.SYSTEM;
10653                }
10654
10655                /*
10656                 * Determine if we have any installed package verifiers. If we
10657                 * do, then we'll defer to them to verify the packages.
10658                 */
10659                final int requiredUid = mRequiredVerifierPackage == null ? -1
10660                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10661                if (!origin.existing && requiredUid != -1
10662                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10663                    final Intent verification = new Intent(
10664                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10665                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10666                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10667                            PACKAGE_MIME_TYPE);
10668                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10669
10670                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10671                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10672                            verifierUser.getIdentifier());
10673
10674                    if (DEBUG_VERIFY) {
10675                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10676                                + verification.toString() + " with " + pkgLite.verifiers.length
10677                                + " optional verifiers");
10678                    }
10679
10680                    final int verificationId = mPendingVerificationToken++;
10681
10682                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10683
10684                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10685                            installerPackageName);
10686
10687                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10688                            installFlags);
10689
10690                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10691                            pkgLite.packageName);
10692
10693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10694                            pkgLite.versionCode);
10695
10696                    if (verificationParams != null) {
10697                        if (verificationParams.getVerificationURI() != null) {
10698                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10699                                 verificationParams.getVerificationURI());
10700                        }
10701                        if (verificationParams.getOriginatingURI() != null) {
10702                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10703                                  verificationParams.getOriginatingURI());
10704                        }
10705                        if (verificationParams.getReferrer() != null) {
10706                            verification.putExtra(Intent.EXTRA_REFERRER,
10707                                  verificationParams.getReferrer());
10708                        }
10709                        if (verificationParams.getOriginatingUid() >= 0) {
10710                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10711                                  verificationParams.getOriginatingUid());
10712                        }
10713                        if (verificationParams.getInstallerUid() >= 0) {
10714                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10715                                  verificationParams.getInstallerUid());
10716                        }
10717                    }
10718
10719                    final PackageVerificationState verificationState = new PackageVerificationState(
10720                            requiredUid, args);
10721
10722                    mPendingVerification.append(verificationId, verificationState);
10723
10724                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10725                            receivers, verificationState);
10726
10727                    /*
10728                     * If any sufficient verifiers were listed in the package
10729                     * manifest, attempt to ask them.
10730                     */
10731                    if (sufficientVerifiers != null) {
10732                        final int N = sufficientVerifiers.size();
10733                        if (N == 0) {
10734                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10735                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10736                        } else {
10737                            for (int i = 0; i < N; i++) {
10738                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10739
10740                                final Intent sufficientIntent = new Intent(verification);
10741                                sufficientIntent.setComponent(verifierComponent);
10742                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10743                            }
10744                        }
10745                    }
10746
10747                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10748                            mRequiredVerifierPackage, receivers);
10749                    if (ret == PackageManager.INSTALL_SUCCEEDED
10750                            && mRequiredVerifierPackage != null) {
10751                        Trace.asyncTraceBegin(
10752                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10753                        /*
10754                         * Send the intent to the required verification agent,
10755                         * but only start the verification timeout after the
10756                         * target BroadcastReceivers have run.
10757                         */
10758                        verification.setComponent(requiredVerifierComponent);
10759                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10760                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10761                                new BroadcastReceiver() {
10762                                    @Override
10763                                    public void onReceive(Context context, Intent intent) {
10764                                        final Message msg = mHandler
10765                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10766                                        msg.arg1 = verificationId;
10767                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10768                                    }
10769                                }, null, 0, null, null);
10770
10771                        /*
10772                         * We don't want the copy to proceed until verification
10773                         * succeeds, so null out this field.
10774                         */
10775                        mArgs = null;
10776                    }
10777                } else {
10778                    /*
10779                     * No package verification is enabled, so immediately start
10780                     * the remote call to initiate copy using temporary file.
10781                     */
10782                    ret = args.copyApk(mContainerService, true);
10783                }
10784            }
10785
10786            mRet = ret;
10787        }
10788
10789        @Override
10790        void handleReturnCode() {
10791            // If mArgs is null, then MCS couldn't be reached. When it
10792            // reconnects, it will try again to install. At that point, this
10793            // will succeed.
10794            if (mArgs != null) {
10795                processPendingInstall(mArgs, mRet);
10796            }
10797        }
10798
10799        @Override
10800        void handleServiceError() {
10801            mArgs = createInstallArgs(this);
10802            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10803        }
10804
10805        public boolean isForwardLocked() {
10806            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10807        }
10808    }
10809
10810    /**
10811     * Used during creation of InstallArgs
10812     *
10813     * @param installFlags package installation flags
10814     * @return true if should be installed on external storage
10815     */
10816    private static boolean installOnExternalAsec(int installFlags) {
10817        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10818            return false;
10819        }
10820        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10821            return true;
10822        }
10823        return false;
10824    }
10825
10826    /**
10827     * Used during creation of InstallArgs
10828     *
10829     * @param installFlags package installation flags
10830     * @return true if should be installed as forward locked
10831     */
10832    private static boolean installForwardLocked(int installFlags) {
10833        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10834    }
10835
10836    private InstallArgs createInstallArgs(InstallParams params) {
10837        if (params.move != null) {
10838            return new MoveInstallArgs(params);
10839        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10840            return new AsecInstallArgs(params);
10841        } else {
10842            return new FileInstallArgs(params);
10843        }
10844    }
10845
10846    /**
10847     * Create args that describe an existing installed package. Typically used
10848     * when cleaning up old installs, or used as a move source.
10849     */
10850    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10851            String resourcePath, String[] instructionSets) {
10852        final boolean isInAsec;
10853        if (installOnExternalAsec(installFlags)) {
10854            /* Apps on SD card are always in ASEC containers. */
10855            isInAsec = true;
10856        } else if (installForwardLocked(installFlags)
10857                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10858            /*
10859             * Forward-locked apps are only in ASEC containers if they're the
10860             * new style
10861             */
10862            isInAsec = true;
10863        } else {
10864            isInAsec = false;
10865        }
10866
10867        if (isInAsec) {
10868            return new AsecInstallArgs(codePath, instructionSets,
10869                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10870        } else {
10871            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10872        }
10873    }
10874
10875    static abstract class InstallArgs {
10876        /** @see InstallParams#origin */
10877        final OriginInfo origin;
10878        /** @see InstallParams#move */
10879        final MoveInfo move;
10880
10881        final IPackageInstallObserver2 observer;
10882        // Always refers to PackageManager flags only
10883        final int installFlags;
10884        final String installerPackageName;
10885        final String volumeUuid;
10886        final ManifestDigest manifestDigest;
10887        final UserHandle user;
10888        final String abiOverride;
10889        final String[] installGrantPermissions;
10890        /** If non-null, drop an async trace when the install completes */
10891        final String traceMethod;
10892        final int traceCookie;
10893
10894        // The list of instruction sets supported by this app. This is currently
10895        // only used during the rmdex() phase to clean up resources. We can get rid of this
10896        // if we move dex files under the common app path.
10897        /* nullable */ String[] instructionSets;
10898
10899        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10900                int installFlags, String installerPackageName, String volumeUuid,
10901                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10902                String abiOverride, String[] installGrantPermissions,
10903                String traceMethod, int traceCookie) {
10904            this.origin = origin;
10905            this.move = move;
10906            this.installFlags = installFlags;
10907            this.observer = observer;
10908            this.installerPackageName = installerPackageName;
10909            this.volumeUuid = volumeUuid;
10910            this.manifestDigest = manifestDigest;
10911            this.user = user;
10912            this.instructionSets = instructionSets;
10913            this.abiOverride = abiOverride;
10914            this.installGrantPermissions = installGrantPermissions;
10915            this.traceMethod = traceMethod;
10916            this.traceCookie = traceCookie;
10917        }
10918
10919        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10920        abstract int doPreInstall(int status);
10921
10922        /**
10923         * Rename package into final resting place. All paths on the given
10924         * scanned package should be updated to reflect the rename.
10925         */
10926        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10927        abstract int doPostInstall(int status, int uid);
10928
10929        /** @see PackageSettingBase#codePathString */
10930        abstract String getCodePath();
10931        /** @see PackageSettingBase#resourcePathString */
10932        abstract String getResourcePath();
10933
10934        // Need installer lock especially for dex file removal.
10935        abstract void cleanUpResourcesLI();
10936        abstract boolean doPostDeleteLI(boolean delete);
10937
10938        /**
10939         * Called before the source arguments are copied. This is used mostly
10940         * for MoveParams when it needs to read the source file to put it in the
10941         * destination.
10942         */
10943        int doPreCopy() {
10944            return PackageManager.INSTALL_SUCCEEDED;
10945        }
10946
10947        /**
10948         * Called after the source arguments are copied. This is used mostly for
10949         * MoveParams when it needs to read the source file to put it in the
10950         * destination.
10951         *
10952         * @return
10953         */
10954        int doPostCopy(int uid) {
10955            return PackageManager.INSTALL_SUCCEEDED;
10956        }
10957
10958        protected boolean isFwdLocked() {
10959            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10960        }
10961
10962        protected boolean isExternalAsec() {
10963            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10964        }
10965
10966        UserHandle getUser() {
10967            return user;
10968        }
10969    }
10970
10971    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10972        if (!allCodePaths.isEmpty()) {
10973            if (instructionSets == null) {
10974                throw new IllegalStateException("instructionSet == null");
10975            }
10976            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10977            for (String codePath : allCodePaths) {
10978                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10979                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10980                    if (retCode < 0) {
10981                        Slog.w(TAG, "Couldn't remove dex file for package: "
10982                                + " at location " + codePath + ", retcode=" + retCode);
10983                        // we don't consider this to be a failure of the core package deletion
10984                    }
10985                }
10986            }
10987        }
10988    }
10989
10990    /**
10991     * Logic to handle installation of non-ASEC applications, including copying
10992     * and renaming logic.
10993     */
10994    class FileInstallArgs extends InstallArgs {
10995        private File codeFile;
10996        private File resourceFile;
10997
10998        // Example topology:
10999        // /data/app/com.example/base.apk
11000        // /data/app/com.example/split_foo.apk
11001        // /data/app/com.example/lib/arm/libfoo.so
11002        // /data/app/com.example/lib/arm64/libfoo.so
11003        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11004
11005        /** New install */
11006        FileInstallArgs(InstallParams params) {
11007            super(params.origin, params.move, params.observer, params.installFlags,
11008                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11009                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11010                    params.grantedRuntimePermissions,
11011                    params.traceMethod, params.traceCookie);
11012            if (isFwdLocked()) {
11013                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11014            }
11015        }
11016
11017        /** Existing install */
11018        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11019            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11020                    null, null, null, 0);
11021            this.codeFile = (codePath != null) ? new File(codePath) : null;
11022            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11023        }
11024
11025        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11026            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11027            try {
11028                return doCopyApk(imcs, temp);
11029            } finally {
11030                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11031            }
11032        }
11033
11034        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11035            if (origin.staged) {
11036                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11037                codeFile = origin.file;
11038                resourceFile = origin.file;
11039                return PackageManager.INSTALL_SUCCEEDED;
11040            }
11041
11042            try {
11043                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11044                codeFile = tempDir;
11045                resourceFile = tempDir;
11046            } catch (IOException e) {
11047                Slog.w(TAG, "Failed to create copy file: " + e);
11048                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11049            }
11050
11051            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11052                @Override
11053                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11054                    if (!FileUtils.isValidExtFilename(name)) {
11055                        throw new IllegalArgumentException("Invalid filename: " + name);
11056                    }
11057                    try {
11058                        final File file = new File(codeFile, name);
11059                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11060                                O_RDWR | O_CREAT, 0644);
11061                        Os.chmod(file.getAbsolutePath(), 0644);
11062                        return new ParcelFileDescriptor(fd);
11063                    } catch (ErrnoException e) {
11064                        throw new RemoteException("Failed to open: " + e.getMessage());
11065                    }
11066                }
11067            };
11068
11069            int ret = PackageManager.INSTALL_SUCCEEDED;
11070            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11071            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11072                Slog.e(TAG, "Failed to copy package");
11073                return ret;
11074            }
11075
11076            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11077            NativeLibraryHelper.Handle handle = null;
11078            try {
11079                handle = NativeLibraryHelper.Handle.create(codeFile);
11080                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11081                        abiOverride);
11082            } catch (IOException e) {
11083                Slog.e(TAG, "Copying native libraries failed", e);
11084                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11085            } finally {
11086                IoUtils.closeQuietly(handle);
11087            }
11088
11089            return ret;
11090        }
11091
11092        int doPreInstall(int status) {
11093            if (status != PackageManager.INSTALL_SUCCEEDED) {
11094                cleanUp();
11095            }
11096            return status;
11097        }
11098
11099        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11100            if (status != PackageManager.INSTALL_SUCCEEDED) {
11101                cleanUp();
11102                return false;
11103            }
11104
11105            final File targetDir = codeFile.getParentFile();
11106            final File beforeCodeFile = codeFile;
11107            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11108
11109            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11110            try {
11111                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11112            } catch (ErrnoException e) {
11113                Slog.w(TAG, "Failed to rename", e);
11114                return false;
11115            }
11116
11117            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11118                Slog.w(TAG, "Failed to restorecon");
11119                return false;
11120            }
11121
11122            // Reflect the rename internally
11123            codeFile = afterCodeFile;
11124            resourceFile = afterCodeFile;
11125
11126            // Reflect the rename in scanned details
11127            pkg.codePath = afterCodeFile.getAbsolutePath();
11128            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11129                    pkg.baseCodePath);
11130            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11131                    pkg.splitCodePaths);
11132
11133            // Reflect the rename in app info
11134            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11135            pkg.applicationInfo.setCodePath(pkg.codePath);
11136            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11137            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11138            pkg.applicationInfo.setResourcePath(pkg.codePath);
11139            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11140            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11141
11142            return true;
11143        }
11144
11145        int doPostInstall(int status, int uid) {
11146            if (status != PackageManager.INSTALL_SUCCEEDED) {
11147                cleanUp();
11148            }
11149            return status;
11150        }
11151
11152        @Override
11153        String getCodePath() {
11154            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11155        }
11156
11157        @Override
11158        String getResourcePath() {
11159            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11160        }
11161
11162        private boolean cleanUp() {
11163            if (codeFile == null || !codeFile.exists()) {
11164                return false;
11165            }
11166
11167            if (codeFile.isDirectory()) {
11168                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11169            } else {
11170                codeFile.delete();
11171            }
11172
11173            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11174                resourceFile.delete();
11175            }
11176
11177            return true;
11178        }
11179
11180        void cleanUpResourcesLI() {
11181            // Try enumerating all code paths before deleting
11182            List<String> allCodePaths = Collections.EMPTY_LIST;
11183            if (codeFile != null && codeFile.exists()) {
11184                try {
11185                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11186                    allCodePaths = pkg.getAllCodePaths();
11187                } catch (PackageParserException e) {
11188                    // Ignored; we tried our best
11189                }
11190            }
11191
11192            cleanUp();
11193            removeDexFiles(allCodePaths, instructionSets);
11194        }
11195
11196        boolean doPostDeleteLI(boolean delete) {
11197            // XXX err, shouldn't we respect the delete flag?
11198            cleanUpResourcesLI();
11199            return true;
11200        }
11201    }
11202
11203    private boolean isAsecExternal(String cid) {
11204        final String asecPath = PackageHelper.getSdFilesystem(cid);
11205        return !asecPath.startsWith(mAsecInternalPath);
11206    }
11207
11208    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11209            PackageManagerException {
11210        if (copyRet < 0) {
11211            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11212                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11213                throw new PackageManagerException(copyRet, message);
11214            }
11215        }
11216    }
11217
11218    /**
11219     * Extract the MountService "container ID" from the full code path of an
11220     * .apk.
11221     */
11222    static String cidFromCodePath(String fullCodePath) {
11223        int eidx = fullCodePath.lastIndexOf("/");
11224        String subStr1 = fullCodePath.substring(0, eidx);
11225        int sidx = subStr1.lastIndexOf("/");
11226        return subStr1.substring(sidx+1, eidx);
11227    }
11228
11229    /**
11230     * Logic to handle installation of ASEC applications, including copying and
11231     * renaming logic.
11232     */
11233    class AsecInstallArgs extends InstallArgs {
11234        static final String RES_FILE_NAME = "pkg.apk";
11235        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11236
11237        String cid;
11238        String packagePath;
11239        String resourcePath;
11240
11241        /** New install */
11242        AsecInstallArgs(InstallParams params) {
11243            super(params.origin, params.move, params.observer, params.installFlags,
11244                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11245                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11246                    params.grantedRuntimePermissions,
11247                    params.traceMethod, params.traceCookie);
11248        }
11249
11250        /** Existing install */
11251        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11252                        boolean isExternal, boolean isForwardLocked) {
11253            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11254                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11255                    instructionSets, null, null, null, 0);
11256            // Hackily pretend we're still looking at a full code path
11257            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11258                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11259            }
11260
11261            // Extract cid from fullCodePath
11262            int eidx = fullCodePath.lastIndexOf("/");
11263            String subStr1 = fullCodePath.substring(0, eidx);
11264            int sidx = subStr1.lastIndexOf("/");
11265            cid = subStr1.substring(sidx+1, eidx);
11266            setMountPath(subStr1);
11267        }
11268
11269        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11270            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11271                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11272                    instructionSets, null, null, null, 0);
11273            this.cid = cid;
11274            setMountPath(PackageHelper.getSdDir(cid));
11275        }
11276
11277        void createCopyFile() {
11278            cid = mInstallerService.allocateExternalStageCidLegacy();
11279        }
11280
11281        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11282            if (origin.staged) {
11283                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11284                cid = origin.cid;
11285                setMountPath(PackageHelper.getSdDir(cid));
11286                return PackageManager.INSTALL_SUCCEEDED;
11287            }
11288
11289            if (temp) {
11290                createCopyFile();
11291            } else {
11292                /*
11293                 * Pre-emptively destroy the container since it's destroyed if
11294                 * copying fails due to it existing anyway.
11295                 */
11296                PackageHelper.destroySdDir(cid);
11297            }
11298
11299            final String newMountPath = imcs.copyPackageToContainer(
11300                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11301                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11302
11303            if (newMountPath != null) {
11304                setMountPath(newMountPath);
11305                return PackageManager.INSTALL_SUCCEEDED;
11306            } else {
11307                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11308            }
11309        }
11310
11311        @Override
11312        String getCodePath() {
11313            return packagePath;
11314        }
11315
11316        @Override
11317        String getResourcePath() {
11318            return resourcePath;
11319        }
11320
11321        int doPreInstall(int status) {
11322            if (status != PackageManager.INSTALL_SUCCEEDED) {
11323                // Destroy container
11324                PackageHelper.destroySdDir(cid);
11325            } else {
11326                boolean mounted = PackageHelper.isContainerMounted(cid);
11327                if (!mounted) {
11328                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11329                            Process.SYSTEM_UID);
11330                    if (newMountPath != null) {
11331                        setMountPath(newMountPath);
11332                    } else {
11333                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11334                    }
11335                }
11336            }
11337            return status;
11338        }
11339
11340        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11341            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11342            String newMountPath = null;
11343            if (PackageHelper.isContainerMounted(cid)) {
11344                // Unmount the container
11345                if (!PackageHelper.unMountSdDir(cid)) {
11346                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11347                    return false;
11348                }
11349            }
11350            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11351                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11352                        " which might be stale. Will try to clean up.");
11353                // Clean up the stale container and proceed to recreate.
11354                if (!PackageHelper.destroySdDir(newCacheId)) {
11355                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11356                    return false;
11357                }
11358                // Successfully cleaned up stale container. Try to rename again.
11359                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11360                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11361                            + " inspite of cleaning it up.");
11362                    return false;
11363                }
11364            }
11365            if (!PackageHelper.isContainerMounted(newCacheId)) {
11366                Slog.w(TAG, "Mounting container " + newCacheId);
11367                newMountPath = PackageHelper.mountSdDir(newCacheId,
11368                        getEncryptKey(), Process.SYSTEM_UID);
11369            } else {
11370                newMountPath = PackageHelper.getSdDir(newCacheId);
11371            }
11372            if (newMountPath == null) {
11373                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11374                return false;
11375            }
11376            Log.i(TAG, "Succesfully renamed " + cid +
11377                    " to " + newCacheId +
11378                    " at new path: " + newMountPath);
11379            cid = newCacheId;
11380
11381            final File beforeCodeFile = new File(packagePath);
11382            setMountPath(newMountPath);
11383            final File afterCodeFile = new File(packagePath);
11384
11385            // Reflect the rename in scanned details
11386            pkg.codePath = afterCodeFile.getAbsolutePath();
11387            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11388                    pkg.baseCodePath);
11389            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11390                    pkg.splitCodePaths);
11391
11392            // Reflect the rename in app info
11393            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11394            pkg.applicationInfo.setCodePath(pkg.codePath);
11395            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11396            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11397            pkg.applicationInfo.setResourcePath(pkg.codePath);
11398            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11399            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11400
11401            return true;
11402        }
11403
11404        private void setMountPath(String mountPath) {
11405            final File mountFile = new File(mountPath);
11406
11407            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11408            if (monolithicFile.exists()) {
11409                packagePath = monolithicFile.getAbsolutePath();
11410                if (isFwdLocked()) {
11411                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11412                } else {
11413                    resourcePath = packagePath;
11414                }
11415            } else {
11416                packagePath = mountFile.getAbsolutePath();
11417                resourcePath = packagePath;
11418            }
11419        }
11420
11421        int doPostInstall(int status, int uid) {
11422            if (status != PackageManager.INSTALL_SUCCEEDED) {
11423                cleanUp();
11424            } else {
11425                final int groupOwner;
11426                final String protectedFile;
11427                if (isFwdLocked()) {
11428                    groupOwner = UserHandle.getSharedAppGid(uid);
11429                    protectedFile = RES_FILE_NAME;
11430                } else {
11431                    groupOwner = -1;
11432                    protectedFile = null;
11433                }
11434
11435                if (uid < Process.FIRST_APPLICATION_UID
11436                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11437                    Slog.e(TAG, "Failed to finalize " + cid);
11438                    PackageHelper.destroySdDir(cid);
11439                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11440                }
11441
11442                boolean mounted = PackageHelper.isContainerMounted(cid);
11443                if (!mounted) {
11444                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11445                }
11446            }
11447            return status;
11448        }
11449
11450        private void cleanUp() {
11451            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11452
11453            // Destroy secure container
11454            PackageHelper.destroySdDir(cid);
11455        }
11456
11457        private List<String> getAllCodePaths() {
11458            final File codeFile = new File(getCodePath());
11459            if (codeFile != null && codeFile.exists()) {
11460                try {
11461                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11462                    return pkg.getAllCodePaths();
11463                } catch (PackageParserException e) {
11464                    // Ignored; we tried our best
11465                }
11466            }
11467            return Collections.EMPTY_LIST;
11468        }
11469
11470        void cleanUpResourcesLI() {
11471            // Enumerate all code paths before deleting
11472            cleanUpResourcesLI(getAllCodePaths());
11473        }
11474
11475        private void cleanUpResourcesLI(List<String> allCodePaths) {
11476            cleanUp();
11477            removeDexFiles(allCodePaths, instructionSets);
11478        }
11479
11480        String getPackageName() {
11481            return getAsecPackageName(cid);
11482        }
11483
11484        boolean doPostDeleteLI(boolean delete) {
11485            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11486            final List<String> allCodePaths = getAllCodePaths();
11487            boolean mounted = PackageHelper.isContainerMounted(cid);
11488            if (mounted) {
11489                // Unmount first
11490                if (PackageHelper.unMountSdDir(cid)) {
11491                    mounted = false;
11492                }
11493            }
11494            if (!mounted && delete) {
11495                cleanUpResourcesLI(allCodePaths);
11496            }
11497            return !mounted;
11498        }
11499
11500        @Override
11501        int doPreCopy() {
11502            if (isFwdLocked()) {
11503                if (!PackageHelper.fixSdPermissions(cid,
11504                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11505                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11506                }
11507            }
11508
11509            return PackageManager.INSTALL_SUCCEEDED;
11510        }
11511
11512        @Override
11513        int doPostCopy(int uid) {
11514            if (isFwdLocked()) {
11515                if (uid < Process.FIRST_APPLICATION_UID
11516                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11517                                RES_FILE_NAME)) {
11518                    Slog.e(TAG, "Failed to finalize " + cid);
11519                    PackageHelper.destroySdDir(cid);
11520                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11521                }
11522            }
11523
11524            return PackageManager.INSTALL_SUCCEEDED;
11525        }
11526    }
11527
11528    /**
11529     * Logic to handle movement of existing installed applications.
11530     */
11531    class MoveInstallArgs extends InstallArgs {
11532        private File codeFile;
11533        private File resourceFile;
11534
11535        /** New install */
11536        MoveInstallArgs(InstallParams params) {
11537            super(params.origin, params.move, params.observer, params.installFlags,
11538                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11539                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11540                    params.grantedRuntimePermissions,
11541                    params.traceMethod, params.traceCookie);
11542        }
11543
11544        int copyApk(IMediaContainerService imcs, boolean temp) {
11545            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11546                    + move.fromUuid + " to " + move.toUuid);
11547            synchronized (mInstaller) {
11548                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11549                        move.dataAppName, move.appId, move.seinfo) != 0) {
11550                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11551                }
11552            }
11553
11554            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11555            resourceFile = codeFile;
11556            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11557
11558            return PackageManager.INSTALL_SUCCEEDED;
11559        }
11560
11561        int doPreInstall(int status) {
11562            if (status != PackageManager.INSTALL_SUCCEEDED) {
11563                cleanUp(move.toUuid);
11564            }
11565            return status;
11566        }
11567
11568        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11569            if (status != PackageManager.INSTALL_SUCCEEDED) {
11570                cleanUp(move.toUuid);
11571                return false;
11572            }
11573
11574            // Reflect the move in app info
11575            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11576            pkg.applicationInfo.setCodePath(pkg.codePath);
11577            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11578            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11579            pkg.applicationInfo.setResourcePath(pkg.codePath);
11580            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11581            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11582
11583            return true;
11584        }
11585
11586        int doPostInstall(int status, int uid) {
11587            if (status == PackageManager.INSTALL_SUCCEEDED) {
11588                cleanUp(move.fromUuid);
11589            } else {
11590                cleanUp(move.toUuid);
11591            }
11592            return status;
11593        }
11594
11595        @Override
11596        String getCodePath() {
11597            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11598        }
11599
11600        @Override
11601        String getResourcePath() {
11602            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11603        }
11604
11605        private boolean cleanUp(String volumeUuid) {
11606            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11607                    move.dataAppName);
11608            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11609            synchronized (mInstallLock) {
11610                // Clean up both app data and code
11611                removeDataDirsLI(volumeUuid, move.packageName);
11612                if (codeFile.isDirectory()) {
11613                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11614                } else {
11615                    codeFile.delete();
11616                }
11617            }
11618            return true;
11619        }
11620
11621        void cleanUpResourcesLI() {
11622            throw new UnsupportedOperationException();
11623        }
11624
11625        boolean doPostDeleteLI(boolean delete) {
11626            throw new UnsupportedOperationException();
11627        }
11628    }
11629
11630    static String getAsecPackageName(String packageCid) {
11631        int idx = packageCid.lastIndexOf("-");
11632        if (idx == -1) {
11633            return packageCid;
11634        }
11635        return packageCid.substring(0, idx);
11636    }
11637
11638    // Utility method used to create code paths based on package name and available index.
11639    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11640        String idxStr = "";
11641        int idx = 1;
11642        // Fall back to default value of idx=1 if prefix is not
11643        // part of oldCodePath
11644        if (oldCodePath != null) {
11645            String subStr = oldCodePath;
11646            // Drop the suffix right away
11647            if (suffix != null && subStr.endsWith(suffix)) {
11648                subStr = subStr.substring(0, subStr.length() - suffix.length());
11649            }
11650            // If oldCodePath already contains prefix find out the
11651            // ending index to either increment or decrement.
11652            int sidx = subStr.lastIndexOf(prefix);
11653            if (sidx != -1) {
11654                subStr = subStr.substring(sidx + prefix.length());
11655                if (subStr != null) {
11656                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11657                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11658                    }
11659                    try {
11660                        idx = Integer.parseInt(subStr);
11661                        if (idx <= 1) {
11662                            idx++;
11663                        } else {
11664                            idx--;
11665                        }
11666                    } catch(NumberFormatException e) {
11667                    }
11668                }
11669            }
11670        }
11671        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11672        return prefix + idxStr;
11673    }
11674
11675    private File getNextCodePath(File targetDir, String packageName) {
11676        int suffix = 1;
11677        File result;
11678        do {
11679            result = new File(targetDir, packageName + "-" + suffix);
11680            suffix++;
11681        } while (result.exists());
11682        return result;
11683    }
11684
11685    // Utility method that returns the relative package path with respect
11686    // to the installation directory. Like say for /data/data/com.test-1.apk
11687    // string com.test-1 is returned.
11688    static String deriveCodePathName(String codePath) {
11689        if (codePath == null) {
11690            return null;
11691        }
11692        final File codeFile = new File(codePath);
11693        final String name = codeFile.getName();
11694        if (codeFile.isDirectory()) {
11695            return name;
11696        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11697            final int lastDot = name.lastIndexOf('.');
11698            return name.substring(0, lastDot);
11699        } else {
11700            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11701            return null;
11702        }
11703    }
11704
11705    class PackageInstalledInfo {
11706        String name;
11707        int uid;
11708        // The set of users that originally had this package installed.
11709        int[] origUsers;
11710        // The set of users that now have this package installed.
11711        int[] newUsers;
11712        PackageParser.Package pkg;
11713        int returnCode;
11714        String returnMsg;
11715        PackageRemovedInfo removedInfo;
11716
11717        public void setError(int code, String msg) {
11718            returnCode = code;
11719            returnMsg = msg;
11720            Slog.w(TAG, msg);
11721        }
11722
11723        public void setError(String msg, PackageParserException e) {
11724            returnCode = e.error;
11725            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11726            Slog.w(TAG, msg, e);
11727        }
11728
11729        public void setError(String msg, PackageManagerException e) {
11730            returnCode = e.error;
11731            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11732            Slog.w(TAG, msg, e);
11733        }
11734
11735        // In some error cases we want to convey more info back to the observer
11736        String origPackage;
11737        String origPermission;
11738    }
11739
11740    /*
11741     * Install a non-existing package.
11742     */
11743    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11744            UserHandle user, String installerPackageName, String volumeUuid,
11745            PackageInstalledInfo res) {
11746        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11747
11748        // Remember this for later, in case we need to rollback this install
11749        String pkgName = pkg.packageName;
11750
11751        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11752        // TODO: b/23350563
11753        final boolean dataDirExists = Environment
11754                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11755
11756        synchronized(mPackages) {
11757            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11758                // A package with the same name is already installed, though
11759                // it has been renamed to an older name.  The package we
11760                // are trying to install should be installed as an update to
11761                // the existing one, but that has not been requested, so bail.
11762                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11763                        + " without first uninstalling package running as "
11764                        + mSettings.mRenamedPackages.get(pkgName));
11765                return;
11766            }
11767            if (mPackages.containsKey(pkgName)) {
11768                // Don't allow installation over an existing package with the same name.
11769                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11770                        + " without first uninstalling.");
11771                return;
11772            }
11773        }
11774
11775        try {
11776            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11777                    System.currentTimeMillis(), user);
11778
11779            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11780            // delete the partially installed application. the data directory will have to be
11781            // restored if it was already existing
11782            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11783                // remove package from internal structures.  Note that we want deletePackageX to
11784                // delete the package data and cache directories that it created in
11785                // scanPackageLocked, unless those directories existed before we even tried to
11786                // install.
11787                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11788                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11789                                res.removedInfo, true);
11790            }
11791
11792        } catch (PackageManagerException e) {
11793            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11794        }
11795
11796        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11797    }
11798
11799    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11800        // Can't rotate keys during boot or if sharedUser.
11801        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11802                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11803            return false;
11804        }
11805        // app is using upgradeKeySets; make sure all are valid
11806        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11807        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11808        for (int i = 0; i < upgradeKeySets.length; i++) {
11809            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11810                Slog.wtf(TAG, "Package "
11811                         + (oldPs.name != null ? oldPs.name : "<null>")
11812                         + " contains upgrade-key-set reference to unknown key-set: "
11813                         + upgradeKeySets[i]
11814                         + " reverting to signatures check.");
11815                return false;
11816            }
11817        }
11818        return true;
11819    }
11820
11821    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11822        // Upgrade keysets are being used.  Determine if new package has a superset of the
11823        // required keys.
11824        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11825        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11826        for (int i = 0; i < upgradeKeySets.length; i++) {
11827            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11828            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11829                return true;
11830            }
11831        }
11832        return false;
11833    }
11834
11835    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11836            UserHandle user, String installerPackageName, String volumeUuid,
11837            PackageInstalledInfo res) {
11838        final PackageParser.Package oldPackage;
11839        final String pkgName = pkg.packageName;
11840        final int[] allUsers;
11841        final boolean[] perUserInstalled;
11842
11843        // First find the old package info and check signatures
11844        synchronized(mPackages) {
11845            oldPackage = mPackages.get(pkgName);
11846            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11847            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11848            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11849                if(!checkUpgradeKeySetLP(ps, pkg)) {
11850                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11851                            "New package not signed by keys specified by upgrade-keysets: "
11852                            + pkgName);
11853                    return;
11854                }
11855            } else {
11856                // default to original signature matching
11857                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11858                    != PackageManager.SIGNATURE_MATCH) {
11859                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11860                            "New package has a different signature: " + pkgName);
11861                    return;
11862                }
11863            }
11864
11865            // In case of rollback, remember per-user/profile install state
11866            allUsers = sUserManager.getUserIds();
11867            perUserInstalled = new boolean[allUsers.length];
11868            for (int i = 0; i < allUsers.length; i++) {
11869                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11870            }
11871        }
11872
11873        boolean sysPkg = (isSystemApp(oldPackage));
11874        if (sysPkg) {
11875            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11876                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11877        } else {
11878            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11879                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11880        }
11881    }
11882
11883    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11884            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11885            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11886            String volumeUuid, PackageInstalledInfo res) {
11887        String pkgName = deletedPackage.packageName;
11888        boolean deletedPkg = true;
11889        boolean updatedSettings = false;
11890
11891        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11892                + deletedPackage);
11893        long origUpdateTime;
11894        if (pkg.mExtras != null) {
11895            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11896        } else {
11897            origUpdateTime = 0;
11898        }
11899
11900        // First delete the existing package while retaining the data directory
11901        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11902                res.removedInfo, true)) {
11903            // If the existing package wasn't successfully deleted
11904            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11905            deletedPkg = false;
11906        } else {
11907            // Successfully deleted the old package; proceed with replace.
11908
11909            // If deleted package lived in a container, give users a chance to
11910            // relinquish resources before killing.
11911            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11912                if (DEBUG_INSTALL) {
11913                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11914                }
11915                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11916                final ArrayList<String> pkgList = new ArrayList<String>(1);
11917                pkgList.add(deletedPackage.applicationInfo.packageName);
11918                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11919            }
11920
11921            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11922            try {
11923                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
11924                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11925                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11926                        perUserInstalled, res, user);
11927                updatedSettings = true;
11928            } catch (PackageManagerException e) {
11929                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11930            }
11931        }
11932
11933        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11934            // remove package from internal structures.  Note that we want deletePackageX to
11935            // delete the package data and cache directories that it created in
11936            // scanPackageLocked, unless those directories existed before we even tried to
11937            // install.
11938            if(updatedSettings) {
11939                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11940                deletePackageLI(
11941                        pkgName, null, true, allUsers, perUserInstalled,
11942                        PackageManager.DELETE_KEEP_DATA,
11943                                res.removedInfo, true);
11944            }
11945            // Since we failed to install the new package we need to restore the old
11946            // package that we deleted.
11947            if (deletedPkg) {
11948                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11949                File restoreFile = new File(deletedPackage.codePath);
11950                // Parse old package
11951                boolean oldExternal = isExternal(deletedPackage);
11952                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11953                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11954                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11955                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11956                try {
11957                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
11958                            null);
11959                } catch (PackageManagerException e) {
11960                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11961                            + e.getMessage());
11962                    return;
11963                }
11964                // Restore of old package succeeded. Update permissions.
11965                // writer
11966                synchronized (mPackages) {
11967                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11968                            UPDATE_PERMISSIONS_ALL);
11969                    // can downgrade to reader
11970                    mSettings.writeLPr();
11971                }
11972                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11973            }
11974        }
11975    }
11976
11977    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11978            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11979            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11980            String volumeUuid, PackageInstalledInfo res) {
11981        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11982                + ", old=" + deletedPackage);
11983        boolean disabledSystem = false;
11984        boolean updatedSettings = false;
11985        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11986        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11987                != 0) {
11988            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11989        }
11990        String packageName = deletedPackage.packageName;
11991        if (packageName == null) {
11992            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11993                    "Attempt to delete null packageName.");
11994            return;
11995        }
11996        PackageParser.Package oldPkg;
11997        PackageSetting oldPkgSetting;
11998        // reader
11999        synchronized (mPackages) {
12000            oldPkg = mPackages.get(packageName);
12001            oldPkgSetting = mSettings.mPackages.get(packageName);
12002            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12003                    (oldPkgSetting == null)) {
12004                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12005                        "Couldn't find package:" + packageName + " information");
12006                return;
12007            }
12008        }
12009
12010        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12011
12012        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12013        res.removedInfo.removedPackage = packageName;
12014        // Remove existing system package
12015        removePackageLI(oldPkgSetting, true);
12016        // writer
12017        synchronized (mPackages) {
12018            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12019            if (!disabledSystem && deletedPackage != null) {
12020                // We didn't need to disable the .apk as a current system package,
12021                // which means we are replacing another update that is already
12022                // installed.  We need to make sure to delete the older one's .apk.
12023                res.removedInfo.args = createInstallArgsForExisting(0,
12024                        deletedPackage.applicationInfo.getCodePath(),
12025                        deletedPackage.applicationInfo.getResourcePath(),
12026                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12027            } else {
12028                res.removedInfo.args = null;
12029            }
12030        }
12031
12032        // Successfully disabled the old package. Now proceed with re-installation
12033        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12034
12035        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12036        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12037
12038        PackageParser.Package newPackage = null;
12039        try {
12040            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12041            if (newPackage.mExtras != null) {
12042                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12043                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12044                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12045
12046                // is the update attempting to change shared user? that isn't going to work...
12047                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12048                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12049                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12050                            + " to " + newPkgSetting.sharedUser);
12051                    updatedSettings = true;
12052                }
12053            }
12054
12055            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12056                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12057                        perUserInstalled, res, user);
12058                updatedSettings = true;
12059            }
12060
12061        } catch (PackageManagerException e) {
12062            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12063        }
12064
12065        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12066            // Re installation failed. Restore old information
12067            // Remove new pkg information
12068            if (newPackage != null) {
12069                removeInstalledPackageLI(newPackage, true);
12070            }
12071            // Add back the old system package
12072            try {
12073                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12074            } catch (PackageManagerException e) {
12075                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12076            }
12077            // Restore the old system information in Settings
12078            synchronized (mPackages) {
12079                if (disabledSystem) {
12080                    mSettings.enableSystemPackageLPw(packageName);
12081                }
12082                if (updatedSettings) {
12083                    mSettings.setInstallerPackageName(packageName,
12084                            oldPkgSetting.installerPackageName);
12085                }
12086                mSettings.writeLPr();
12087            }
12088        }
12089    }
12090
12091    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12092        // Collect all used permissions in the UID
12093        ArraySet<String> usedPermissions = new ArraySet<>();
12094        final int packageCount = su.packages.size();
12095        for (int i = 0; i < packageCount; i++) {
12096            PackageSetting ps = su.packages.valueAt(i);
12097            if (ps.pkg == null) {
12098                continue;
12099            }
12100            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12101            for (int j = 0; j < requestedPermCount; j++) {
12102                String permission = ps.pkg.requestedPermissions.get(j);
12103                BasePermission bp = mSettings.mPermissions.get(permission);
12104                if (bp != null) {
12105                    usedPermissions.add(permission);
12106                }
12107            }
12108        }
12109
12110        PermissionsState permissionsState = su.getPermissionsState();
12111        // Prune install permissions
12112        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12113        final int installPermCount = installPermStates.size();
12114        for (int i = installPermCount - 1; i >= 0;  i--) {
12115            PermissionState permissionState = installPermStates.get(i);
12116            if (!usedPermissions.contains(permissionState.getName())) {
12117                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12118                if (bp != null) {
12119                    permissionsState.revokeInstallPermission(bp);
12120                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12121                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12122                }
12123            }
12124        }
12125
12126        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12127
12128        // Prune runtime permissions
12129        for (int userId : allUserIds) {
12130            List<PermissionState> runtimePermStates = permissionsState
12131                    .getRuntimePermissionStates(userId);
12132            final int runtimePermCount = runtimePermStates.size();
12133            for (int i = runtimePermCount - 1; i >= 0; i--) {
12134                PermissionState permissionState = runtimePermStates.get(i);
12135                if (!usedPermissions.contains(permissionState.getName())) {
12136                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12137                    if (bp != null) {
12138                        permissionsState.revokeRuntimePermission(bp, userId);
12139                        permissionsState.updatePermissionFlags(bp, userId,
12140                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12141                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12142                                runtimePermissionChangedUserIds, userId);
12143                    }
12144                }
12145            }
12146        }
12147
12148        return runtimePermissionChangedUserIds;
12149    }
12150
12151    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12152            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12153            UserHandle user) {
12154        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12155
12156        String pkgName = newPackage.packageName;
12157        synchronized (mPackages) {
12158            //write settings. the installStatus will be incomplete at this stage.
12159            //note that the new package setting would have already been
12160            //added to mPackages. It hasn't been persisted yet.
12161            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12162            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12163            mSettings.writeLPr();
12164            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12165        }
12166
12167        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12168        synchronized (mPackages) {
12169            updatePermissionsLPw(newPackage.packageName, newPackage,
12170                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12171                            ? UPDATE_PERMISSIONS_ALL : 0));
12172            // For system-bundled packages, we assume that installing an upgraded version
12173            // of the package implies that the user actually wants to run that new code,
12174            // so we enable the package.
12175            PackageSetting ps = mSettings.mPackages.get(pkgName);
12176            if (ps != null) {
12177                if (isSystemApp(newPackage)) {
12178                    // NB: implicit assumption that system package upgrades apply to all users
12179                    if (DEBUG_INSTALL) {
12180                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12181                    }
12182                    if (res.origUsers != null) {
12183                        for (int userHandle : res.origUsers) {
12184                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12185                                    userHandle, installerPackageName);
12186                        }
12187                    }
12188                    // Also convey the prior install/uninstall state
12189                    if (allUsers != null && perUserInstalled != null) {
12190                        for (int i = 0; i < allUsers.length; i++) {
12191                            if (DEBUG_INSTALL) {
12192                                Slog.d(TAG, "    user " + allUsers[i]
12193                                        + " => " + perUserInstalled[i]);
12194                            }
12195                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12196                        }
12197                        // these install state changes will be persisted in the
12198                        // upcoming call to mSettings.writeLPr().
12199                    }
12200                }
12201                // It's implied that when a user requests installation, they want the app to be
12202                // installed and enabled.
12203                int userId = user.getIdentifier();
12204                if (userId != UserHandle.USER_ALL) {
12205                    ps.setInstalled(true, userId);
12206                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12207                }
12208            }
12209            res.name = pkgName;
12210            res.uid = newPackage.applicationInfo.uid;
12211            res.pkg = newPackage;
12212            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12213            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12214            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12215            //to update install status
12216            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12217            mSettings.writeLPr();
12218            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12219        }
12220
12221        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12222    }
12223
12224    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12225        try {
12226            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12227            installPackageLI(args, res);
12228        } finally {
12229            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12230        }
12231    }
12232
12233    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12234        final int installFlags = args.installFlags;
12235        final String installerPackageName = args.installerPackageName;
12236        final String volumeUuid = args.volumeUuid;
12237        final File tmpPackageFile = new File(args.getCodePath());
12238        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12239        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12240                || (args.volumeUuid != null));
12241        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12242        boolean replace = false;
12243        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12244        if (args.move != null) {
12245            // moving a complete application; perfom an initial scan on the new install location
12246            scanFlags |= SCAN_INITIAL;
12247        }
12248        // Result object to be returned
12249        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12250
12251        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12252
12253        // Retrieve PackageSettings and parse package
12254        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12255                | PackageParser.PARSE_ENFORCE_CODE
12256                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12257                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12258                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12259        PackageParser pp = new PackageParser();
12260        pp.setSeparateProcesses(mSeparateProcesses);
12261        pp.setDisplayMetrics(mMetrics);
12262
12263        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12264        final PackageParser.Package pkg;
12265        try {
12266            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12267        } catch (PackageParserException e) {
12268            res.setError("Failed parse during installPackageLI", e);
12269            return;
12270        } finally {
12271            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12272        }
12273
12274        // Mark that we have an install time CPU ABI override.
12275        pkg.cpuAbiOverride = args.abiOverride;
12276
12277        String pkgName = res.name = pkg.packageName;
12278        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12279            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12280                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12281                return;
12282            }
12283        }
12284
12285        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12286        try {
12287            pp.collectCertificates(pkg, parseFlags);
12288        } catch (PackageParserException e) {
12289            res.setError("Failed collect during installPackageLI", e);
12290            return;
12291        } finally {
12292            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12293        }
12294
12295        /* If the installer passed in a manifest digest, compare it now. */
12296        if (args.manifestDigest != null) {
12297            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12298            try {
12299                pp.collectManifestDigest(pkg);
12300            } catch (PackageParserException e) {
12301                res.setError("Failed collect during installPackageLI", e);
12302                return;
12303            } finally {
12304                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12305            }
12306
12307            if (DEBUG_INSTALL) {
12308                final String parsedManifest = pkg.manifestDigest == null ? "null"
12309                        : pkg.manifestDigest.toString();
12310                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12311                        + parsedManifest);
12312            }
12313
12314            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12315                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12316                return;
12317            }
12318        } else if (DEBUG_INSTALL) {
12319            final String parsedManifest = pkg.manifestDigest == null
12320                    ? "null" : pkg.manifestDigest.toString();
12321            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12322        }
12323
12324        // Get rid of all references to package scan path via parser.
12325        pp = null;
12326        String oldCodePath = null;
12327        boolean systemApp = false;
12328        synchronized (mPackages) {
12329            // Check if installing already existing package
12330            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12331                String oldName = mSettings.mRenamedPackages.get(pkgName);
12332                if (pkg.mOriginalPackages != null
12333                        && pkg.mOriginalPackages.contains(oldName)
12334                        && mPackages.containsKey(oldName)) {
12335                    // This package is derived from an original package,
12336                    // and this device has been updating from that original
12337                    // name.  We must continue using the original name, so
12338                    // rename the new package here.
12339                    pkg.setPackageName(oldName);
12340                    pkgName = pkg.packageName;
12341                    replace = true;
12342                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12343                            + oldName + " pkgName=" + pkgName);
12344                } else if (mPackages.containsKey(pkgName)) {
12345                    // This package, under its official name, already exists
12346                    // on the device; we should replace it.
12347                    replace = true;
12348                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12349                }
12350
12351                // Prevent apps opting out from runtime permissions
12352                if (replace) {
12353                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12354                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12355                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12356                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12357                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12358                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12359                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12360                                        + " doesn't support runtime permissions but the old"
12361                                        + " target SDK " + oldTargetSdk + " does.");
12362                        return;
12363                    }
12364                }
12365            }
12366
12367            PackageSetting ps = mSettings.mPackages.get(pkgName);
12368            if (ps != null) {
12369                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12370
12371                // Quick sanity check that we're signed correctly if updating;
12372                // we'll check this again later when scanning, but we want to
12373                // bail early here before tripping over redefined permissions.
12374                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12375                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12376                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12377                                + pkg.packageName + " upgrade keys do not match the "
12378                                + "previously installed version");
12379                        return;
12380                    }
12381                } else {
12382                    try {
12383                        verifySignaturesLP(ps, pkg);
12384                    } catch (PackageManagerException e) {
12385                        res.setError(e.error, e.getMessage());
12386                        return;
12387                    }
12388                }
12389
12390                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12391                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12392                    systemApp = (ps.pkg.applicationInfo.flags &
12393                            ApplicationInfo.FLAG_SYSTEM) != 0;
12394                }
12395                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12396            }
12397
12398            // Check whether the newly-scanned package wants to define an already-defined perm
12399            int N = pkg.permissions.size();
12400            for (int i = N-1; i >= 0; i--) {
12401                PackageParser.Permission perm = pkg.permissions.get(i);
12402                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12403                if (bp != null) {
12404                    // If the defining package is signed with our cert, it's okay.  This
12405                    // also includes the "updating the same package" case, of course.
12406                    // "updating same package" could also involve key-rotation.
12407                    final boolean sigsOk;
12408                    if (bp.sourcePackage.equals(pkg.packageName)
12409                            && (bp.packageSetting instanceof PackageSetting)
12410                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12411                                    scanFlags))) {
12412                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12413                    } else {
12414                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12415                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12416                    }
12417                    if (!sigsOk) {
12418                        // If the owning package is the system itself, we log but allow
12419                        // install to proceed; we fail the install on all other permission
12420                        // redefinitions.
12421                        if (!bp.sourcePackage.equals("android")) {
12422                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12423                                    + pkg.packageName + " attempting to redeclare permission "
12424                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12425                            res.origPermission = perm.info.name;
12426                            res.origPackage = bp.sourcePackage;
12427                            return;
12428                        } else {
12429                            Slog.w(TAG, "Package " + pkg.packageName
12430                                    + " attempting to redeclare system permission "
12431                                    + perm.info.name + "; ignoring new declaration");
12432                            pkg.permissions.remove(i);
12433                        }
12434                    }
12435                }
12436            }
12437
12438        }
12439
12440        if (systemApp && onExternal) {
12441            // Disable updates to system apps on sdcard
12442            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12443                    "Cannot install updates to system apps on sdcard");
12444            return;
12445        }
12446
12447        if (args.move != null) {
12448            // We did an in-place move, so dex is ready to roll
12449            scanFlags |= SCAN_NO_DEX;
12450            scanFlags |= SCAN_MOVE;
12451
12452            synchronized (mPackages) {
12453                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12454                if (ps == null) {
12455                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12456                            "Missing settings for moved package " + pkgName);
12457                }
12458
12459                // We moved the entire application as-is, so bring over the
12460                // previously derived ABI information.
12461                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12462                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12463            }
12464
12465        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12466            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12467            scanFlags |= SCAN_NO_DEX;
12468
12469            try {
12470                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12471                        true /* extract libs */);
12472            } catch (PackageManagerException pme) {
12473                Slog.e(TAG, "Error deriving application ABI", pme);
12474                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12475                return;
12476            }
12477        }
12478
12479        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12480            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12481            return;
12482        }
12483
12484        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12485
12486        if (replace) {
12487            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12488                    installerPackageName, volumeUuid, res);
12489        } else {
12490            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12491                    args.user, installerPackageName, volumeUuid, res);
12492        }
12493        synchronized (mPackages) {
12494            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12495            if (ps != null) {
12496                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12497            }
12498        }
12499    }
12500
12501    private void startIntentFilterVerifications(int userId, boolean replacing,
12502            PackageParser.Package pkg) {
12503        if (mIntentFilterVerifierComponent == null) {
12504            Slog.w(TAG, "No IntentFilter verification will not be done as "
12505                    + "there is no IntentFilterVerifier available!");
12506            return;
12507        }
12508
12509        final int verifierUid = getPackageUid(
12510                mIntentFilterVerifierComponent.getPackageName(),
12511                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12512
12513        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12514        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12515        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12516        mHandler.sendMessage(msg);
12517    }
12518
12519    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12520            PackageParser.Package pkg) {
12521        int size = pkg.activities.size();
12522        if (size == 0) {
12523            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12524                    "No activity, so no need to verify any IntentFilter!");
12525            return;
12526        }
12527
12528        final boolean hasDomainURLs = hasDomainURLs(pkg);
12529        if (!hasDomainURLs) {
12530            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12531                    "No domain URLs, so no need to verify any IntentFilter!");
12532            return;
12533        }
12534
12535        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12536                + " if any IntentFilter from the " + size
12537                + " Activities needs verification ...");
12538
12539        int count = 0;
12540        final String packageName = pkg.packageName;
12541
12542        synchronized (mPackages) {
12543            // If this is a new install and we see that we've already run verification for this
12544            // package, we have nothing to do: it means the state was restored from backup.
12545            if (!replacing) {
12546                IntentFilterVerificationInfo ivi =
12547                        mSettings.getIntentFilterVerificationLPr(packageName);
12548                if (ivi != null) {
12549                    if (DEBUG_DOMAIN_VERIFICATION) {
12550                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12551                                + ivi.getStatusString());
12552                    }
12553                    return;
12554                }
12555            }
12556
12557            // If any filters need to be verified, then all need to be.
12558            boolean needToVerify = false;
12559            for (PackageParser.Activity a : pkg.activities) {
12560                for (ActivityIntentInfo filter : a.intents) {
12561                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12562                        if (DEBUG_DOMAIN_VERIFICATION) {
12563                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12564                        }
12565                        needToVerify = true;
12566                        break;
12567                    }
12568                }
12569            }
12570
12571            if (needToVerify) {
12572                final int verificationId = mIntentFilterVerificationToken++;
12573                for (PackageParser.Activity a : pkg.activities) {
12574                    for (ActivityIntentInfo filter : a.intents) {
12575                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12576                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12577                                    "Verification needed for IntentFilter:" + filter.toString());
12578                            mIntentFilterVerifier.addOneIntentFilterVerification(
12579                                    verifierUid, userId, verificationId, filter, packageName);
12580                            count++;
12581                        }
12582                    }
12583                }
12584            }
12585        }
12586
12587        if (count > 0) {
12588            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12589                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12590                    +  " for userId:" + userId);
12591            mIntentFilterVerifier.startVerifications(userId);
12592        } else {
12593            if (DEBUG_DOMAIN_VERIFICATION) {
12594                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12595            }
12596        }
12597    }
12598
12599    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12600        final ComponentName cn  = filter.activity.getComponentName();
12601        final String packageName = cn.getPackageName();
12602
12603        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12604                packageName);
12605        if (ivi == null) {
12606            return true;
12607        }
12608        int status = ivi.getStatus();
12609        switch (status) {
12610            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12611            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12612                return true;
12613
12614            default:
12615                // Nothing to do
12616                return false;
12617        }
12618    }
12619
12620    private static boolean isMultiArch(PackageSetting ps) {
12621        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12622    }
12623
12624    private static boolean isMultiArch(ApplicationInfo info) {
12625        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12626    }
12627
12628    private static boolean isExternal(PackageParser.Package pkg) {
12629        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12630    }
12631
12632    private static boolean isExternal(PackageSetting ps) {
12633        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12634    }
12635
12636    private static boolean isExternal(ApplicationInfo info) {
12637        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12638    }
12639
12640    private static boolean isSystemApp(PackageParser.Package pkg) {
12641        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12642    }
12643
12644    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12645        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12646    }
12647
12648    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12649        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12650    }
12651
12652    private static boolean isSystemApp(PackageSetting ps) {
12653        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12654    }
12655
12656    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12657        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12658    }
12659
12660    private int packageFlagsToInstallFlags(PackageSetting ps) {
12661        int installFlags = 0;
12662        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12663            // This existing package was an external ASEC install when we have
12664            // the external flag without a UUID
12665            installFlags |= PackageManager.INSTALL_EXTERNAL;
12666        }
12667        if (ps.isForwardLocked()) {
12668            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12669        }
12670        return installFlags;
12671    }
12672
12673    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12674        if (isExternal(pkg)) {
12675            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12676                return StorageManager.UUID_PRIMARY_PHYSICAL;
12677            } else {
12678                return pkg.volumeUuid;
12679            }
12680        } else {
12681            return StorageManager.UUID_PRIVATE_INTERNAL;
12682        }
12683    }
12684
12685    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12686        if (isExternal(pkg)) {
12687            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12688                return mSettings.getExternalVersion();
12689            } else {
12690                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12691            }
12692        } else {
12693            return mSettings.getInternalVersion();
12694        }
12695    }
12696
12697    private void deleteTempPackageFiles() {
12698        final FilenameFilter filter = new FilenameFilter() {
12699            public boolean accept(File dir, String name) {
12700                return name.startsWith("vmdl") && name.endsWith(".tmp");
12701            }
12702        };
12703        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12704            file.delete();
12705        }
12706    }
12707
12708    @Override
12709    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12710            int flags) {
12711        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12712                flags);
12713    }
12714
12715    @Override
12716    public void deletePackage(final String packageName,
12717            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12718        mContext.enforceCallingOrSelfPermission(
12719                android.Manifest.permission.DELETE_PACKAGES, null);
12720        Preconditions.checkNotNull(packageName);
12721        Preconditions.checkNotNull(observer);
12722        final int uid = Binder.getCallingUid();
12723        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
12724        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
12725        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
12726            mContext.enforceCallingPermission(
12727                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12728                    "deletePackage for user " + userId);
12729        }
12730
12731        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12732            try {
12733                observer.onPackageDeleted(packageName,
12734                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12735            } catch (RemoteException re) {
12736            }
12737            return;
12738        }
12739
12740        for (int currentUserId : users) {
12741            if (getBlockUninstallForUser(packageName, currentUserId)) {
12742                try {
12743                    observer.onPackageDeleted(packageName,
12744                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
12745                } catch (RemoteException re) {
12746                }
12747                return;
12748            }
12749        }
12750
12751        if (DEBUG_REMOVE) {
12752            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12753        }
12754        // Queue up an async operation since the package deletion may take a little while.
12755        mHandler.post(new Runnable() {
12756            public void run() {
12757                mHandler.removeCallbacks(this);
12758                final int returnCode = deletePackageX(packageName, userId, flags);
12759                try {
12760                    observer.onPackageDeleted(packageName, returnCode, null);
12761                } catch (RemoteException e) {
12762                    Log.i(TAG, "Observer no longer exists.");
12763                } //end catch
12764            } //end run
12765        });
12766    }
12767
12768    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12769        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12770                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12771        try {
12772            if (dpm != null) {
12773                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwner();
12774                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
12775                        : deviceOwnerComponentName.getPackageName();
12776                // Does the package contains the device owner?
12777                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
12778                // this check is probably not needed, since DO should be registered as a device
12779                // admin on some user too. (Original bug for this: b/17657954)
12780                if (packageName.equals(deviceOwnerPackageName)) {
12781                    return true;
12782                }
12783                // Does it contain a device admin for any user?
12784                int[] users;
12785                if (userId == UserHandle.USER_ALL) {
12786                    users = sUserManager.getUserIds();
12787                } else {
12788                    users = new int[]{userId};
12789                }
12790                for (int i = 0; i < users.length; ++i) {
12791                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12792                        return true;
12793                    }
12794                }
12795            }
12796        } catch (RemoteException e) {
12797        }
12798        return false;
12799    }
12800
12801    /**
12802     *  This method is an internal method that could be get invoked either
12803     *  to delete an installed package or to clean up a failed installation.
12804     *  After deleting an installed package, a broadcast is sent to notify any
12805     *  listeners that the package has been installed. For cleaning up a failed
12806     *  installation, the broadcast is not necessary since the package's
12807     *  installation wouldn't have sent the initial broadcast either
12808     *  The key steps in deleting a package are
12809     *  deleting the package information in internal structures like mPackages,
12810     *  deleting the packages base directories through installd
12811     *  updating mSettings to reflect current status
12812     *  persisting settings for later use
12813     *  sending a broadcast if necessary
12814     */
12815    private int deletePackageX(String packageName, int userId, int flags) {
12816        final PackageRemovedInfo info = new PackageRemovedInfo();
12817        final boolean res;
12818
12819        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12820                ? UserHandle.ALL : new UserHandle(userId);
12821
12822        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12823            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12824            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12825        }
12826
12827        boolean removedForAllUsers = false;
12828        boolean systemUpdate = false;
12829
12830        // for the uninstall-updates case and restricted profiles, remember the per-
12831        // userhandle installed state
12832        int[] allUsers;
12833        boolean[] perUserInstalled;
12834        synchronized (mPackages) {
12835            PackageSetting ps = mSettings.mPackages.get(packageName);
12836            allUsers = sUserManager.getUserIds();
12837            perUserInstalled = new boolean[allUsers.length];
12838            for (int i = 0; i < allUsers.length; i++) {
12839                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12840            }
12841        }
12842
12843        synchronized (mInstallLock) {
12844            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12845            res = deletePackageLI(packageName, removeForUser,
12846                    true, allUsers, perUserInstalled,
12847                    flags | REMOVE_CHATTY, info, true);
12848            systemUpdate = info.isRemovedPackageSystemUpdate;
12849            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12850                removedForAllUsers = true;
12851            }
12852            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12853                    + " removedForAllUsers=" + removedForAllUsers);
12854        }
12855
12856        if (res) {
12857            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12858
12859            // If the removed package was a system update, the old system package
12860            // was re-enabled; we need to broadcast this information
12861            if (systemUpdate) {
12862                Bundle extras = new Bundle(1);
12863                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12864                        ? info.removedAppId : info.uid);
12865                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12866
12867                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12868                        extras, null, null, null);
12869                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12870                        extras, null, null, null);
12871                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12872                        null, packageName, null, null);
12873            }
12874        }
12875        // Force a gc here.
12876        Runtime.getRuntime().gc();
12877        // Delete the resources here after sending the broadcast to let
12878        // other processes clean up before deleting resources.
12879        if (info.args != null) {
12880            synchronized (mInstallLock) {
12881                info.args.doPostDeleteLI(true);
12882            }
12883        }
12884
12885        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12886    }
12887
12888    class PackageRemovedInfo {
12889        String removedPackage;
12890        int uid = -1;
12891        int removedAppId = -1;
12892        int[] removedUsers = null;
12893        boolean isRemovedPackageSystemUpdate = false;
12894        // Clean up resources deleted packages.
12895        InstallArgs args = null;
12896
12897        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12898            Bundle extras = new Bundle(1);
12899            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12900            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12901            if (replacing) {
12902                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12903            }
12904            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12905            if (removedPackage != null) {
12906                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12907                        extras, null, null, removedUsers);
12908                if (fullRemove && !replacing) {
12909                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12910                            extras, null, null, removedUsers);
12911                }
12912            }
12913            if (removedAppId >= 0) {
12914                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12915                        removedUsers);
12916            }
12917        }
12918    }
12919
12920    /*
12921     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12922     * flag is not set, the data directory is removed as well.
12923     * make sure this flag is set for partially installed apps. If not its meaningless to
12924     * delete a partially installed application.
12925     */
12926    private void removePackageDataLI(PackageSetting ps,
12927            int[] allUserHandles, boolean[] perUserInstalled,
12928            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12929        String packageName = ps.name;
12930        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12931        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12932        // Retrieve object to delete permissions for shared user later on
12933        final PackageSetting deletedPs;
12934        // reader
12935        synchronized (mPackages) {
12936            deletedPs = mSettings.mPackages.get(packageName);
12937            if (outInfo != null) {
12938                outInfo.removedPackage = packageName;
12939                outInfo.removedUsers = deletedPs != null
12940                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12941                        : null;
12942            }
12943        }
12944        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12945            removeDataDirsLI(ps.volumeUuid, packageName);
12946            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12947        }
12948        // writer
12949        synchronized (mPackages) {
12950            if (deletedPs != null) {
12951                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12952                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12953                    clearDefaultBrowserIfNeeded(packageName);
12954                    if (outInfo != null) {
12955                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12956                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12957                    }
12958                    updatePermissionsLPw(deletedPs.name, null, 0);
12959                    if (deletedPs.sharedUser != null) {
12960                        // Remove permissions associated with package. Since runtime
12961                        // permissions are per user we have to kill the removed package
12962                        // or packages running under the shared user of the removed
12963                        // package if revoking the permissions requested only by the removed
12964                        // package is successful and this causes a change in gids.
12965                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12966                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12967                                    userId);
12968                            if (userIdToKill == UserHandle.USER_ALL
12969                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
12970                                // If gids changed for this user, kill all affected packages.
12971                                mHandler.post(new Runnable() {
12972                                    @Override
12973                                    public void run() {
12974                                        // This has to happen with no lock held.
12975                                        killApplication(deletedPs.name, deletedPs.appId,
12976                                                KILL_APP_REASON_GIDS_CHANGED);
12977                                    }
12978                                });
12979                                break;
12980                            }
12981                        }
12982                    }
12983                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12984                }
12985                // make sure to preserve per-user disabled state if this removal was just
12986                // a downgrade of a system app to the factory package
12987                if (allUserHandles != null && perUserInstalled != null) {
12988                    if (DEBUG_REMOVE) {
12989                        Slog.d(TAG, "Propagating install state across downgrade");
12990                    }
12991                    for (int i = 0; i < allUserHandles.length; i++) {
12992                        if (DEBUG_REMOVE) {
12993                            Slog.d(TAG, "    user " + allUserHandles[i]
12994                                    + " => " + perUserInstalled[i]);
12995                        }
12996                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12997                    }
12998                }
12999            }
13000            // can downgrade to reader
13001            if (writeSettings) {
13002                // Save settings now
13003                mSettings.writeLPr();
13004            }
13005        }
13006        if (outInfo != null) {
13007            // A user ID was deleted here. Go through all users and remove it
13008            // from KeyStore.
13009            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13010        }
13011    }
13012
13013    static boolean locationIsPrivileged(File path) {
13014        try {
13015            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13016                    .getCanonicalPath();
13017            return path.getCanonicalPath().startsWith(privilegedAppDir);
13018        } catch (IOException e) {
13019            Slog.e(TAG, "Unable to access code path " + path);
13020        }
13021        return false;
13022    }
13023
13024    /*
13025     * Tries to delete system package.
13026     */
13027    private boolean deleteSystemPackageLI(PackageSetting newPs,
13028            int[] allUserHandles, boolean[] perUserInstalled,
13029            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13030        final boolean applyUserRestrictions
13031                = (allUserHandles != null) && (perUserInstalled != null);
13032        PackageSetting disabledPs = null;
13033        // Confirm if the system package has been updated
13034        // An updated system app can be deleted. This will also have to restore
13035        // the system pkg from system partition
13036        // reader
13037        synchronized (mPackages) {
13038            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13039        }
13040        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13041                + " disabledPs=" + disabledPs);
13042        if (disabledPs == null) {
13043            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13044            return false;
13045        } else if (DEBUG_REMOVE) {
13046            Slog.d(TAG, "Deleting system pkg from data partition");
13047        }
13048        if (DEBUG_REMOVE) {
13049            if (applyUserRestrictions) {
13050                Slog.d(TAG, "Remembering install states:");
13051                for (int i = 0; i < allUserHandles.length; i++) {
13052                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13053                }
13054            }
13055        }
13056        // Delete the updated package
13057        outInfo.isRemovedPackageSystemUpdate = true;
13058        if (disabledPs.versionCode < newPs.versionCode) {
13059            // Delete data for downgrades
13060            flags &= ~PackageManager.DELETE_KEEP_DATA;
13061        } else {
13062            // Preserve data by setting flag
13063            flags |= PackageManager.DELETE_KEEP_DATA;
13064        }
13065        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13066                allUserHandles, perUserInstalled, outInfo, writeSettings);
13067        if (!ret) {
13068            return false;
13069        }
13070        // writer
13071        synchronized (mPackages) {
13072            // Reinstate the old system package
13073            mSettings.enableSystemPackageLPw(newPs.name);
13074            // Remove any native libraries from the upgraded package.
13075            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13076        }
13077        // Install the system package
13078        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13079        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13080        if (locationIsPrivileged(disabledPs.codePath)) {
13081            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13082        }
13083
13084        final PackageParser.Package newPkg;
13085        try {
13086            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13087        } catch (PackageManagerException e) {
13088            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13089            return false;
13090        }
13091
13092        // writer
13093        synchronized (mPackages) {
13094            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13095
13096            // Propagate the permissions state as we do not want to drop on the floor
13097            // runtime permissions. The update permissions method below will take
13098            // care of removing obsolete permissions and grant install permissions.
13099            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13100            updatePermissionsLPw(newPkg.packageName, newPkg,
13101                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13102
13103            if (applyUserRestrictions) {
13104                if (DEBUG_REMOVE) {
13105                    Slog.d(TAG, "Propagating install state across reinstall");
13106                }
13107                for (int i = 0; i < allUserHandles.length; i++) {
13108                    if (DEBUG_REMOVE) {
13109                        Slog.d(TAG, "    user " + allUserHandles[i]
13110                                + " => " + perUserInstalled[i]);
13111                    }
13112                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13113
13114                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13115                }
13116                // Regardless of writeSettings we need to ensure that this restriction
13117                // state propagation is persisted
13118                mSettings.writeAllUsersPackageRestrictionsLPr();
13119            }
13120            // can downgrade to reader here
13121            if (writeSettings) {
13122                mSettings.writeLPr();
13123            }
13124        }
13125        return true;
13126    }
13127
13128    private boolean deleteInstalledPackageLI(PackageSetting ps,
13129            boolean deleteCodeAndResources, int flags,
13130            int[] allUserHandles, boolean[] perUserInstalled,
13131            PackageRemovedInfo outInfo, boolean writeSettings) {
13132        if (outInfo != null) {
13133            outInfo.uid = ps.appId;
13134        }
13135
13136        // Delete package data from internal structures and also remove data if flag is set
13137        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13138
13139        // Delete application code and resources
13140        if (deleteCodeAndResources && (outInfo != null)) {
13141            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13142                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13143            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13144        }
13145        return true;
13146    }
13147
13148    @Override
13149    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13150            int userId) {
13151        mContext.enforceCallingOrSelfPermission(
13152                android.Manifest.permission.DELETE_PACKAGES, null);
13153        synchronized (mPackages) {
13154            PackageSetting ps = mSettings.mPackages.get(packageName);
13155            if (ps == null) {
13156                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13157                return false;
13158            }
13159            if (!ps.getInstalled(userId)) {
13160                // Can't block uninstall for an app that is not installed or enabled.
13161                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13162                return false;
13163            }
13164            ps.setBlockUninstall(blockUninstall, userId);
13165            mSettings.writePackageRestrictionsLPr(userId);
13166        }
13167        return true;
13168    }
13169
13170    @Override
13171    public boolean getBlockUninstallForUser(String packageName, int userId) {
13172        synchronized (mPackages) {
13173            PackageSetting ps = mSettings.mPackages.get(packageName);
13174            if (ps == null) {
13175                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13176                return false;
13177            }
13178            return ps.getBlockUninstall(userId);
13179        }
13180    }
13181
13182    /*
13183     * This method handles package deletion in general
13184     */
13185    private boolean deletePackageLI(String packageName, UserHandle user,
13186            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13187            int flags, PackageRemovedInfo outInfo,
13188            boolean writeSettings) {
13189        if (packageName == null) {
13190            Slog.w(TAG, "Attempt to delete null packageName.");
13191            return false;
13192        }
13193        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13194        PackageSetting ps;
13195        boolean dataOnly = false;
13196        int removeUser = -1;
13197        int appId = -1;
13198        synchronized (mPackages) {
13199            ps = mSettings.mPackages.get(packageName);
13200            if (ps == null) {
13201                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13202                return false;
13203            }
13204            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13205                    && user.getIdentifier() != UserHandle.USER_ALL) {
13206                // The caller is asking that the package only be deleted for a single
13207                // user.  To do this, we just mark its uninstalled state and delete
13208                // its data.  If this is a system app, we only allow this to happen if
13209                // they have set the special DELETE_SYSTEM_APP which requests different
13210                // semantics than normal for uninstalling system apps.
13211                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13212                final int userId = user.getIdentifier();
13213                ps.setUserState(userId,
13214                        COMPONENT_ENABLED_STATE_DEFAULT,
13215                        false, //installed
13216                        true,  //stopped
13217                        true,  //notLaunched
13218                        false, //hidden
13219                        null, null, null,
13220                        false, // blockUninstall
13221                        ps.readUserState(userId).domainVerificationStatus, 0);
13222                if (!isSystemApp(ps)) {
13223                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13224                        // Other user still have this package installed, so all
13225                        // we need to do is clear this user's data and save that
13226                        // it is uninstalled.
13227                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13228                        removeUser = user.getIdentifier();
13229                        appId = ps.appId;
13230                        scheduleWritePackageRestrictionsLocked(removeUser);
13231                    } else {
13232                        // We need to set it back to 'installed' so the uninstall
13233                        // broadcasts will be sent correctly.
13234                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13235                        ps.setInstalled(true, user.getIdentifier());
13236                    }
13237                } else {
13238                    // This is a system app, so we assume that the
13239                    // other users still have this package installed, so all
13240                    // we need to do is clear this user's data and save that
13241                    // it is uninstalled.
13242                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13243                    removeUser = user.getIdentifier();
13244                    appId = ps.appId;
13245                    scheduleWritePackageRestrictionsLocked(removeUser);
13246                }
13247            }
13248        }
13249
13250        if (removeUser >= 0) {
13251            // From above, we determined that we are deleting this only
13252            // for a single user.  Continue the work here.
13253            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13254            if (outInfo != null) {
13255                outInfo.removedPackage = packageName;
13256                outInfo.removedAppId = appId;
13257                outInfo.removedUsers = new int[] {removeUser};
13258            }
13259            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13260            removeKeystoreDataIfNeeded(removeUser, appId);
13261            schedulePackageCleaning(packageName, removeUser, false);
13262            synchronized (mPackages) {
13263                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13264                    scheduleWritePackageRestrictionsLocked(removeUser);
13265                }
13266                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13267            }
13268            return true;
13269        }
13270
13271        if (dataOnly) {
13272            // Delete application data first
13273            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13274            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13275            return true;
13276        }
13277
13278        boolean ret = false;
13279        if (isSystemApp(ps)) {
13280            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13281            // When an updated system application is deleted we delete the existing resources as well and
13282            // fall back to existing code in system partition
13283            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13284                    flags, outInfo, writeSettings);
13285        } else {
13286            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13287            // Kill application pre-emptively especially for apps on sd.
13288            killApplication(packageName, ps.appId, "uninstall pkg");
13289            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13290                    allUserHandles, perUserInstalled,
13291                    outInfo, writeSettings);
13292        }
13293
13294        return ret;
13295    }
13296
13297    private final class ClearStorageConnection implements ServiceConnection {
13298        IMediaContainerService mContainerService;
13299
13300        @Override
13301        public void onServiceConnected(ComponentName name, IBinder service) {
13302            synchronized (this) {
13303                mContainerService = IMediaContainerService.Stub.asInterface(service);
13304                notifyAll();
13305            }
13306        }
13307
13308        @Override
13309        public void onServiceDisconnected(ComponentName name) {
13310        }
13311    }
13312
13313    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13314        final boolean mounted;
13315        if (Environment.isExternalStorageEmulated()) {
13316            mounted = true;
13317        } else {
13318            final String status = Environment.getExternalStorageState();
13319
13320            mounted = status.equals(Environment.MEDIA_MOUNTED)
13321                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13322        }
13323
13324        if (!mounted) {
13325            return;
13326        }
13327
13328        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13329        int[] users;
13330        if (userId == UserHandle.USER_ALL) {
13331            users = sUserManager.getUserIds();
13332        } else {
13333            users = new int[] { userId };
13334        }
13335        final ClearStorageConnection conn = new ClearStorageConnection();
13336        if (mContext.bindServiceAsUser(
13337                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13338            try {
13339                for (int curUser : users) {
13340                    long timeout = SystemClock.uptimeMillis() + 5000;
13341                    synchronized (conn) {
13342                        long now = SystemClock.uptimeMillis();
13343                        while (conn.mContainerService == null && now < timeout) {
13344                            try {
13345                                conn.wait(timeout - now);
13346                            } catch (InterruptedException e) {
13347                            }
13348                        }
13349                    }
13350                    if (conn.mContainerService == null) {
13351                        return;
13352                    }
13353
13354                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13355                    clearDirectory(conn.mContainerService,
13356                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13357                    if (allData) {
13358                        clearDirectory(conn.mContainerService,
13359                                userEnv.buildExternalStorageAppDataDirs(packageName));
13360                        clearDirectory(conn.mContainerService,
13361                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13362                    }
13363                }
13364            } finally {
13365                mContext.unbindService(conn);
13366            }
13367        }
13368    }
13369
13370    @Override
13371    public void clearApplicationUserData(final String packageName,
13372            final IPackageDataObserver observer, final int userId) {
13373        mContext.enforceCallingOrSelfPermission(
13374                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13375        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13376        // Queue up an async operation since the package deletion may take a little while.
13377        mHandler.post(new Runnable() {
13378            public void run() {
13379                mHandler.removeCallbacks(this);
13380                final boolean succeeded;
13381                synchronized (mInstallLock) {
13382                    succeeded = clearApplicationUserDataLI(packageName, userId);
13383                }
13384                clearExternalStorageDataSync(packageName, userId, true);
13385                if (succeeded) {
13386                    // invoke DeviceStorageMonitor's update method to clear any notifications
13387                    DeviceStorageMonitorInternal
13388                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13389                    if (dsm != null) {
13390                        dsm.checkMemory();
13391                    }
13392                }
13393                if(observer != null) {
13394                    try {
13395                        observer.onRemoveCompleted(packageName, succeeded);
13396                    } catch (RemoteException e) {
13397                        Log.i(TAG, "Observer no longer exists.");
13398                    }
13399                } //end if observer
13400            } //end run
13401        });
13402    }
13403
13404    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13405        if (packageName == null) {
13406            Slog.w(TAG, "Attempt to delete null packageName.");
13407            return false;
13408        }
13409
13410        // Try finding details about the requested package
13411        PackageParser.Package pkg;
13412        synchronized (mPackages) {
13413            pkg = mPackages.get(packageName);
13414            if (pkg == null) {
13415                final PackageSetting ps = mSettings.mPackages.get(packageName);
13416                if (ps != null) {
13417                    pkg = ps.pkg;
13418                }
13419            }
13420
13421            if (pkg == null) {
13422                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13423                return false;
13424            }
13425
13426            PackageSetting ps = (PackageSetting) pkg.mExtras;
13427            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13428        }
13429
13430        // Always delete data directories for package, even if we found no other
13431        // record of app. This helps users recover from UID mismatches without
13432        // resorting to a full data wipe.
13433        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13434        if (retCode < 0) {
13435            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13436            return false;
13437        }
13438
13439        final int appId = pkg.applicationInfo.uid;
13440        removeKeystoreDataIfNeeded(userId, appId);
13441
13442        // Create a native library symlink only if we have native libraries
13443        // and if the native libraries are 32 bit libraries. We do not provide
13444        // this symlink for 64 bit libraries.
13445        if (pkg.applicationInfo.primaryCpuAbi != null &&
13446                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13447            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13448            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13449                    nativeLibPath, userId) < 0) {
13450                Slog.w(TAG, "Failed linking native library dir");
13451                return false;
13452            }
13453        }
13454
13455        return true;
13456    }
13457
13458    /**
13459     * Reverts user permission state changes (permissions and flags) in
13460     * all packages for a given user.
13461     *
13462     * @param userId The device user for which to do a reset.
13463     */
13464    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13465        final int packageCount = mPackages.size();
13466        for (int i = 0; i < packageCount; i++) {
13467            PackageParser.Package pkg = mPackages.valueAt(i);
13468            PackageSetting ps = (PackageSetting) pkg.mExtras;
13469            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13470        }
13471    }
13472
13473    /**
13474     * Reverts user permission state changes (permissions and flags).
13475     *
13476     * @param ps The package for which to reset.
13477     * @param userId The device user for which to do a reset.
13478     */
13479    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13480            final PackageSetting ps, final int userId) {
13481        if (ps.pkg == null) {
13482            return;
13483        }
13484
13485        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13486                | FLAG_PERMISSION_USER_FIXED
13487                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13488
13489        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13490                | FLAG_PERMISSION_POLICY_FIXED;
13491
13492        boolean writeInstallPermissions = false;
13493        boolean writeRuntimePermissions = false;
13494
13495        final int permissionCount = ps.pkg.requestedPermissions.size();
13496        for (int i = 0; i < permissionCount; i++) {
13497            String permission = ps.pkg.requestedPermissions.get(i);
13498
13499            BasePermission bp = mSettings.mPermissions.get(permission);
13500            if (bp == null) {
13501                continue;
13502            }
13503
13504            // If shared user we just reset the state to which only this app contributed.
13505            if (ps.sharedUser != null) {
13506                boolean used = false;
13507                final int packageCount = ps.sharedUser.packages.size();
13508                for (int j = 0; j < packageCount; j++) {
13509                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13510                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13511                            && pkg.pkg.requestedPermissions.contains(permission)) {
13512                        used = true;
13513                        break;
13514                    }
13515                }
13516                if (used) {
13517                    continue;
13518                }
13519            }
13520
13521            PermissionsState permissionsState = ps.getPermissionsState();
13522
13523            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13524
13525            // Always clear the user settable flags.
13526            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13527                    bp.name) != null;
13528            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13529                if (hasInstallState) {
13530                    writeInstallPermissions = true;
13531                } else {
13532                    writeRuntimePermissions = true;
13533                }
13534            }
13535
13536            // Below is only runtime permission handling.
13537            if (!bp.isRuntime()) {
13538                continue;
13539            }
13540
13541            // Never clobber system or policy.
13542            if ((oldFlags & policyOrSystemFlags) != 0) {
13543                continue;
13544            }
13545
13546            // If this permission was granted by default, make sure it is.
13547            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13548                if (permissionsState.grantRuntimePermission(bp, userId)
13549                        != PERMISSION_OPERATION_FAILURE) {
13550                    writeRuntimePermissions = true;
13551                }
13552            } else {
13553                // Otherwise, reset the permission.
13554                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13555                switch (revokeResult) {
13556                    case PERMISSION_OPERATION_SUCCESS: {
13557                        writeRuntimePermissions = true;
13558                    } break;
13559
13560                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13561                        writeRuntimePermissions = true;
13562                        final int appId = ps.appId;
13563                        mHandler.post(new Runnable() {
13564                            @Override
13565                            public void run() {
13566                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13567                            }
13568                        });
13569                    } break;
13570                }
13571            }
13572        }
13573
13574        // Synchronously write as we are taking permissions away.
13575        if (writeRuntimePermissions) {
13576            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13577        }
13578
13579        // Synchronously write as we are taking permissions away.
13580        if (writeInstallPermissions) {
13581            mSettings.writeLPr();
13582        }
13583    }
13584
13585    /**
13586     * Remove entries from the keystore daemon. Will only remove it if the
13587     * {@code appId} is valid.
13588     */
13589    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13590        if (appId < 0) {
13591            return;
13592        }
13593
13594        final KeyStore keyStore = KeyStore.getInstance();
13595        if (keyStore != null) {
13596            if (userId == UserHandle.USER_ALL) {
13597                for (final int individual : sUserManager.getUserIds()) {
13598                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13599                }
13600            } else {
13601                keyStore.clearUid(UserHandle.getUid(userId, appId));
13602            }
13603        } else {
13604            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13605        }
13606    }
13607
13608    @Override
13609    public void deleteApplicationCacheFiles(final String packageName,
13610            final IPackageDataObserver observer) {
13611        mContext.enforceCallingOrSelfPermission(
13612                android.Manifest.permission.DELETE_CACHE_FILES, null);
13613        // Queue up an async operation since the package deletion may take a little while.
13614        final int userId = UserHandle.getCallingUserId();
13615        mHandler.post(new Runnable() {
13616            public void run() {
13617                mHandler.removeCallbacks(this);
13618                final boolean succeded;
13619                synchronized (mInstallLock) {
13620                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13621                }
13622                clearExternalStorageDataSync(packageName, userId, false);
13623                if (observer != null) {
13624                    try {
13625                        observer.onRemoveCompleted(packageName, succeded);
13626                    } catch (RemoteException e) {
13627                        Log.i(TAG, "Observer no longer exists.");
13628                    }
13629                } //end if observer
13630            } //end run
13631        });
13632    }
13633
13634    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13635        if (packageName == null) {
13636            Slog.w(TAG, "Attempt to delete null packageName.");
13637            return false;
13638        }
13639        PackageParser.Package p;
13640        synchronized (mPackages) {
13641            p = mPackages.get(packageName);
13642        }
13643        if (p == null) {
13644            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13645            return false;
13646        }
13647        final ApplicationInfo applicationInfo = p.applicationInfo;
13648        if (applicationInfo == null) {
13649            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13650            return false;
13651        }
13652        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13653        if (retCode < 0) {
13654            Slog.w(TAG, "Couldn't remove cache files for package: "
13655                       + packageName + " u" + userId);
13656            return false;
13657        }
13658        return true;
13659    }
13660
13661    @Override
13662    public void getPackageSizeInfo(final String packageName, int userHandle,
13663            final IPackageStatsObserver observer) {
13664        mContext.enforceCallingOrSelfPermission(
13665                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13666        if (packageName == null) {
13667            throw new IllegalArgumentException("Attempt to get size of null packageName");
13668        }
13669
13670        PackageStats stats = new PackageStats(packageName, userHandle);
13671
13672        /*
13673         * Queue up an async operation since the package measurement may take a
13674         * little while.
13675         */
13676        Message msg = mHandler.obtainMessage(INIT_COPY);
13677        msg.obj = new MeasureParams(stats, observer);
13678        mHandler.sendMessage(msg);
13679    }
13680
13681    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13682            PackageStats pStats) {
13683        if (packageName == null) {
13684            Slog.w(TAG, "Attempt to get size of null packageName.");
13685            return false;
13686        }
13687        PackageParser.Package p;
13688        boolean dataOnly = false;
13689        String libDirRoot = null;
13690        String asecPath = null;
13691        PackageSetting ps = null;
13692        synchronized (mPackages) {
13693            p = mPackages.get(packageName);
13694            ps = mSettings.mPackages.get(packageName);
13695            if(p == null) {
13696                dataOnly = true;
13697                if((ps == null) || (ps.pkg == null)) {
13698                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13699                    return false;
13700                }
13701                p = ps.pkg;
13702            }
13703            if (ps != null) {
13704                libDirRoot = ps.legacyNativeLibraryPathString;
13705            }
13706            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13707                final long token = Binder.clearCallingIdentity();
13708                try {
13709                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13710                    if (secureContainerId != null) {
13711                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13712                    }
13713                } finally {
13714                    Binder.restoreCallingIdentity(token);
13715                }
13716            }
13717        }
13718        String publicSrcDir = null;
13719        if(!dataOnly) {
13720            final ApplicationInfo applicationInfo = p.applicationInfo;
13721            if (applicationInfo == null) {
13722                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13723                return false;
13724            }
13725            if (p.isForwardLocked()) {
13726                publicSrcDir = applicationInfo.getBaseResourcePath();
13727            }
13728        }
13729        // TODO: extend to measure size of split APKs
13730        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13731        // not just the first level.
13732        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13733        // just the primary.
13734        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13735
13736        String apkPath;
13737        File packageDir = new File(p.codePath);
13738
13739        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13740            apkPath = packageDir.getAbsolutePath();
13741            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13742            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13743                libDirRoot = null;
13744            }
13745        } else {
13746            apkPath = p.baseCodePath;
13747        }
13748
13749        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13750                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13751        if (res < 0) {
13752            return false;
13753        }
13754
13755        // Fix-up for forward-locked applications in ASEC containers.
13756        if (!isExternal(p)) {
13757            pStats.codeSize += pStats.externalCodeSize;
13758            pStats.externalCodeSize = 0L;
13759        }
13760
13761        return true;
13762    }
13763
13764
13765    @Override
13766    public void addPackageToPreferred(String packageName) {
13767        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13768    }
13769
13770    @Override
13771    public void removePackageFromPreferred(String packageName) {
13772        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13773    }
13774
13775    @Override
13776    public List<PackageInfo> getPreferredPackages(int flags) {
13777        return new ArrayList<PackageInfo>();
13778    }
13779
13780    private int getUidTargetSdkVersionLockedLPr(int uid) {
13781        Object obj = mSettings.getUserIdLPr(uid);
13782        if (obj instanceof SharedUserSetting) {
13783            final SharedUserSetting sus = (SharedUserSetting) obj;
13784            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13785            final Iterator<PackageSetting> it = sus.packages.iterator();
13786            while (it.hasNext()) {
13787                final PackageSetting ps = it.next();
13788                if (ps.pkg != null) {
13789                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13790                    if (v < vers) vers = v;
13791                }
13792            }
13793            return vers;
13794        } else if (obj instanceof PackageSetting) {
13795            final PackageSetting ps = (PackageSetting) obj;
13796            if (ps.pkg != null) {
13797                return ps.pkg.applicationInfo.targetSdkVersion;
13798            }
13799        }
13800        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13801    }
13802
13803    @Override
13804    public void addPreferredActivity(IntentFilter filter, int match,
13805            ComponentName[] set, ComponentName activity, int userId) {
13806        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13807                "Adding preferred");
13808    }
13809
13810    private void addPreferredActivityInternal(IntentFilter filter, int match,
13811            ComponentName[] set, ComponentName activity, boolean always, int userId,
13812            String opname) {
13813        // writer
13814        int callingUid = Binder.getCallingUid();
13815        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13816        if (filter.countActions() == 0) {
13817            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13818            return;
13819        }
13820        synchronized (mPackages) {
13821            if (mContext.checkCallingOrSelfPermission(
13822                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13823                    != PackageManager.PERMISSION_GRANTED) {
13824                if (getUidTargetSdkVersionLockedLPr(callingUid)
13825                        < Build.VERSION_CODES.FROYO) {
13826                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13827                            + callingUid);
13828                    return;
13829                }
13830                mContext.enforceCallingOrSelfPermission(
13831                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13832            }
13833
13834            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13835            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13836                    + userId + ":");
13837            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13838            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13839            scheduleWritePackageRestrictionsLocked(userId);
13840        }
13841    }
13842
13843    @Override
13844    public void replacePreferredActivity(IntentFilter filter, int match,
13845            ComponentName[] set, ComponentName activity, int userId) {
13846        if (filter.countActions() != 1) {
13847            throw new IllegalArgumentException(
13848                    "replacePreferredActivity expects filter to have only 1 action.");
13849        }
13850        if (filter.countDataAuthorities() != 0
13851                || filter.countDataPaths() != 0
13852                || filter.countDataSchemes() > 1
13853                || filter.countDataTypes() != 0) {
13854            throw new IllegalArgumentException(
13855                    "replacePreferredActivity expects filter to have no data authorities, " +
13856                    "paths, or types; and at most one scheme.");
13857        }
13858
13859        final int callingUid = Binder.getCallingUid();
13860        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13861        synchronized (mPackages) {
13862            if (mContext.checkCallingOrSelfPermission(
13863                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13864                    != PackageManager.PERMISSION_GRANTED) {
13865                if (getUidTargetSdkVersionLockedLPr(callingUid)
13866                        < Build.VERSION_CODES.FROYO) {
13867                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13868                            + Binder.getCallingUid());
13869                    return;
13870                }
13871                mContext.enforceCallingOrSelfPermission(
13872                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13873            }
13874
13875            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13876            if (pir != null) {
13877                // Get all of the existing entries that exactly match this filter.
13878                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13879                if (existing != null && existing.size() == 1) {
13880                    PreferredActivity cur = existing.get(0);
13881                    if (DEBUG_PREFERRED) {
13882                        Slog.i(TAG, "Checking replace of preferred:");
13883                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13884                        if (!cur.mPref.mAlways) {
13885                            Slog.i(TAG, "  -- CUR; not mAlways!");
13886                        } else {
13887                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13888                            Slog.i(TAG, "  -- CUR: mSet="
13889                                    + Arrays.toString(cur.mPref.mSetComponents));
13890                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13891                            Slog.i(TAG, "  -- NEW: mMatch="
13892                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13893                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13894                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13895                        }
13896                    }
13897                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13898                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13899                            && cur.mPref.sameSet(set)) {
13900                        // Setting the preferred activity to what it happens to be already
13901                        if (DEBUG_PREFERRED) {
13902                            Slog.i(TAG, "Replacing with same preferred activity "
13903                                    + cur.mPref.mShortComponent + " for user "
13904                                    + userId + ":");
13905                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13906                        }
13907                        return;
13908                    }
13909                }
13910
13911                if (existing != null) {
13912                    if (DEBUG_PREFERRED) {
13913                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13914                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13915                    }
13916                    for (int i = 0; i < existing.size(); i++) {
13917                        PreferredActivity pa = existing.get(i);
13918                        if (DEBUG_PREFERRED) {
13919                            Slog.i(TAG, "Removing existing preferred activity "
13920                                    + pa.mPref.mComponent + ":");
13921                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13922                        }
13923                        pir.removeFilter(pa);
13924                    }
13925                }
13926            }
13927            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13928                    "Replacing preferred");
13929        }
13930    }
13931
13932    @Override
13933    public void clearPackagePreferredActivities(String packageName) {
13934        final int uid = Binder.getCallingUid();
13935        // writer
13936        synchronized (mPackages) {
13937            PackageParser.Package pkg = mPackages.get(packageName);
13938            if (pkg == null || pkg.applicationInfo.uid != uid) {
13939                if (mContext.checkCallingOrSelfPermission(
13940                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13941                        != PackageManager.PERMISSION_GRANTED) {
13942                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13943                            < Build.VERSION_CODES.FROYO) {
13944                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13945                                + Binder.getCallingUid());
13946                        return;
13947                    }
13948                    mContext.enforceCallingOrSelfPermission(
13949                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13950                }
13951            }
13952
13953            int user = UserHandle.getCallingUserId();
13954            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13955                scheduleWritePackageRestrictionsLocked(user);
13956            }
13957        }
13958    }
13959
13960    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13961    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13962        ArrayList<PreferredActivity> removed = null;
13963        boolean changed = false;
13964        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13965            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13966            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13967            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13968                continue;
13969            }
13970            Iterator<PreferredActivity> it = pir.filterIterator();
13971            while (it.hasNext()) {
13972                PreferredActivity pa = it.next();
13973                // Mark entry for removal only if it matches the package name
13974                // and the entry is of type "always".
13975                if (packageName == null ||
13976                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13977                                && pa.mPref.mAlways)) {
13978                    if (removed == null) {
13979                        removed = new ArrayList<PreferredActivity>();
13980                    }
13981                    removed.add(pa);
13982                }
13983            }
13984            if (removed != null) {
13985                for (int j=0; j<removed.size(); j++) {
13986                    PreferredActivity pa = removed.get(j);
13987                    pir.removeFilter(pa);
13988                }
13989                changed = true;
13990            }
13991        }
13992        return changed;
13993    }
13994
13995    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13996    private void clearIntentFilterVerificationsLPw(int userId) {
13997        final int packageCount = mPackages.size();
13998        for (int i = 0; i < packageCount; i++) {
13999            PackageParser.Package pkg = mPackages.valueAt(i);
14000            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14001        }
14002    }
14003
14004    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14005    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14006        if (userId == UserHandle.USER_ALL) {
14007            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14008                    sUserManager.getUserIds())) {
14009                for (int oneUserId : sUserManager.getUserIds()) {
14010                    scheduleWritePackageRestrictionsLocked(oneUserId);
14011                }
14012            }
14013        } else {
14014            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14015                scheduleWritePackageRestrictionsLocked(userId);
14016            }
14017        }
14018    }
14019
14020    void clearDefaultBrowserIfNeeded(String packageName) {
14021        for (int oneUserId : sUserManager.getUserIds()) {
14022            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14023            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14024            if (packageName.equals(defaultBrowserPackageName)) {
14025                setDefaultBrowserPackageName(null, oneUserId);
14026            }
14027        }
14028    }
14029
14030    @Override
14031    public void resetApplicationPreferences(int userId) {
14032        mContext.enforceCallingOrSelfPermission(
14033                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14034        // writer
14035        synchronized (mPackages) {
14036            final long identity = Binder.clearCallingIdentity();
14037            try {
14038                clearPackagePreferredActivitiesLPw(null, userId);
14039                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14040                // TODO: We have to reset the default SMS and Phone. This requires
14041                // significant refactoring to keep all default apps in the package
14042                // manager (cleaner but more work) or have the services provide
14043                // callbacks to the package manager to request a default app reset.
14044                applyFactoryDefaultBrowserLPw(userId);
14045                clearIntentFilterVerificationsLPw(userId);
14046                primeDomainVerificationsLPw(userId);
14047                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14048                scheduleWritePackageRestrictionsLocked(userId);
14049            } finally {
14050                Binder.restoreCallingIdentity(identity);
14051            }
14052        }
14053    }
14054
14055    @Override
14056    public int getPreferredActivities(List<IntentFilter> outFilters,
14057            List<ComponentName> outActivities, String packageName) {
14058
14059        int num = 0;
14060        final int userId = UserHandle.getCallingUserId();
14061        // reader
14062        synchronized (mPackages) {
14063            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14064            if (pir != null) {
14065                final Iterator<PreferredActivity> it = pir.filterIterator();
14066                while (it.hasNext()) {
14067                    final PreferredActivity pa = it.next();
14068                    if (packageName == null
14069                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14070                                    && pa.mPref.mAlways)) {
14071                        if (outFilters != null) {
14072                            outFilters.add(new IntentFilter(pa));
14073                        }
14074                        if (outActivities != null) {
14075                            outActivities.add(pa.mPref.mComponent);
14076                        }
14077                    }
14078                }
14079            }
14080        }
14081
14082        return num;
14083    }
14084
14085    @Override
14086    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14087            int userId) {
14088        int callingUid = Binder.getCallingUid();
14089        if (callingUid != Process.SYSTEM_UID) {
14090            throw new SecurityException(
14091                    "addPersistentPreferredActivity can only be run by the system");
14092        }
14093        if (filter.countActions() == 0) {
14094            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14095            return;
14096        }
14097        synchronized (mPackages) {
14098            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14099                    " :");
14100            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14101            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14102                    new PersistentPreferredActivity(filter, activity));
14103            scheduleWritePackageRestrictionsLocked(userId);
14104        }
14105    }
14106
14107    @Override
14108    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14109        int callingUid = Binder.getCallingUid();
14110        if (callingUid != Process.SYSTEM_UID) {
14111            throw new SecurityException(
14112                    "clearPackagePersistentPreferredActivities can only be run by the system");
14113        }
14114        ArrayList<PersistentPreferredActivity> removed = null;
14115        boolean changed = false;
14116        synchronized (mPackages) {
14117            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14118                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14119                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14120                        .valueAt(i);
14121                if (userId != thisUserId) {
14122                    continue;
14123                }
14124                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14125                while (it.hasNext()) {
14126                    PersistentPreferredActivity ppa = it.next();
14127                    // Mark entry for removal only if it matches the package name.
14128                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14129                        if (removed == null) {
14130                            removed = new ArrayList<PersistentPreferredActivity>();
14131                        }
14132                        removed.add(ppa);
14133                    }
14134                }
14135                if (removed != null) {
14136                    for (int j=0; j<removed.size(); j++) {
14137                        PersistentPreferredActivity ppa = removed.get(j);
14138                        ppir.removeFilter(ppa);
14139                    }
14140                    changed = true;
14141                }
14142            }
14143
14144            if (changed) {
14145                scheduleWritePackageRestrictionsLocked(userId);
14146            }
14147        }
14148    }
14149
14150    /**
14151     * Common machinery for picking apart a restored XML blob and passing
14152     * it to a caller-supplied functor to be applied to the running system.
14153     */
14154    private void restoreFromXml(XmlPullParser parser, int userId,
14155            String expectedStartTag, BlobXmlRestorer functor)
14156            throws IOException, XmlPullParserException {
14157        int type;
14158        while ((type = parser.next()) != XmlPullParser.START_TAG
14159                && type != XmlPullParser.END_DOCUMENT) {
14160        }
14161        if (type != XmlPullParser.START_TAG) {
14162            // oops didn't find a start tag?!
14163            if (DEBUG_BACKUP) {
14164                Slog.e(TAG, "Didn't find start tag during restore");
14165            }
14166            return;
14167        }
14168
14169        // this is supposed to be TAG_PREFERRED_BACKUP
14170        if (!expectedStartTag.equals(parser.getName())) {
14171            if (DEBUG_BACKUP) {
14172                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14173            }
14174            return;
14175        }
14176
14177        // skip interfering stuff, then we're aligned with the backing implementation
14178        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14179        functor.apply(parser, userId);
14180    }
14181
14182    private interface BlobXmlRestorer {
14183        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14184    }
14185
14186    /**
14187     * Non-Binder method, support for the backup/restore mechanism: write the
14188     * full set of preferred activities in its canonical XML format.  Returns the
14189     * XML output as a byte array, or null if there is none.
14190     */
14191    @Override
14192    public byte[] getPreferredActivityBackup(int userId) {
14193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14194            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14195        }
14196
14197        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14198        try {
14199            final XmlSerializer serializer = new FastXmlSerializer();
14200            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14201            serializer.startDocument(null, true);
14202            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14203
14204            synchronized (mPackages) {
14205                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14206            }
14207
14208            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14209            serializer.endDocument();
14210            serializer.flush();
14211        } catch (Exception e) {
14212            if (DEBUG_BACKUP) {
14213                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14214            }
14215            return null;
14216        }
14217
14218        return dataStream.toByteArray();
14219    }
14220
14221    @Override
14222    public void restorePreferredActivities(byte[] backup, int userId) {
14223        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14224            throw new SecurityException("Only the system may call restorePreferredActivities()");
14225        }
14226
14227        try {
14228            final XmlPullParser parser = Xml.newPullParser();
14229            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14230            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14231                    new BlobXmlRestorer() {
14232                        @Override
14233                        public void apply(XmlPullParser parser, int userId)
14234                                throws XmlPullParserException, IOException {
14235                            synchronized (mPackages) {
14236                                mSettings.readPreferredActivitiesLPw(parser, userId);
14237                            }
14238                        }
14239                    } );
14240        } catch (Exception e) {
14241            if (DEBUG_BACKUP) {
14242                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14243            }
14244        }
14245    }
14246
14247    /**
14248     * Non-Binder method, support for the backup/restore mechanism: write the
14249     * default browser (etc) settings in its canonical XML format.  Returns the default
14250     * browser XML representation as a byte array, or null if there is none.
14251     */
14252    @Override
14253    public byte[] getDefaultAppsBackup(int userId) {
14254        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14255            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14256        }
14257
14258        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14259        try {
14260            final XmlSerializer serializer = new FastXmlSerializer();
14261            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14262            serializer.startDocument(null, true);
14263            serializer.startTag(null, TAG_DEFAULT_APPS);
14264
14265            synchronized (mPackages) {
14266                mSettings.writeDefaultAppsLPr(serializer, userId);
14267            }
14268
14269            serializer.endTag(null, TAG_DEFAULT_APPS);
14270            serializer.endDocument();
14271            serializer.flush();
14272        } catch (Exception e) {
14273            if (DEBUG_BACKUP) {
14274                Slog.e(TAG, "Unable to write default apps for backup", e);
14275            }
14276            return null;
14277        }
14278
14279        return dataStream.toByteArray();
14280    }
14281
14282    @Override
14283    public void restoreDefaultApps(byte[] backup, int userId) {
14284        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14285            throw new SecurityException("Only the system may call restoreDefaultApps()");
14286        }
14287
14288        try {
14289            final XmlPullParser parser = Xml.newPullParser();
14290            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14291            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14292                    new BlobXmlRestorer() {
14293                        @Override
14294                        public void apply(XmlPullParser parser, int userId)
14295                                throws XmlPullParserException, IOException {
14296                            synchronized (mPackages) {
14297                                mSettings.readDefaultAppsLPw(parser, userId);
14298                            }
14299                        }
14300                    } );
14301        } catch (Exception e) {
14302            if (DEBUG_BACKUP) {
14303                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14304            }
14305        }
14306    }
14307
14308    @Override
14309    public byte[] getIntentFilterVerificationBackup(int userId) {
14310        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14311            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14312        }
14313
14314        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14315        try {
14316            final XmlSerializer serializer = new FastXmlSerializer();
14317            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14318            serializer.startDocument(null, true);
14319            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14320
14321            synchronized (mPackages) {
14322                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14323            }
14324
14325            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14326            serializer.endDocument();
14327            serializer.flush();
14328        } catch (Exception e) {
14329            if (DEBUG_BACKUP) {
14330                Slog.e(TAG, "Unable to write default apps for backup", e);
14331            }
14332            return null;
14333        }
14334
14335        return dataStream.toByteArray();
14336    }
14337
14338    @Override
14339    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14340        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14341            throw new SecurityException("Only the system may call restorePreferredActivities()");
14342        }
14343
14344        try {
14345            final XmlPullParser parser = Xml.newPullParser();
14346            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14347            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14348                    new BlobXmlRestorer() {
14349                        @Override
14350                        public void apply(XmlPullParser parser, int userId)
14351                                throws XmlPullParserException, IOException {
14352                            synchronized (mPackages) {
14353                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14354                                mSettings.writeLPr();
14355                            }
14356                        }
14357                    } );
14358        } catch (Exception e) {
14359            if (DEBUG_BACKUP) {
14360                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14361            }
14362        }
14363    }
14364
14365    @Override
14366    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14367            int sourceUserId, int targetUserId, int flags) {
14368        mContext.enforceCallingOrSelfPermission(
14369                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14370        int callingUid = Binder.getCallingUid();
14371        enforceOwnerRights(ownerPackage, callingUid);
14372        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14373        if (intentFilter.countActions() == 0) {
14374            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14375            return;
14376        }
14377        synchronized (mPackages) {
14378            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14379                    ownerPackage, targetUserId, flags);
14380            CrossProfileIntentResolver resolver =
14381                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14382            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14383            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14384            if (existing != null) {
14385                int size = existing.size();
14386                for (int i = 0; i < size; i++) {
14387                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14388                        return;
14389                    }
14390                }
14391            }
14392            resolver.addFilter(newFilter);
14393            scheduleWritePackageRestrictionsLocked(sourceUserId);
14394        }
14395    }
14396
14397    @Override
14398    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14399        mContext.enforceCallingOrSelfPermission(
14400                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14401        int callingUid = Binder.getCallingUid();
14402        enforceOwnerRights(ownerPackage, callingUid);
14403        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14404        synchronized (mPackages) {
14405            CrossProfileIntentResolver resolver =
14406                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14407            ArraySet<CrossProfileIntentFilter> set =
14408                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14409            for (CrossProfileIntentFilter filter : set) {
14410                if (filter.getOwnerPackage().equals(ownerPackage)) {
14411                    resolver.removeFilter(filter);
14412                }
14413            }
14414            scheduleWritePackageRestrictionsLocked(sourceUserId);
14415        }
14416    }
14417
14418    // Enforcing that callingUid is owning pkg on userId
14419    private void enforceOwnerRights(String pkg, int callingUid) {
14420        // The system owns everything.
14421        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14422            return;
14423        }
14424        int callingUserId = UserHandle.getUserId(callingUid);
14425        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14426        if (pi == null) {
14427            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14428                    + callingUserId);
14429        }
14430        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14431            throw new SecurityException("Calling uid " + callingUid
14432                    + " does not own package " + pkg);
14433        }
14434    }
14435
14436    @Override
14437    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14438        Intent intent = new Intent(Intent.ACTION_MAIN);
14439        intent.addCategory(Intent.CATEGORY_HOME);
14440
14441        final int callingUserId = UserHandle.getCallingUserId();
14442        List<ResolveInfo> list = queryIntentActivities(intent, null,
14443                PackageManager.GET_META_DATA, callingUserId);
14444        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14445                true, false, false, callingUserId);
14446
14447        allHomeCandidates.clear();
14448        if (list != null) {
14449            for (ResolveInfo ri : list) {
14450                allHomeCandidates.add(ri);
14451            }
14452        }
14453        return (preferred == null || preferred.activityInfo == null)
14454                ? null
14455                : new ComponentName(preferred.activityInfo.packageName,
14456                        preferred.activityInfo.name);
14457    }
14458
14459    @Override
14460    public void setApplicationEnabledSetting(String appPackageName,
14461            int newState, int flags, int userId, String callingPackage) {
14462        if (!sUserManager.exists(userId)) return;
14463        if (callingPackage == null) {
14464            callingPackage = Integer.toString(Binder.getCallingUid());
14465        }
14466        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14467    }
14468
14469    @Override
14470    public void setComponentEnabledSetting(ComponentName componentName,
14471            int newState, int flags, int userId) {
14472        if (!sUserManager.exists(userId)) return;
14473        setEnabledSetting(componentName.getPackageName(),
14474                componentName.getClassName(), newState, flags, userId, null);
14475    }
14476
14477    private void setEnabledSetting(final String packageName, String className, int newState,
14478            final int flags, int userId, String callingPackage) {
14479        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14480              || newState == COMPONENT_ENABLED_STATE_ENABLED
14481              || newState == COMPONENT_ENABLED_STATE_DISABLED
14482              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14483              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14484            throw new IllegalArgumentException("Invalid new component state: "
14485                    + newState);
14486        }
14487        PackageSetting pkgSetting;
14488        final int uid = Binder.getCallingUid();
14489        final int permission = mContext.checkCallingOrSelfPermission(
14490                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14491        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14492        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14493        boolean sendNow = false;
14494        boolean isApp = (className == null);
14495        String componentName = isApp ? packageName : className;
14496        int packageUid = -1;
14497        ArrayList<String> components;
14498
14499        // writer
14500        synchronized (mPackages) {
14501            pkgSetting = mSettings.mPackages.get(packageName);
14502            if (pkgSetting == null) {
14503                if (className == null) {
14504                    throw new IllegalArgumentException(
14505                            "Unknown package: " + packageName);
14506                }
14507                throw new IllegalArgumentException(
14508                        "Unknown component: " + packageName
14509                        + "/" + className);
14510            }
14511            // Allow root and verify that userId is not being specified by a different user
14512            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14513                throw new SecurityException(
14514                        "Permission Denial: attempt to change component state from pid="
14515                        + Binder.getCallingPid()
14516                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14517            }
14518            if (className == null) {
14519                // We're dealing with an application/package level state change
14520                if (pkgSetting.getEnabled(userId) == newState) {
14521                    // Nothing to do
14522                    return;
14523                }
14524                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14525                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14526                    // Don't care about who enables an app.
14527                    callingPackage = null;
14528                }
14529                pkgSetting.setEnabled(newState, userId, callingPackage);
14530                // pkgSetting.pkg.mSetEnabled = newState;
14531            } else {
14532                // We're dealing with a component level state change
14533                // First, verify that this is a valid class name.
14534                PackageParser.Package pkg = pkgSetting.pkg;
14535                if (pkg == null || !pkg.hasComponentClassName(className)) {
14536                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14537                        throw new IllegalArgumentException("Component class " + className
14538                                + " does not exist in " + packageName);
14539                    } else {
14540                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14541                                + className + " does not exist in " + packageName);
14542                    }
14543                }
14544                switch (newState) {
14545                case COMPONENT_ENABLED_STATE_ENABLED:
14546                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14547                        return;
14548                    }
14549                    break;
14550                case COMPONENT_ENABLED_STATE_DISABLED:
14551                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14552                        return;
14553                    }
14554                    break;
14555                case COMPONENT_ENABLED_STATE_DEFAULT:
14556                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14557                        return;
14558                    }
14559                    break;
14560                default:
14561                    Slog.e(TAG, "Invalid new component state: " + newState);
14562                    return;
14563                }
14564            }
14565            scheduleWritePackageRestrictionsLocked(userId);
14566            components = mPendingBroadcasts.get(userId, packageName);
14567            final boolean newPackage = components == null;
14568            if (newPackage) {
14569                components = new ArrayList<String>();
14570            }
14571            if (!components.contains(componentName)) {
14572                components.add(componentName);
14573            }
14574            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14575                sendNow = true;
14576                // Purge entry from pending broadcast list if another one exists already
14577                // since we are sending one right away.
14578                mPendingBroadcasts.remove(userId, packageName);
14579            } else {
14580                if (newPackage) {
14581                    mPendingBroadcasts.put(userId, packageName, components);
14582                }
14583                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14584                    // Schedule a message
14585                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14586                }
14587            }
14588        }
14589
14590        long callingId = Binder.clearCallingIdentity();
14591        try {
14592            if (sendNow) {
14593                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14594                sendPackageChangedBroadcast(packageName,
14595                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14596            }
14597        } finally {
14598            Binder.restoreCallingIdentity(callingId);
14599        }
14600    }
14601
14602    private void sendPackageChangedBroadcast(String packageName,
14603            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14604        if (DEBUG_INSTALL)
14605            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14606                    + componentNames);
14607        Bundle extras = new Bundle(4);
14608        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14609        String nameList[] = new String[componentNames.size()];
14610        componentNames.toArray(nameList);
14611        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14612        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14613        extras.putInt(Intent.EXTRA_UID, packageUid);
14614        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14615                new int[] {UserHandle.getUserId(packageUid)});
14616    }
14617
14618    @Override
14619    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14620        if (!sUserManager.exists(userId)) return;
14621        final int uid = Binder.getCallingUid();
14622        final int permission = mContext.checkCallingOrSelfPermission(
14623                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14624        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14625        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14626        // writer
14627        synchronized (mPackages) {
14628            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14629                    allowedByPermission, uid, userId)) {
14630                scheduleWritePackageRestrictionsLocked(userId);
14631            }
14632        }
14633    }
14634
14635    @Override
14636    public String getInstallerPackageName(String packageName) {
14637        // reader
14638        synchronized (mPackages) {
14639            return mSettings.getInstallerPackageNameLPr(packageName);
14640        }
14641    }
14642
14643    @Override
14644    public int getApplicationEnabledSetting(String packageName, int userId) {
14645        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14646        int uid = Binder.getCallingUid();
14647        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14648        // reader
14649        synchronized (mPackages) {
14650            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14651        }
14652    }
14653
14654    @Override
14655    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14656        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14657        int uid = Binder.getCallingUid();
14658        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14659        // reader
14660        synchronized (mPackages) {
14661            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14662        }
14663    }
14664
14665    @Override
14666    public void enterSafeMode() {
14667        enforceSystemOrRoot("Only the system can request entering safe mode");
14668
14669        if (!mSystemReady) {
14670            mSafeMode = true;
14671        }
14672    }
14673
14674    @Override
14675    public void systemReady() {
14676        mSystemReady = true;
14677
14678        // Read the compatibilty setting when the system is ready.
14679        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14680                mContext.getContentResolver(),
14681                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14682        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14683        if (DEBUG_SETTINGS) {
14684            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14685        }
14686
14687        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14688
14689        synchronized (mPackages) {
14690            // Verify that all of the preferred activity components actually
14691            // exist.  It is possible for applications to be updated and at
14692            // that point remove a previously declared activity component that
14693            // had been set as a preferred activity.  We try to clean this up
14694            // the next time we encounter that preferred activity, but it is
14695            // possible for the user flow to never be able to return to that
14696            // situation so here we do a sanity check to make sure we haven't
14697            // left any junk around.
14698            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14699            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14700                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14701                removed.clear();
14702                for (PreferredActivity pa : pir.filterSet()) {
14703                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14704                        removed.add(pa);
14705                    }
14706                }
14707                if (removed.size() > 0) {
14708                    for (int r=0; r<removed.size(); r++) {
14709                        PreferredActivity pa = removed.get(r);
14710                        Slog.w(TAG, "Removing dangling preferred activity: "
14711                                + pa.mPref.mComponent);
14712                        pir.removeFilter(pa);
14713                    }
14714                    mSettings.writePackageRestrictionsLPr(
14715                            mSettings.mPreferredActivities.keyAt(i));
14716                }
14717            }
14718
14719            for (int userId : UserManagerService.getInstance().getUserIds()) {
14720                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14721                    grantPermissionsUserIds = ArrayUtils.appendInt(
14722                            grantPermissionsUserIds, userId);
14723                }
14724            }
14725        }
14726        sUserManager.systemReady();
14727
14728        // If we upgraded grant all default permissions before kicking off.
14729        for (int userId : grantPermissionsUserIds) {
14730            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14731        }
14732
14733        // Kick off any messages waiting for system ready
14734        if (mPostSystemReadyMessages != null) {
14735            for (Message msg : mPostSystemReadyMessages) {
14736                msg.sendToTarget();
14737            }
14738            mPostSystemReadyMessages = null;
14739        }
14740
14741        // Watch for external volumes that come and go over time
14742        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14743        storage.registerListener(mStorageListener);
14744
14745        mInstallerService.systemReady();
14746        mPackageDexOptimizer.systemReady();
14747
14748        MountServiceInternal mountServiceInternal = LocalServices.getService(
14749                MountServiceInternal.class);
14750        mountServiceInternal.addExternalStoragePolicy(
14751                new MountServiceInternal.ExternalStorageMountPolicy() {
14752            @Override
14753            public int getMountMode(int uid, String packageName) {
14754                if (Process.isIsolated(uid)) {
14755                    return Zygote.MOUNT_EXTERNAL_NONE;
14756                }
14757                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14758                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14759                }
14760                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14761                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14762                }
14763                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14764                    return Zygote.MOUNT_EXTERNAL_READ;
14765                }
14766                return Zygote.MOUNT_EXTERNAL_WRITE;
14767            }
14768
14769            @Override
14770            public boolean hasExternalStorage(int uid, String packageName) {
14771                return true;
14772            }
14773        });
14774    }
14775
14776    @Override
14777    public boolean isSafeMode() {
14778        return mSafeMode;
14779    }
14780
14781    @Override
14782    public boolean hasSystemUidErrors() {
14783        return mHasSystemUidErrors;
14784    }
14785
14786    static String arrayToString(int[] array) {
14787        StringBuffer buf = new StringBuffer(128);
14788        buf.append('[');
14789        if (array != null) {
14790            for (int i=0; i<array.length; i++) {
14791                if (i > 0) buf.append(", ");
14792                buf.append(array[i]);
14793            }
14794        }
14795        buf.append(']');
14796        return buf.toString();
14797    }
14798
14799    static class DumpState {
14800        public static final int DUMP_LIBS = 1 << 0;
14801        public static final int DUMP_FEATURES = 1 << 1;
14802        public static final int DUMP_RESOLVERS = 1 << 2;
14803        public static final int DUMP_PERMISSIONS = 1 << 3;
14804        public static final int DUMP_PACKAGES = 1 << 4;
14805        public static final int DUMP_SHARED_USERS = 1 << 5;
14806        public static final int DUMP_MESSAGES = 1 << 6;
14807        public static final int DUMP_PROVIDERS = 1 << 7;
14808        public static final int DUMP_VERIFIERS = 1 << 8;
14809        public static final int DUMP_PREFERRED = 1 << 9;
14810        public static final int DUMP_PREFERRED_XML = 1 << 10;
14811        public static final int DUMP_KEYSETS = 1 << 11;
14812        public static final int DUMP_VERSION = 1 << 12;
14813        public static final int DUMP_INSTALLS = 1 << 13;
14814        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14815        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14816
14817        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14818
14819        private int mTypes;
14820
14821        private int mOptions;
14822
14823        private boolean mTitlePrinted;
14824
14825        private SharedUserSetting mSharedUser;
14826
14827        public boolean isDumping(int type) {
14828            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14829                return true;
14830            }
14831
14832            return (mTypes & type) != 0;
14833        }
14834
14835        public void setDump(int type) {
14836            mTypes |= type;
14837        }
14838
14839        public boolean isOptionEnabled(int option) {
14840            return (mOptions & option) != 0;
14841        }
14842
14843        public void setOptionEnabled(int option) {
14844            mOptions |= option;
14845        }
14846
14847        public boolean onTitlePrinted() {
14848            final boolean printed = mTitlePrinted;
14849            mTitlePrinted = true;
14850            return printed;
14851        }
14852
14853        public boolean getTitlePrinted() {
14854            return mTitlePrinted;
14855        }
14856
14857        public void setTitlePrinted(boolean enabled) {
14858            mTitlePrinted = enabled;
14859        }
14860
14861        public SharedUserSetting getSharedUser() {
14862            return mSharedUser;
14863        }
14864
14865        public void setSharedUser(SharedUserSetting user) {
14866            mSharedUser = user;
14867        }
14868    }
14869
14870    @Override
14871    public void onShellCommand(FileDescriptor in, FileDescriptor out,
14872            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
14873        (new PackageManagerShellCommand(this)).exec(
14874                this, in, out, err, args, resultReceiver);
14875    }
14876
14877    @Override
14878    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14879        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14880                != PackageManager.PERMISSION_GRANTED) {
14881            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14882                    + Binder.getCallingPid()
14883                    + ", uid=" + Binder.getCallingUid()
14884                    + " without permission "
14885                    + android.Manifest.permission.DUMP);
14886            return;
14887        }
14888
14889        DumpState dumpState = new DumpState();
14890        boolean fullPreferred = false;
14891        boolean checkin = false;
14892
14893        String packageName = null;
14894        ArraySet<String> permissionNames = null;
14895
14896        int opti = 0;
14897        while (opti < args.length) {
14898            String opt = args[opti];
14899            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14900                break;
14901            }
14902            opti++;
14903
14904            if ("-a".equals(opt)) {
14905                // Right now we only know how to print all.
14906            } else if ("-h".equals(opt)) {
14907                pw.println("Package manager dump options:");
14908                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14909                pw.println("    --checkin: dump for a checkin");
14910                pw.println("    -f: print details of intent filters");
14911                pw.println("    -h: print this help");
14912                pw.println("  cmd may be one of:");
14913                pw.println("    l[ibraries]: list known shared libraries");
14914                pw.println("    f[ibraries]: list device features");
14915                pw.println("    k[eysets]: print known keysets");
14916                pw.println("    r[esolvers]: dump intent resolvers");
14917                pw.println("    perm[issions]: dump permissions");
14918                pw.println("    permission [name ...]: dump declaration and use of given permission");
14919                pw.println("    pref[erred]: print preferred package settings");
14920                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14921                pw.println("    prov[iders]: dump content providers");
14922                pw.println("    p[ackages]: dump installed packages");
14923                pw.println("    s[hared-users]: dump shared user IDs");
14924                pw.println("    m[essages]: print collected runtime messages");
14925                pw.println("    v[erifiers]: print package verifier info");
14926                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14927                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14928                pw.println("    version: print database version info");
14929                pw.println("    write: write current settings now");
14930                pw.println("    installs: details about install sessions");
14931                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14932                pw.println("    <package.name>: info about given package");
14933                return;
14934            } else if ("--checkin".equals(opt)) {
14935                checkin = true;
14936            } else if ("-f".equals(opt)) {
14937                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14938            } else {
14939                pw.println("Unknown argument: " + opt + "; use -h for help");
14940            }
14941        }
14942
14943        // Is the caller requesting to dump a particular piece of data?
14944        if (opti < args.length) {
14945            String cmd = args[opti];
14946            opti++;
14947            // Is this a package name?
14948            if ("android".equals(cmd) || cmd.contains(".")) {
14949                packageName = cmd;
14950                // When dumping a single package, we always dump all of its
14951                // filter information since the amount of data will be reasonable.
14952                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14953            } else if ("check-permission".equals(cmd)) {
14954                if (opti >= args.length) {
14955                    pw.println("Error: check-permission missing permission argument");
14956                    return;
14957                }
14958                String perm = args[opti];
14959                opti++;
14960                if (opti >= args.length) {
14961                    pw.println("Error: check-permission missing package argument");
14962                    return;
14963                }
14964                String pkg = args[opti];
14965                opti++;
14966                int user = UserHandle.getUserId(Binder.getCallingUid());
14967                if (opti < args.length) {
14968                    try {
14969                        user = Integer.parseInt(args[opti]);
14970                    } catch (NumberFormatException e) {
14971                        pw.println("Error: check-permission user argument is not a number: "
14972                                + args[opti]);
14973                        return;
14974                    }
14975                }
14976                pw.println(checkPermission(perm, pkg, user));
14977                return;
14978            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14979                dumpState.setDump(DumpState.DUMP_LIBS);
14980            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14981                dumpState.setDump(DumpState.DUMP_FEATURES);
14982            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14983                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14984            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14985                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14986            } else if ("permission".equals(cmd)) {
14987                if (opti >= args.length) {
14988                    pw.println("Error: permission requires permission name");
14989                    return;
14990                }
14991                permissionNames = new ArraySet<>();
14992                while (opti < args.length) {
14993                    permissionNames.add(args[opti]);
14994                    opti++;
14995                }
14996                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14997                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14998            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14999                dumpState.setDump(DumpState.DUMP_PREFERRED);
15000            } else if ("preferred-xml".equals(cmd)) {
15001                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15002                if (opti < args.length && "--full".equals(args[opti])) {
15003                    fullPreferred = true;
15004                    opti++;
15005                }
15006            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15007                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15008            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15009                dumpState.setDump(DumpState.DUMP_PACKAGES);
15010            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15011                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15012            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15013                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15014            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15015                dumpState.setDump(DumpState.DUMP_MESSAGES);
15016            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15017                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15018            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15019                    || "intent-filter-verifiers".equals(cmd)) {
15020                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15021            } else if ("version".equals(cmd)) {
15022                dumpState.setDump(DumpState.DUMP_VERSION);
15023            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15024                dumpState.setDump(DumpState.DUMP_KEYSETS);
15025            } else if ("installs".equals(cmd)) {
15026                dumpState.setDump(DumpState.DUMP_INSTALLS);
15027            } else if ("write".equals(cmd)) {
15028                synchronized (mPackages) {
15029                    mSettings.writeLPr();
15030                    pw.println("Settings written.");
15031                    return;
15032                }
15033            }
15034        }
15035
15036        if (checkin) {
15037            pw.println("vers,1");
15038        }
15039
15040        // reader
15041        synchronized (mPackages) {
15042            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15043                if (!checkin) {
15044                    if (dumpState.onTitlePrinted())
15045                        pw.println();
15046                    pw.println("Database versions:");
15047                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15048                }
15049            }
15050
15051            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15052                if (!checkin) {
15053                    if (dumpState.onTitlePrinted())
15054                        pw.println();
15055                    pw.println("Verifiers:");
15056                    pw.print("  Required: ");
15057                    pw.print(mRequiredVerifierPackage);
15058                    pw.print(" (uid=");
15059                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15060                    pw.println(")");
15061                } else if (mRequiredVerifierPackage != null) {
15062                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15063                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15064                }
15065            }
15066
15067            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15068                    packageName == null) {
15069                if (mIntentFilterVerifierComponent != null) {
15070                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15071                    if (!checkin) {
15072                        if (dumpState.onTitlePrinted())
15073                            pw.println();
15074                        pw.println("Intent Filter Verifier:");
15075                        pw.print("  Using: ");
15076                        pw.print(verifierPackageName);
15077                        pw.print(" (uid=");
15078                        pw.print(getPackageUid(verifierPackageName, 0));
15079                        pw.println(")");
15080                    } else if (verifierPackageName != null) {
15081                        pw.print("ifv,"); pw.print(verifierPackageName);
15082                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15083                    }
15084                } else {
15085                    pw.println();
15086                    pw.println("No Intent Filter Verifier available!");
15087                }
15088            }
15089
15090            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15091                boolean printedHeader = false;
15092                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15093                while (it.hasNext()) {
15094                    String name = it.next();
15095                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15096                    if (!checkin) {
15097                        if (!printedHeader) {
15098                            if (dumpState.onTitlePrinted())
15099                                pw.println();
15100                            pw.println("Libraries:");
15101                            printedHeader = true;
15102                        }
15103                        pw.print("  ");
15104                    } else {
15105                        pw.print("lib,");
15106                    }
15107                    pw.print(name);
15108                    if (!checkin) {
15109                        pw.print(" -> ");
15110                    }
15111                    if (ent.path != null) {
15112                        if (!checkin) {
15113                            pw.print("(jar) ");
15114                            pw.print(ent.path);
15115                        } else {
15116                            pw.print(",jar,");
15117                            pw.print(ent.path);
15118                        }
15119                    } else {
15120                        if (!checkin) {
15121                            pw.print("(apk) ");
15122                            pw.print(ent.apk);
15123                        } else {
15124                            pw.print(",apk,");
15125                            pw.print(ent.apk);
15126                        }
15127                    }
15128                    pw.println();
15129                }
15130            }
15131
15132            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15133                if (dumpState.onTitlePrinted())
15134                    pw.println();
15135                if (!checkin) {
15136                    pw.println("Features:");
15137                }
15138                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15139                while (it.hasNext()) {
15140                    String name = it.next();
15141                    if (!checkin) {
15142                        pw.print("  ");
15143                    } else {
15144                        pw.print("feat,");
15145                    }
15146                    pw.println(name);
15147                }
15148            }
15149
15150            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15151                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15152                        : "Activity Resolver Table:", "  ", packageName,
15153                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15154                    dumpState.setTitlePrinted(true);
15155                }
15156                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15157                        : "Receiver Resolver Table:", "  ", packageName,
15158                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15159                    dumpState.setTitlePrinted(true);
15160                }
15161                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15162                        : "Service Resolver Table:", "  ", packageName,
15163                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15164                    dumpState.setTitlePrinted(true);
15165                }
15166                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15167                        : "Provider Resolver Table:", "  ", packageName,
15168                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15169                    dumpState.setTitlePrinted(true);
15170                }
15171            }
15172
15173            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15174                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15175                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15176                    int user = mSettings.mPreferredActivities.keyAt(i);
15177                    if (pir.dump(pw,
15178                            dumpState.getTitlePrinted()
15179                                ? "\nPreferred Activities User " + user + ":"
15180                                : "Preferred Activities User " + user + ":", "  ",
15181                            packageName, true, false)) {
15182                        dumpState.setTitlePrinted(true);
15183                    }
15184                }
15185            }
15186
15187            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15188                pw.flush();
15189                FileOutputStream fout = new FileOutputStream(fd);
15190                BufferedOutputStream str = new BufferedOutputStream(fout);
15191                XmlSerializer serializer = new FastXmlSerializer();
15192                try {
15193                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15194                    serializer.startDocument(null, true);
15195                    serializer.setFeature(
15196                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15197                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15198                    serializer.endDocument();
15199                    serializer.flush();
15200                } catch (IllegalArgumentException e) {
15201                    pw.println("Failed writing: " + e);
15202                } catch (IllegalStateException e) {
15203                    pw.println("Failed writing: " + e);
15204                } catch (IOException e) {
15205                    pw.println("Failed writing: " + e);
15206                }
15207            }
15208
15209            if (!checkin
15210                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15211                    && packageName == null) {
15212                pw.println();
15213                int count = mSettings.mPackages.size();
15214                if (count == 0) {
15215                    pw.println("No applications!");
15216                    pw.println();
15217                } else {
15218                    final String prefix = "  ";
15219                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15220                    if (allPackageSettings.size() == 0) {
15221                        pw.println("No domain preferred apps!");
15222                        pw.println();
15223                    } else {
15224                        pw.println("App verification status:");
15225                        pw.println();
15226                        count = 0;
15227                        for (PackageSetting ps : allPackageSettings) {
15228                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15229                            if (ivi == null || ivi.getPackageName() == null) continue;
15230                            pw.println(prefix + "Package: " + ivi.getPackageName());
15231                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15232                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15233                            pw.println();
15234                            count++;
15235                        }
15236                        if (count == 0) {
15237                            pw.println(prefix + "No app verification established.");
15238                            pw.println();
15239                        }
15240                        for (int userId : sUserManager.getUserIds()) {
15241                            pw.println("App linkages for user " + userId + ":");
15242                            pw.println();
15243                            count = 0;
15244                            for (PackageSetting ps : allPackageSettings) {
15245                                final long status = ps.getDomainVerificationStatusForUser(userId);
15246                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15247                                    continue;
15248                                }
15249                                pw.println(prefix + "Package: " + ps.name);
15250                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15251                                String statusStr = IntentFilterVerificationInfo.
15252                                        getStatusStringFromValue(status);
15253                                pw.println(prefix + "Status:  " + statusStr);
15254                                pw.println();
15255                                count++;
15256                            }
15257                            if (count == 0) {
15258                                pw.println(prefix + "No configured app linkages.");
15259                                pw.println();
15260                            }
15261                        }
15262                    }
15263                }
15264            }
15265
15266            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15267                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15268                if (packageName == null && permissionNames == null) {
15269                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15270                        if (iperm == 0) {
15271                            if (dumpState.onTitlePrinted())
15272                                pw.println();
15273                            pw.println("AppOp Permissions:");
15274                        }
15275                        pw.print("  AppOp Permission ");
15276                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15277                        pw.println(":");
15278                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15279                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15280                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15281                        }
15282                    }
15283                }
15284            }
15285
15286            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15287                boolean printedSomething = false;
15288                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15289                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15290                        continue;
15291                    }
15292                    if (!printedSomething) {
15293                        if (dumpState.onTitlePrinted())
15294                            pw.println();
15295                        pw.println("Registered ContentProviders:");
15296                        printedSomething = true;
15297                    }
15298                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15299                    pw.print("    "); pw.println(p.toString());
15300                }
15301                printedSomething = false;
15302                for (Map.Entry<String, PackageParser.Provider> entry :
15303                        mProvidersByAuthority.entrySet()) {
15304                    PackageParser.Provider p = entry.getValue();
15305                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15306                        continue;
15307                    }
15308                    if (!printedSomething) {
15309                        if (dumpState.onTitlePrinted())
15310                            pw.println();
15311                        pw.println("ContentProvider Authorities:");
15312                        printedSomething = true;
15313                    }
15314                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15315                    pw.print("    "); pw.println(p.toString());
15316                    if (p.info != null && p.info.applicationInfo != null) {
15317                        final String appInfo = p.info.applicationInfo.toString();
15318                        pw.print("      applicationInfo="); pw.println(appInfo);
15319                    }
15320                }
15321            }
15322
15323            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15324                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15325            }
15326
15327            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15328                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15329            }
15330
15331            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15332                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15333            }
15334
15335            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15336                // XXX should handle packageName != null by dumping only install data that
15337                // the given package is involved with.
15338                if (dumpState.onTitlePrinted()) pw.println();
15339                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15340            }
15341
15342            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15343                if (dumpState.onTitlePrinted()) pw.println();
15344                mSettings.dumpReadMessagesLPr(pw, dumpState);
15345
15346                pw.println();
15347                pw.println("Package warning messages:");
15348                BufferedReader in = null;
15349                String line = null;
15350                try {
15351                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15352                    while ((line = in.readLine()) != null) {
15353                        if (line.contains("ignored: updated version")) continue;
15354                        pw.println(line);
15355                    }
15356                } catch (IOException ignored) {
15357                } finally {
15358                    IoUtils.closeQuietly(in);
15359                }
15360            }
15361
15362            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15363                BufferedReader in = null;
15364                String line = null;
15365                try {
15366                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15367                    while ((line = in.readLine()) != null) {
15368                        if (line.contains("ignored: updated version")) continue;
15369                        pw.print("msg,");
15370                        pw.println(line);
15371                    }
15372                } catch (IOException ignored) {
15373                } finally {
15374                    IoUtils.closeQuietly(in);
15375                }
15376            }
15377        }
15378    }
15379
15380    private String dumpDomainString(String packageName) {
15381        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15382        List<IntentFilter> filters = getAllIntentFilters(packageName);
15383
15384        ArraySet<String> result = new ArraySet<>();
15385        if (iviList.size() > 0) {
15386            for (IntentFilterVerificationInfo ivi : iviList) {
15387                for (String host : ivi.getDomains()) {
15388                    result.add(host);
15389                }
15390            }
15391        }
15392        if (filters != null && filters.size() > 0) {
15393            for (IntentFilter filter : filters) {
15394                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15395                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15396                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15397                    result.addAll(filter.getHostsList());
15398                }
15399            }
15400        }
15401
15402        StringBuilder sb = new StringBuilder(result.size() * 16);
15403        for (String domain : result) {
15404            if (sb.length() > 0) sb.append(" ");
15405            sb.append(domain);
15406        }
15407        return sb.toString();
15408    }
15409
15410    // ------- apps on sdcard specific code -------
15411    static final boolean DEBUG_SD_INSTALL = false;
15412
15413    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15414
15415    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15416
15417    private boolean mMediaMounted = false;
15418
15419    static String getEncryptKey() {
15420        try {
15421            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15422                    SD_ENCRYPTION_KEYSTORE_NAME);
15423            if (sdEncKey == null) {
15424                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15425                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15426                if (sdEncKey == null) {
15427                    Slog.e(TAG, "Failed to create encryption keys");
15428                    return null;
15429                }
15430            }
15431            return sdEncKey;
15432        } catch (NoSuchAlgorithmException nsae) {
15433            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15434            return null;
15435        } catch (IOException ioe) {
15436            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15437            return null;
15438        }
15439    }
15440
15441    /*
15442     * Update media status on PackageManager.
15443     */
15444    @Override
15445    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15446        int callingUid = Binder.getCallingUid();
15447        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15448            throw new SecurityException("Media status can only be updated by the system");
15449        }
15450        // reader; this apparently protects mMediaMounted, but should probably
15451        // be a different lock in that case.
15452        synchronized (mPackages) {
15453            Log.i(TAG, "Updating external media status from "
15454                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15455                    + (mediaStatus ? "mounted" : "unmounted"));
15456            if (DEBUG_SD_INSTALL)
15457                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15458                        + ", mMediaMounted=" + mMediaMounted);
15459            if (mediaStatus == mMediaMounted) {
15460                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15461                        : 0, -1);
15462                mHandler.sendMessage(msg);
15463                return;
15464            }
15465            mMediaMounted = mediaStatus;
15466        }
15467        // Queue up an async operation since the package installation may take a
15468        // little while.
15469        mHandler.post(new Runnable() {
15470            public void run() {
15471                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15472            }
15473        });
15474    }
15475
15476    /**
15477     * Called by MountService when the initial ASECs to scan are available.
15478     * Should block until all the ASEC containers are finished being scanned.
15479     */
15480    public void scanAvailableAsecs() {
15481        updateExternalMediaStatusInner(true, false, false);
15482        if (mShouldRestoreconData) {
15483            SELinuxMMAC.setRestoreconDone();
15484            mShouldRestoreconData = false;
15485        }
15486    }
15487
15488    /*
15489     * Collect information of applications on external media, map them against
15490     * existing containers and update information based on current mount status.
15491     * Please note that we always have to report status if reportStatus has been
15492     * set to true especially when unloading packages.
15493     */
15494    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15495            boolean externalStorage) {
15496        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15497        int[] uidArr = EmptyArray.INT;
15498
15499        final String[] list = PackageHelper.getSecureContainerList();
15500        if (ArrayUtils.isEmpty(list)) {
15501            Log.i(TAG, "No secure containers found");
15502        } else {
15503            // Process list of secure containers and categorize them
15504            // as active or stale based on their package internal state.
15505
15506            // reader
15507            synchronized (mPackages) {
15508                for (String cid : list) {
15509                    // Leave stages untouched for now; installer service owns them
15510                    if (PackageInstallerService.isStageName(cid)) continue;
15511
15512                    if (DEBUG_SD_INSTALL)
15513                        Log.i(TAG, "Processing container " + cid);
15514                    String pkgName = getAsecPackageName(cid);
15515                    if (pkgName == null) {
15516                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15517                        continue;
15518                    }
15519                    if (DEBUG_SD_INSTALL)
15520                        Log.i(TAG, "Looking for pkg : " + pkgName);
15521
15522                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15523                    if (ps == null) {
15524                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15525                        continue;
15526                    }
15527
15528                    /*
15529                     * Skip packages that are not external if we're unmounting
15530                     * external storage.
15531                     */
15532                    if (externalStorage && !isMounted && !isExternal(ps)) {
15533                        continue;
15534                    }
15535
15536                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15537                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15538                    // The package status is changed only if the code path
15539                    // matches between settings and the container id.
15540                    if (ps.codePathString != null
15541                            && ps.codePathString.startsWith(args.getCodePath())) {
15542                        if (DEBUG_SD_INSTALL) {
15543                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15544                                    + " at code path: " + ps.codePathString);
15545                        }
15546
15547                        // We do have a valid package installed on sdcard
15548                        processCids.put(args, ps.codePathString);
15549                        final int uid = ps.appId;
15550                        if (uid != -1) {
15551                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15552                        }
15553                    } else {
15554                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15555                                + ps.codePathString);
15556                    }
15557                }
15558            }
15559
15560            Arrays.sort(uidArr);
15561        }
15562
15563        // Process packages with valid entries.
15564        if (isMounted) {
15565            if (DEBUG_SD_INSTALL)
15566                Log.i(TAG, "Loading packages");
15567            loadMediaPackages(processCids, uidArr, externalStorage);
15568            startCleaningPackages();
15569            mInstallerService.onSecureContainersAvailable();
15570        } else {
15571            if (DEBUG_SD_INSTALL)
15572                Log.i(TAG, "Unloading packages");
15573            unloadMediaPackages(processCids, uidArr, reportStatus);
15574        }
15575    }
15576
15577    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15578            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15579        final int size = infos.size();
15580        final String[] packageNames = new String[size];
15581        final int[] packageUids = new int[size];
15582        for (int i = 0; i < size; i++) {
15583            final ApplicationInfo info = infos.get(i);
15584            packageNames[i] = info.packageName;
15585            packageUids[i] = info.uid;
15586        }
15587        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15588                finishedReceiver);
15589    }
15590
15591    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15592            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15593        sendResourcesChangedBroadcast(mediaStatus, replacing,
15594                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15595    }
15596
15597    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15598            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15599        int size = pkgList.length;
15600        if (size > 0) {
15601            // Send broadcasts here
15602            Bundle extras = new Bundle();
15603            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15604            if (uidArr != null) {
15605                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15606            }
15607            if (replacing) {
15608                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15609            }
15610            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15611                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15612            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15613        }
15614    }
15615
15616   /*
15617     * Look at potentially valid container ids from processCids If package
15618     * information doesn't match the one on record or package scanning fails,
15619     * the cid is added to list of removeCids. We currently don't delete stale
15620     * containers.
15621     */
15622    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15623            boolean externalStorage) {
15624        ArrayList<String> pkgList = new ArrayList<String>();
15625        Set<AsecInstallArgs> keys = processCids.keySet();
15626
15627        for (AsecInstallArgs args : keys) {
15628            String codePath = processCids.get(args);
15629            if (DEBUG_SD_INSTALL)
15630                Log.i(TAG, "Loading container : " + args.cid);
15631            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15632            try {
15633                // Make sure there are no container errors first.
15634                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15635                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15636                            + " when installing from sdcard");
15637                    continue;
15638                }
15639                // Check code path here.
15640                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15641                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15642                            + " does not match one in settings " + codePath);
15643                    continue;
15644                }
15645                // Parse package
15646                int parseFlags = mDefParseFlags;
15647                if (args.isExternalAsec()) {
15648                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15649                }
15650                if (args.isFwdLocked()) {
15651                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15652                }
15653
15654                synchronized (mInstallLock) {
15655                    PackageParser.Package pkg = null;
15656                    try {
15657                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15658                    } catch (PackageManagerException e) {
15659                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15660                    }
15661                    // Scan the package
15662                    if (pkg != null) {
15663                        /*
15664                         * TODO why is the lock being held? doPostInstall is
15665                         * called in other places without the lock. This needs
15666                         * to be straightened out.
15667                         */
15668                        // writer
15669                        synchronized (mPackages) {
15670                            retCode = PackageManager.INSTALL_SUCCEEDED;
15671                            pkgList.add(pkg.packageName);
15672                            // Post process args
15673                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15674                                    pkg.applicationInfo.uid);
15675                        }
15676                    } else {
15677                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15678                    }
15679                }
15680
15681            } finally {
15682                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15683                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15684                }
15685            }
15686        }
15687        // writer
15688        synchronized (mPackages) {
15689            // If the platform SDK has changed since the last time we booted,
15690            // we need to re-grant app permission to catch any new ones that
15691            // appear. This is really a hack, and means that apps can in some
15692            // cases get permissions that the user didn't initially explicitly
15693            // allow... it would be nice to have some better way to handle
15694            // this situation.
15695            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15696                    : mSettings.getInternalVersion();
15697            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15698                    : StorageManager.UUID_PRIVATE_INTERNAL;
15699
15700            int updateFlags = UPDATE_PERMISSIONS_ALL;
15701            if (ver.sdkVersion != mSdkVersion) {
15702                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15703                        + mSdkVersion + "; regranting permissions for external");
15704                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15705            }
15706            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15707
15708            // Yay, everything is now upgraded
15709            ver.forceCurrent();
15710
15711            // can downgrade to reader
15712            // Persist settings
15713            mSettings.writeLPr();
15714        }
15715        // Send a broadcast to let everyone know we are done processing
15716        if (pkgList.size() > 0) {
15717            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15718        }
15719    }
15720
15721   /*
15722     * Utility method to unload a list of specified containers
15723     */
15724    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15725        // Just unmount all valid containers.
15726        for (AsecInstallArgs arg : cidArgs) {
15727            synchronized (mInstallLock) {
15728                arg.doPostDeleteLI(false);
15729           }
15730       }
15731   }
15732
15733    /*
15734     * Unload packages mounted on external media. This involves deleting package
15735     * data from internal structures, sending broadcasts about diabled packages,
15736     * gc'ing to free up references, unmounting all secure containers
15737     * corresponding to packages on external media, and posting a
15738     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15739     * that we always have to post this message if status has been requested no
15740     * matter what.
15741     */
15742    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15743            final boolean reportStatus) {
15744        if (DEBUG_SD_INSTALL)
15745            Log.i(TAG, "unloading media packages");
15746        ArrayList<String> pkgList = new ArrayList<String>();
15747        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15748        final Set<AsecInstallArgs> keys = processCids.keySet();
15749        for (AsecInstallArgs args : keys) {
15750            String pkgName = args.getPackageName();
15751            if (DEBUG_SD_INSTALL)
15752                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15753            // Delete package internally
15754            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15755            synchronized (mInstallLock) {
15756                boolean res = deletePackageLI(pkgName, null, false, null, null,
15757                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15758                if (res) {
15759                    pkgList.add(pkgName);
15760                } else {
15761                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15762                    failedList.add(args);
15763                }
15764            }
15765        }
15766
15767        // reader
15768        synchronized (mPackages) {
15769            // We didn't update the settings after removing each package;
15770            // write them now for all packages.
15771            mSettings.writeLPr();
15772        }
15773
15774        // We have to absolutely send UPDATED_MEDIA_STATUS only
15775        // after confirming that all the receivers processed the ordered
15776        // broadcast when packages get disabled, force a gc to clean things up.
15777        // and unload all the containers.
15778        if (pkgList.size() > 0) {
15779            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15780                    new IIntentReceiver.Stub() {
15781                public void performReceive(Intent intent, int resultCode, String data,
15782                        Bundle extras, boolean ordered, boolean sticky,
15783                        int sendingUser) throws RemoteException {
15784                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15785                            reportStatus ? 1 : 0, 1, keys);
15786                    mHandler.sendMessage(msg);
15787                }
15788            });
15789        } else {
15790            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15791                    keys);
15792            mHandler.sendMessage(msg);
15793        }
15794    }
15795
15796    private void loadPrivatePackages(final VolumeInfo vol) {
15797        mHandler.post(new Runnable() {
15798            @Override
15799            public void run() {
15800                loadPrivatePackagesInner(vol);
15801            }
15802        });
15803    }
15804
15805    private void loadPrivatePackagesInner(VolumeInfo vol) {
15806        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15807        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15808
15809        final VersionInfo ver;
15810        final List<PackageSetting> packages;
15811        synchronized (mPackages) {
15812            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15813            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15814        }
15815
15816        for (PackageSetting ps : packages) {
15817            synchronized (mInstallLock) {
15818                final PackageParser.Package pkg;
15819                try {
15820                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
15821                    loaded.add(pkg.applicationInfo);
15822                } catch (PackageManagerException e) {
15823                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15824                }
15825
15826                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15827                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15828                }
15829            }
15830        }
15831
15832        synchronized (mPackages) {
15833            int updateFlags = UPDATE_PERMISSIONS_ALL;
15834            if (ver.sdkVersion != mSdkVersion) {
15835                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15836                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15837                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15838            }
15839            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
15840
15841            // Yay, everything is now upgraded
15842            ver.forceCurrent();
15843
15844            mSettings.writeLPr();
15845        }
15846
15847        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15848        sendResourcesChangedBroadcast(true, false, loaded, null);
15849    }
15850
15851    private void unloadPrivatePackages(final VolumeInfo vol) {
15852        mHandler.post(new Runnable() {
15853            @Override
15854            public void run() {
15855                unloadPrivatePackagesInner(vol);
15856            }
15857        });
15858    }
15859
15860    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15861        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15862        synchronized (mInstallLock) {
15863        synchronized (mPackages) {
15864            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15865            for (PackageSetting ps : packages) {
15866                if (ps.pkg == null) continue;
15867
15868                final ApplicationInfo info = ps.pkg.applicationInfo;
15869                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15870                if (deletePackageLI(ps.name, null, false, null, null,
15871                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15872                    unloaded.add(info);
15873                } else {
15874                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15875                }
15876            }
15877
15878            mSettings.writeLPr();
15879        }
15880        }
15881
15882        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15883        sendResourcesChangedBroadcast(false, false, unloaded, null);
15884    }
15885
15886    /**
15887     * Examine all users present on given mounted volume, and destroy data
15888     * belonging to users that are no longer valid, or whose user ID has been
15889     * recycled.
15890     */
15891    private void reconcileUsers(String volumeUuid) {
15892        final File[] files = FileUtils
15893                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15894        for (File file : files) {
15895            if (!file.isDirectory()) continue;
15896
15897            final int userId;
15898            final UserInfo info;
15899            try {
15900                userId = Integer.parseInt(file.getName());
15901                info = sUserManager.getUserInfo(userId);
15902            } catch (NumberFormatException e) {
15903                Slog.w(TAG, "Invalid user directory " + file);
15904                continue;
15905            }
15906
15907            boolean destroyUser = false;
15908            if (info == null) {
15909                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15910                        + " because no matching user was found");
15911                destroyUser = true;
15912            } else {
15913                try {
15914                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15915                } catch (IOException e) {
15916                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15917                            + " because we failed to enforce serial number: " + e);
15918                    destroyUser = true;
15919                }
15920            }
15921
15922            if (destroyUser) {
15923                synchronized (mInstallLock) {
15924                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15925                }
15926            }
15927        }
15928
15929        final StorageManager sm = mContext.getSystemService(StorageManager.class);
15930        final UserManager um = mContext.getSystemService(UserManager.class);
15931        for (UserInfo user : um.getUsers()) {
15932            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15933            if (userDir.exists()) continue;
15934
15935            try {
15936                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
15937                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15938            } catch (IOException e) {
15939                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15940            }
15941        }
15942    }
15943
15944    /**
15945     * Examine all apps present on given mounted volume, and destroy apps that
15946     * aren't expected, either due to uninstallation or reinstallation on
15947     * another volume.
15948     */
15949    private void reconcileApps(String volumeUuid) {
15950        final File[] files = FileUtils
15951                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15952        for (File file : files) {
15953            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15954                    && !PackageInstallerService.isStageName(file.getName());
15955            if (!isPackage) {
15956                // Ignore entries which are not packages
15957                continue;
15958            }
15959
15960            boolean destroyApp = false;
15961            String packageName = null;
15962            try {
15963                final PackageLite pkg = PackageParser.parsePackageLite(file,
15964                        PackageParser.PARSE_MUST_BE_APK);
15965                packageName = pkg.packageName;
15966
15967                synchronized (mPackages) {
15968                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15969                    if (ps == null) {
15970                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15971                                + volumeUuid + " because we found no install record");
15972                        destroyApp = true;
15973                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15974                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15975                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15976                        destroyApp = true;
15977                    }
15978                }
15979
15980            } catch (PackageParserException e) {
15981                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15982                destroyApp = true;
15983            }
15984
15985            if (destroyApp) {
15986                synchronized (mInstallLock) {
15987                    if (packageName != null) {
15988                        removeDataDirsLI(volumeUuid, packageName);
15989                    }
15990                    if (file.isDirectory()) {
15991                        mInstaller.rmPackageDir(file.getAbsolutePath());
15992                    } else {
15993                        file.delete();
15994                    }
15995                }
15996            }
15997        }
15998    }
15999
16000    private void unfreezePackage(String packageName) {
16001        synchronized (mPackages) {
16002            final PackageSetting ps = mSettings.mPackages.get(packageName);
16003            if (ps != null) {
16004                ps.frozen = false;
16005            }
16006        }
16007    }
16008
16009    @Override
16010    public int movePackage(final String packageName, final String volumeUuid) {
16011        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16012
16013        final int moveId = mNextMoveId.getAndIncrement();
16014        mHandler.post(new Runnable() {
16015            @Override
16016            public void run() {
16017                try {
16018                    movePackageInternal(packageName, volumeUuid, moveId);
16019                } catch (PackageManagerException e) {
16020                    Slog.w(TAG, "Failed to move " + packageName, e);
16021                    mMoveCallbacks.notifyStatusChanged(moveId,
16022                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16023                }
16024            }
16025        });
16026        return moveId;
16027    }
16028
16029    private void movePackageInternal(final String packageName, final String volumeUuid,
16030            final int moveId) throws PackageManagerException {
16031        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16032        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16033        final PackageManager pm = mContext.getPackageManager();
16034
16035        final boolean currentAsec;
16036        final String currentVolumeUuid;
16037        final File codeFile;
16038        final String installerPackageName;
16039        final String packageAbiOverride;
16040        final int appId;
16041        final String seinfo;
16042        final String label;
16043
16044        // reader
16045        synchronized (mPackages) {
16046            final PackageParser.Package pkg = mPackages.get(packageName);
16047            final PackageSetting ps = mSettings.mPackages.get(packageName);
16048            if (pkg == null || ps == null) {
16049                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16050            }
16051
16052            if (pkg.applicationInfo.isSystemApp()) {
16053                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16054                        "Cannot move system application");
16055            }
16056
16057            if (pkg.applicationInfo.isExternalAsec()) {
16058                currentAsec = true;
16059                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16060            } else if (pkg.applicationInfo.isForwardLocked()) {
16061                currentAsec = true;
16062                currentVolumeUuid = "forward_locked";
16063            } else {
16064                currentAsec = false;
16065                currentVolumeUuid = ps.volumeUuid;
16066
16067                final File probe = new File(pkg.codePath);
16068                final File probeOat = new File(probe, "oat");
16069                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16070                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16071                            "Move only supported for modern cluster style installs");
16072                }
16073            }
16074
16075            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16076                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16077                        "Package already moved to " + volumeUuid);
16078            }
16079
16080            if (ps.frozen) {
16081                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16082                        "Failed to move already frozen package");
16083            }
16084            ps.frozen = true;
16085
16086            codeFile = new File(pkg.codePath);
16087            installerPackageName = ps.installerPackageName;
16088            packageAbiOverride = ps.cpuAbiOverrideString;
16089            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16090            seinfo = pkg.applicationInfo.seinfo;
16091            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16092        }
16093
16094        // Now that we're guarded by frozen state, kill app during move
16095        final long token = Binder.clearCallingIdentity();
16096        try {
16097            killApplication(packageName, appId, "move pkg");
16098        } finally {
16099            Binder.restoreCallingIdentity(token);
16100        }
16101
16102        final Bundle extras = new Bundle();
16103        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16104        extras.putString(Intent.EXTRA_TITLE, label);
16105        mMoveCallbacks.notifyCreated(moveId, extras);
16106
16107        int installFlags;
16108        final boolean moveCompleteApp;
16109        final File measurePath;
16110
16111        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16112            installFlags = INSTALL_INTERNAL;
16113            moveCompleteApp = !currentAsec;
16114            measurePath = Environment.getDataAppDirectory(volumeUuid);
16115        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16116            installFlags = INSTALL_EXTERNAL;
16117            moveCompleteApp = false;
16118            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16119        } else {
16120            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16121            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16122                    || !volume.isMountedWritable()) {
16123                unfreezePackage(packageName);
16124                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16125                        "Move location not mounted private volume");
16126            }
16127
16128            Preconditions.checkState(!currentAsec);
16129
16130            installFlags = INSTALL_INTERNAL;
16131            moveCompleteApp = true;
16132            measurePath = Environment.getDataAppDirectory(volumeUuid);
16133        }
16134
16135        final PackageStats stats = new PackageStats(null, -1);
16136        synchronized (mInstaller) {
16137            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16138                unfreezePackage(packageName);
16139                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16140                        "Failed to measure package size");
16141            }
16142        }
16143
16144        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16145                + stats.dataSize);
16146
16147        final long startFreeBytes = measurePath.getFreeSpace();
16148        final long sizeBytes;
16149        if (moveCompleteApp) {
16150            sizeBytes = stats.codeSize + stats.dataSize;
16151        } else {
16152            sizeBytes = stats.codeSize;
16153        }
16154
16155        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16156            unfreezePackage(packageName);
16157            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16158                    "Not enough free space to move");
16159        }
16160
16161        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16162
16163        final CountDownLatch installedLatch = new CountDownLatch(1);
16164        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16165            @Override
16166            public void onUserActionRequired(Intent intent) throws RemoteException {
16167                throw new IllegalStateException();
16168            }
16169
16170            @Override
16171            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16172                    Bundle extras) throws RemoteException {
16173                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16174                        + PackageManager.installStatusToString(returnCode, msg));
16175
16176                installedLatch.countDown();
16177
16178                // Regardless of success or failure of the move operation,
16179                // always unfreeze the package
16180                unfreezePackage(packageName);
16181
16182                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16183                switch (status) {
16184                    case PackageInstaller.STATUS_SUCCESS:
16185                        mMoveCallbacks.notifyStatusChanged(moveId,
16186                                PackageManager.MOVE_SUCCEEDED);
16187                        break;
16188                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16189                        mMoveCallbacks.notifyStatusChanged(moveId,
16190                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16191                        break;
16192                    default:
16193                        mMoveCallbacks.notifyStatusChanged(moveId,
16194                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16195                        break;
16196                }
16197            }
16198        };
16199
16200        final MoveInfo move;
16201        if (moveCompleteApp) {
16202            // Kick off a thread to report progress estimates
16203            new Thread() {
16204                @Override
16205                public void run() {
16206                    while (true) {
16207                        try {
16208                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16209                                break;
16210                            }
16211                        } catch (InterruptedException ignored) {
16212                        }
16213
16214                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16215                        final int progress = 10 + (int) MathUtils.constrain(
16216                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16217                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16218                    }
16219                }
16220            }.start();
16221
16222            final String dataAppName = codeFile.getName();
16223            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16224                    dataAppName, appId, seinfo);
16225        } else {
16226            move = null;
16227        }
16228
16229        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16230
16231        final Message msg = mHandler.obtainMessage(INIT_COPY);
16232        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16233        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16234                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16235        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16236        msg.obj = params;
16237
16238        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16239                System.identityHashCode(msg.obj));
16240        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16241                System.identityHashCode(msg.obj));
16242
16243        mHandler.sendMessage(msg);
16244    }
16245
16246    @Override
16247    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16248        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16249
16250        final int realMoveId = mNextMoveId.getAndIncrement();
16251        final Bundle extras = new Bundle();
16252        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16253        mMoveCallbacks.notifyCreated(realMoveId, extras);
16254
16255        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16256            @Override
16257            public void onCreated(int moveId, Bundle extras) {
16258                // Ignored
16259            }
16260
16261            @Override
16262            public void onStatusChanged(int moveId, int status, long estMillis) {
16263                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16264            }
16265        };
16266
16267        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16268        storage.setPrimaryStorageUuid(volumeUuid, callback);
16269        return realMoveId;
16270    }
16271
16272    @Override
16273    public int getMoveStatus(int moveId) {
16274        mContext.enforceCallingOrSelfPermission(
16275                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16276        return mMoveCallbacks.mLastStatus.get(moveId);
16277    }
16278
16279    @Override
16280    public void registerMoveCallback(IPackageMoveObserver callback) {
16281        mContext.enforceCallingOrSelfPermission(
16282                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16283        mMoveCallbacks.register(callback);
16284    }
16285
16286    @Override
16287    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16288        mContext.enforceCallingOrSelfPermission(
16289                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16290        mMoveCallbacks.unregister(callback);
16291    }
16292
16293    @Override
16294    public boolean setInstallLocation(int loc) {
16295        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16296                null);
16297        if (getInstallLocation() == loc) {
16298            return true;
16299        }
16300        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16301                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16302            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16303                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16304            return true;
16305        }
16306        return false;
16307   }
16308
16309    @Override
16310    public int getInstallLocation() {
16311        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16312                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16313                PackageHelper.APP_INSTALL_AUTO);
16314    }
16315
16316    /** Called by UserManagerService */
16317    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16318        mDirtyUsers.remove(userHandle);
16319        mSettings.removeUserLPw(userHandle);
16320        mPendingBroadcasts.remove(userHandle);
16321        if (mInstaller != null) {
16322            // Technically, we shouldn't be doing this with the package lock
16323            // held.  However, this is very rare, and there is already so much
16324            // other disk I/O going on, that we'll let it slide for now.
16325            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16326            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16327                final String volumeUuid = vol.getFsUuid();
16328                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16329                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16330            }
16331        }
16332        mUserNeedsBadging.delete(userHandle);
16333        removeUnusedPackagesLILPw(userManager, userHandle);
16334    }
16335
16336    /**
16337     * We're removing userHandle and would like to remove any downloaded packages
16338     * that are no longer in use by any other user.
16339     * @param userHandle the user being removed
16340     */
16341    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16342        final boolean DEBUG_CLEAN_APKS = false;
16343        int [] users = userManager.getUserIds();
16344        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16345        while (psit.hasNext()) {
16346            PackageSetting ps = psit.next();
16347            if (ps.pkg == null) {
16348                continue;
16349            }
16350            final String packageName = ps.pkg.packageName;
16351            // Skip over if system app
16352            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16353                continue;
16354            }
16355            if (DEBUG_CLEAN_APKS) {
16356                Slog.i(TAG, "Checking package " + packageName);
16357            }
16358            boolean keep = false;
16359            for (int i = 0; i < users.length; i++) {
16360                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16361                    keep = true;
16362                    if (DEBUG_CLEAN_APKS) {
16363                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16364                                + users[i]);
16365                    }
16366                    break;
16367                }
16368            }
16369            if (!keep) {
16370                if (DEBUG_CLEAN_APKS) {
16371                    Slog.i(TAG, "  Removing package " + packageName);
16372                }
16373                mHandler.post(new Runnable() {
16374                    public void run() {
16375                        deletePackageX(packageName, userHandle, 0);
16376                    } //end run
16377                });
16378            }
16379        }
16380    }
16381
16382    /** Called by UserManagerService */
16383    void createNewUserLILPw(int userHandle) {
16384        if (mInstaller != null) {
16385            mInstaller.createUserConfig(userHandle);
16386            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16387            applyFactoryDefaultBrowserLPw(userHandle);
16388            primeDomainVerificationsLPw(userHandle);
16389        }
16390    }
16391
16392    void newUserCreated(final int userHandle) {
16393        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16394    }
16395
16396    @Override
16397    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16398        mContext.enforceCallingOrSelfPermission(
16399                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16400                "Only package verification agents can read the verifier device identity");
16401
16402        synchronized (mPackages) {
16403            return mSettings.getVerifierDeviceIdentityLPw();
16404        }
16405    }
16406
16407    @Override
16408    public void setPermissionEnforced(String permission, boolean enforced) {
16409        // TODO: Now that we no longer change GID for storage, this should to away.
16410        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16411                "setPermissionEnforced");
16412        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16413            synchronized (mPackages) {
16414                if (mSettings.mReadExternalStorageEnforced == null
16415                        || mSettings.mReadExternalStorageEnforced != enforced) {
16416                    mSettings.mReadExternalStorageEnforced = enforced;
16417                    mSettings.writeLPr();
16418                }
16419            }
16420            // kill any non-foreground processes so we restart them and
16421            // grant/revoke the GID.
16422            final IActivityManager am = ActivityManagerNative.getDefault();
16423            if (am != null) {
16424                final long token = Binder.clearCallingIdentity();
16425                try {
16426                    am.killProcessesBelowForeground("setPermissionEnforcement");
16427                } catch (RemoteException e) {
16428                } finally {
16429                    Binder.restoreCallingIdentity(token);
16430                }
16431            }
16432        } else {
16433            throw new IllegalArgumentException("No selective enforcement for " + permission);
16434        }
16435    }
16436
16437    @Override
16438    @Deprecated
16439    public boolean isPermissionEnforced(String permission) {
16440        return true;
16441    }
16442
16443    @Override
16444    public boolean isStorageLow() {
16445        final long token = Binder.clearCallingIdentity();
16446        try {
16447            final DeviceStorageMonitorInternal
16448                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16449            if (dsm != null) {
16450                return dsm.isMemoryLow();
16451            } else {
16452                return false;
16453            }
16454        } finally {
16455            Binder.restoreCallingIdentity(token);
16456        }
16457    }
16458
16459    @Override
16460    public IPackageInstaller getPackageInstaller() {
16461        return mInstallerService;
16462    }
16463
16464    private boolean userNeedsBadging(int userId) {
16465        int index = mUserNeedsBadging.indexOfKey(userId);
16466        if (index < 0) {
16467            final UserInfo userInfo;
16468            final long token = Binder.clearCallingIdentity();
16469            try {
16470                userInfo = sUserManager.getUserInfo(userId);
16471            } finally {
16472                Binder.restoreCallingIdentity(token);
16473            }
16474            final boolean b;
16475            if (userInfo != null && userInfo.isManagedProfile()) {
16476                b = true;
16477            } else {
16478                b = false;
16479            }
16480            mUserNeedsBadging.put(userId, b);
16481            return b;
16482        }
16483        return mUserNeedsBadging.valueAt(index);
16484    }
16485
16486    @Override
16487    public KeySet getKeySetByAlias(String packageName, String alias) {
16488        if (packageName == null || alias == null) {
16489            return null;
16490        }
16491        synchronized(mPackages) {
16492            final PackageParser.Package pkg = mPackages.get(packageName);
16493            if (pkg == null) {
16494                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16495                throw new IllegalArgumentException("Unknown package: " + packageName);
16496            }
16497            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16498            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16499        }
16500    }
16501
16502    @Override
16503    public KeySet getSigningKeySet(String packageName) {
16504        if (packageName == null) {
16505            return null;
16506        }
16507        synchronized(mPackages) {
16508            final PackageParser.Package pkg = mPackages.get(packageName);
16509            if (pkg == null) {
16510                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16511                throw new IllegalArgumentException("Unknown package: " + packageName);
16512            }
16513            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16514                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16515                throw new SecurityException("May not access signing KeySet of other apps.");
16516            }
16517            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16518            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16519        }
16520    }
16521
16522    @Override
16523    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16524        if (packageName == null || ks == null) {
16525            return false;
16526        }
16527        synchronized(mPackages) {
16528            final PackageParser.Package pkg = mPackages.get(packageName);
16529            if (pkg == null) {
16530                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16531                throw new IllegalArgumentException("Unknown package: " + packageName);
16532            }
16533            IBinder ksh = ks.getToken();
16534            if (ksh instanceof KeySetHandle) {
16535                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16536                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16537            }
16538            return false;
16539        }
16540    }
16541
16542    @Override
16543    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16544        if (packageName == null || ks == null) {
16545            return false;
16546        }
16547        synchronized(mPackages) {
16548            final PackageParser.Package pkg = mPackages.get(packageName);
16549            if (pkg == null) {
16550                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16551                throw new IllegalArgumentException("Unknown package: " + packageName);
16552            }
16553            IBinder ksh = ks.getToken();
16554            if (ksh instanceof KeySetHandle) {
16555                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16556                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16557            }
16558            return false;
16559        }
16560    }
16561
16562    /**
16563     * Check and throw if the given before/after packages would be considered a
16564     * downgrade.
16565     */
16566    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16567            throws PackageManagerException {
16568        if (after.versionCode < before.mVersionCode) {
16569            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16570                    "Update version code " + after.versionCode + " is older than current "
16571                    + before.mVersionCode);
16572        } else if (after.versionCode == before.mVersionCode) {
16573            if (after.baseRevisionCode < before.baseRevisionCode) {
16574                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16575                        "Update base revision code " + after.baseRevisionCode
16576                        + " is older than current " + before.baseRevisionCode);
16577            }
16578
16579            if (!ArrayUtils.isEmpty(after.splitNames)) {
16580                for (int i = 0; i < after.splitNames.length; i++) {
16581                    final String splitName = after.splitNames[i];
16582                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16583                    if (j != -1) {
16584                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16585                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16586                                    "Update split " + splitName + " revision code "
16587                                    + after.splitRevisionCodes[i] + " is older than current "
16588                                    + before.splitRevisionCodes[j]);
16589                        }
16590                    }
16591                }
16592            }
16593        }
16594    }
16595
16596    private static class MoveCallbacks extends Handler {
16597        private static final int MSG_CREATED = 1;
16598        private static final int MSG_STATUS_CHANGED = 2;
16599
16600        private final RemoteCallbackList<IPackageMoveObserver>
16601                mCallbacks = new RemoteCallbackList<>();
16602
16603        private final SparseIntArray mLastStatus = new SparseIntArray();
16604
16605        public MoveCallbacks(Looper looper) {
16606            super(looper);
16607        }
16608
16609        public void register(IPackageMoveObserver callback) {
16610            mCallbacks.register(callback);
16611        }
16612
16613        public void unregister(IPackageMoveObserver callback) {
16614            mCallbacks.unregister(callback);
16615        }
16616
16617        @Override
16618        public void handleMessage(Message msg) {
16619            final SomeArgs args = (SomeArgs) msg.obj;
16620            final int n = mCallbacks.beginBroadcast();
16621            for (int i = 0; i < n; i++) {
16622                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16623                try {
16624                    invokeCallback(callback, msg.what, args);
16625                } catch (RemoteException ignored) {
16626                }
16627            }
16628            mCallbacks.finishBroadcast();
16629            args.recycle();
16630        }
16631
16632        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16633                throws RemoteException {
16634            switch (what) {
16635                case MSG_CREATED: {
16636                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16637                    break;
16638                }
16639                case MSG_STATUS_CHANGED: {
16640                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16641                    break;
16642                }
16643            }
16644        }
16645
16646        private void notifyCreated(int moveId, Bundle extras) {
16647            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16648
16649            final SomeArgs args = SomeArgs.obtain();
16650            args.argi1 = moveId;
16651            args.arg2 = extras;
16652            obtainMessage(MSG_CREATED, args).sendToTarget();
16653        }
16654
16655        private void notifyStatusChanged(int moveId, int status) {
16656            notifyStatusChanged(moveId, status, -1);
16657        }
16658
16659        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16660            Slog.v(TAG, "Move " + moveId + " status " + status);
16661
16662            final SomeArgs args = SomeArgs.obtain();
16663            args.argi1 = moveId;
16664            args.argi2 = status;
16665            args.arg3 = estMillis;
16666            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16667
16668            synchronized (mLastStatus) {
16669                mLastStatus.put(moveId, status);
16670            }
16671        }
16672    }
16673
16674    private final class OnPermissionChangeListeners extends Handler {
16675        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16676
16677        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16678                new RemoteCallbackList<>();
16679
16680        public OnPermissionChangeListeners(Looper looper) {
16681            super(looper);
16682        }
16683
16684        @Override
16685        public void handleMessage(Message msg) {
16686            switch (msg.what) {
16687                case MSG_ON_PERMISSIONS_CHANGED: {
16688                    final int uid = msg.arg1;
16689                    handleOnPermissionsChanged(uid);
16690                } break;
16691            }
16692        }
16693
16694        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16695            mPermissionListeners.register(listener);
16696
16697        }
16698
16699        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16700            mPermissionListeners.unregister(listener);
16701        }
16702
16703        public void onPermissionsChanged(int uid) {
16704            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16705                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16706            }
16707        }
16708
16709        private void handleOnPermissionsChanged(int uid) {
16710            final int count = mPermissionListeners.beginBroadcast();
16711            try {
16712                for (int i = 0; i < count; i++) {
16713                    IOnPermissionsChangeListener callback = mPermissionListeners
16714                            .getBroadcastItem(i);
16715                    try {
16716                        callback.onPermissionsChanged(uid);
16717                    } catch (RemoteException e) {
16718                        Log.e(TAG, "Permission listener is dead", e);
16719                    }
16720                }
16721            } finally {
16722                mPermissionListeners.finishBroadcast();
16723            }
16724        }
16725    }
16726
16727    private class PackageManagerInternalImpl extends PackageManagerInternal {
16728        @Override
16729        public void setLocationPackagesProvider(PackagesProvider provider) {
16730            synchronized (mPackages) {
16731                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16732            }
16733        }
16734
16735        @Override
16736        public void setImePackagesProvider(PackagesProvider provider) {
16737            synchronized (mPackages) {
16738                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16739            }
16740        }
16741
16742        @Override
16743        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16744            synchronized (mPackages) {
16745                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16746            }
16747        }
16748
16749        @Override
16750        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16751            synchronized (mPackages) {
16752                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16753            }
16754        }
16755
16756        @Override
16757        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16758            synchronized (mPackages) {
16759                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16760            }
16761        }
16762
16763        @Override
16764        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16765            synchronized (mPackages) {
16766                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16767            }
16768        }
16769
16770        @Override
16771        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16772            synchronized (mPackages) {
16773                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16774            }
16775        }
16776
16777        @Override
16778        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16779            synchronized (mPackages) {
16780                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16781                        packageName, userId);
16782            }
16783        }
16784
16785        @Override
16786        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16787            synchronized (mPackages) {
16788                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16789                        packageName, userId);
16790            }
16791        }
16792        @Override
16793        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16794            synchronized (mPackages) {
16795                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16796                        packageName, userId);
16797            }
16798        }
16799    }
16800
16801    @Override
16802    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16803        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16804        synchronized (mPackages) {
16805            final long identity = Binder.clearCallingIdentity();
16806            try {
16807                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16808                        packageNames, userId);
16809            } finally {
16810                Binder.restoreCallingIdentity(identity);
16811            }
16812        }
16813    }
16814
16815    private static void enforceSystemOrPhoneCaller(String tag) {
16816        int callingUid = Binder.getCallingUid();
16817        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16818            throw new SecurityException(
16819                    "Cannot call " + tag + " from UID " + callingUid);
16820        }
16821    }
16822}
16823