PackageManagerService.java revision 8324a6ee8334668c25e05c669bc04bf9c0c8c583
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_USER_OWNER;
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.InstructionSets.getAppDexInstructionSets;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
86
87import android.Manifest;
88import android.app.ActivityManager;
89import android.app.ActivityManagerNative;
90import android.app.AppGlobals;
91import android.app.IActivityManager;
92import android.app.admin.IDevicePolicyManager;
93import android.app.backup.IBackupManager;
94import android.app.usage.UsageStats;
95import android.app.usage.UsageStatsManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.FeatureInfo;
108import android.content.pm.IOnPermissionsChangeListener;
109import android.content.pm.IPackageDataObserver;
110import android.content.pm.IPackageDeleteObserver;
111import android.content.pm.IPackageDeleteObserver2;
112import android.content.pm.IPackageInstallObserver2;
113import android.content.pm.IPackageInstaller;
114import android.content.pm.IPackageManager;
115import android.content.pm.IPackageMoveObserver;
116import android.content.pm.IPackageStatsObserver;
117import android.content.pm.InstrumentationInfo;
118import android.content.pm.IntentFilterVerificationInfo;
119import android.content.pm.KeySet;
120import android.content.pm.ManifestDigest;
121import android.content.pm.PackageCleanItem;
122import android.content.pm.PackageInfo;
123import android.content.pm.PackageInfoLite;
124import android.content.pm.PackageInstaller;
125import android.content.pm.PackageManager;
126import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
127import android.content.pm.PackageManagerInternal;
128import android.content.pm.PackageParser;
129import android.content.pm.PackageParser.ActivityIntentInfo;
130import android.content.pm.PackageParser.PackageLite;
131import android.content.pm.PackageParser.PackageParserException;
132import android.content.pm.PackageStats;
133import android.content.pm.PackageUserState;
134import android.content.pm.ParceledListSlice;
135import android.content.pm.PermissionGroupInfo;
136import android.content.pm.PermissionInfo;
137import android.content.pm.ProviderInfo;
138import android.content.pm.ResolveInfo;
139import android.content.pm.ServiceInfo;
140import android.content.pm.Signature;
141import android.content.pm.UserInfo;
142import android.content.pm.VerificationParams;
143import android.content.pm.VerifierDeviceIdentity;
144import android.content.pm.VerifierInfo;
145import android.content.res.Resources;
146import android.hardware.display.DisplayManager;
147import android.net.Uri;
148import android.os.Debug;
149import android.os.Binder;
150import android.os.Build;
151import android.os.Bundle;
152import android.os.Environment;
153import android.os.Environment.UserEnvironment;
154import android.os.FileUtils;
155import android.os.Handler;
156import android.os.IBinder;
157import android.os.Looper;
158import android.os.Message;
159import android.os.Parcel;
160import android.os.ParcelFileDescriptor;
161import android.os.Process;
162import android.os.RemoteCallbackList;
163import android.os.RemoteException;
164import android.os.SELinux;
165import android.os.ServiceManager;
166import android.os.SystemClock;
167import android.os.SystemProperties;
168import android.os.Trace;
169import android.os.UserHandle;
170import android.os.UserManager;
171import android.os.storage.IMountService;
172import android.os.storage.MountServiceInternal;
173import android.os.storage.StorageEventListener;
174import android.os.storage.StorageManager;
175import android.os.storage.VolumeInfo;
176import android.os.storage.VolumeRecord;
177import android.security.KeyStore;
178import android.security.SystemKeyStore;
179import android.system.ErrnoException;
180import android.system.Os;
181import android.system.StructStat;
182import android.text.TextUtils;
183import android.text.format.DateUtils;
184import android.util.ArrayMap;
185import android.util.ArraySet;
186import android.util.AtomicFile;
187import android.util.DisplayMetrics;
188import android.util.EventLog;
189import android.util.ExceptionUtils;
190import android.util.Log;
191import android.util.LogPrinter;
192import android.util.MathUtils;
193import android.util.PrintStreamPrinter;
194import android.util.Slog;
195import android.util.SparseArray;
196import android.util.SparseBooleanArray;
197import android.util.SparseIntArray;
198import android.util.Xml;
199import android.view.Display;
200
201import dalvik.system.DexFile;
202import dalvik.system.VMRuntime;
203
204import libcore.io.IoUtils;
205import libcore.util.EmptyArray;
206
207import com.android.internal.R;
208import com.android.internal.annotations.GuardedBy;
209import com.android.internal.app.IMediaContainerService;
210import com.android.internal.app.ResolverActivity;
211import com.android.internal.content.NativeLibraryHelper;
212import com.android.internal.content.PackageHelper;
213import com.android.internal.os.IParcelFileDescriptorFactory;
214import com.android.internal.os.SomeArgs;
215import com.android.internal.os.Zygote;
216import com.android.internal.util.ArrayUtils;
217import com.android.internal.util.FastPrintWriter;
218import com.android.internal.util.FastXmlSerializer;
219import com.android.internal.util.IndentingPrintWriter;
220import com.android.internal.util.Preconditions;
221import com.android.server.EventLogTags;
222import com.android.server.FgThread;
223import com.android.server.IntentResolver;
224import com.android.server.LocalServices;
225import com.android.server.ServiceThread;
226import com.android.server.SystemConfig;
227import com.android.server.Watchdog;
228import com.android.server.pm.PermissionsState.PermissionState;
229import com.android.server.pm.Settings.DatabaseVersion;
230import com.android.server.pm.Settings.VersionInfo;
231import com.android.server.storage.DeviceStorageMonitorInternal;
232
233import org.xmlpull.v1.XmlPullParser;
234import org.xmlpull.v1.XmlPullParserException;
235import org.xmlpull.v1.XmlSerializer;
236
237import java.io.BufferedInputStream;
238import java.io.BufferedOutputStream;
239import java.io.BufferedReader;
240import java.io.ByteArrayInputStream;
241import java.io.ByteArrayOutputStream;
242import java.io.File;
243import java.io.FileDescriptor;
244import java.io.FileNotFoundException;
245import java.io.FileOutputStream;
246import java.io.FileReader;
247import java.io.FilenameFilter;
248import java.io.IOException;
249import java.io.InputStream;
250import java.io.PrintWriter;
251import java.nio.charset.StandardCharsets;
252import java.security.NoSuchAlgorithmException;
253import java.security.PublicKey;
254import java.security.cert.CertificateEncodingException;
255import java.security.cert.CertificateException;
256import java.text.SimpleDateFormat;
257import java.util.ArrayList;
258import java.util.Arrays;
259import java.util.Collection;
260import java.util.Collections;
261import java.util.Comparator;
262import java.util.Date;
263import java.util.Iterator;
264import java.util.List;
265import java.util.Map;
266import java.util.Objects;
267import java.util.Set;
268import java.util.concurrent.CountDownLatch;
269import java.util.concurrent.TimeUnit;
270import java.util.concurrent.atomic.AtomicBoolean;
271import java.util.concurrent.atomic.AtomicInteger;
272import java.util.concurrent.atomic.AtomicLong;
273
274/**
275 * Keep track of all those .apks everywhere.
276 *
277 * This is very central to the platform's security; please run the unit
278 * tests whenever making modifications here:
279 *
280runtest -c android.content.pm.PackageManagerTests frameworks-core
281 *
282 * {@hide}
283 */
284public class PackageManagerService extends IPackageManager.Stub {
285    static final String TAG = "PackageManager";
286    static final boolean DEBUG_SETTINGS = false;
287    static final boolean DEBUG_PREFERRED = false;
288    static final boolean DEBUG_UPGRADE = false;
289    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
290    private static final boolean DEBUG_BACKUP = false;
291    private static final boolean DEBUG_INSTALL = false;
292    private static final boolean DEBUG_REMOVE = false;
293    private static final boolean DEBUG_BROADCASTS = false;
294    private static final boolean DEBUG_SHOW_INFO = false;
295    private static final boolean DEBUG_PACKAGE_INFO = false;
296    private static final boolean DEBUG_INTENT_MATCHING = false;
297    private static final boolean DEBUG_PACKAGE_SCANNING = false;
298    private static final boolean DEBUG_VERIFY = false;
299    private static final boolean DEBUG_DEXOPT = false;
300    private static final boolean DEBUG_ABI_SELECTION = false;
301
302    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
303
304    private static final int RADIO_UID = Process.PHONE_UID;
305    private static final int LOG_UID = Process.LOG_UID;
306    private static final int NFC_UID = Process.NFC_UID;
307    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
308    private static final int SHELL_UID = Process.SHELL_UID;
309
310    // Cap the size of permission trees that 3rd party apps can define
311    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
312
313    // Suffix used during package installation when copying/moving
314    // package apks to install directory.
315    private static final String INSTALL_PACKAGE_SUFFIX = "-";
316
317    static final int SCAN_NO_DEX = 1<<1;
318    static final int SCAN_FORCE_DEX = 1<<2;
319    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
320    static final int SCAN_NEW_INSTALL = 1<<4;
321    static final int SCAN_NO_PATHS = 1<<5;
322    static final int SCAN_UPDATE_TIME = 1<<6;
323    static final int SCAN_DEFER_DEX = 1<<7;
324    static final int SCAN_BOOTING = 1<<8;
325    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
326    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
327    static final int SCAN_REPLACING = 1<<11;
328    static final int SCAN_REQUIRE_KNOWN = 1<<12;
329    static final int SCAN_MOVE = 1<<13;
330    static final int SCAN_INITIAL = 1<<14;
331
332    static final int REMOVE_CHATTY = 1<<16;
333
334    private static final int[] EMPTY_INT_ARRAY = new int[0];
335
336    /**
337     * Timeout (in milliseconds) after which the watchdog should declare that
338     * our handler thread is wedged.  The usual default for such things is one
339     * minute but we sometimes do very lengthy I/O operations on this thread,
340     * such as installing multi-gigabyte applications, so ours needs to be longer.
341     */
342    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
343
344    /**
345     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
346     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
347     * settings entry if available, otherwise we use the hardcoded default.  If it's been
348     * more than this long since the last fstrim, we force one during the boot sequence.
349     *
350     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
351     * one gets run at the next available charging+idle time.  This final mandatory
352     * no-fstrim check kicks in only of the other scheduling criteria is never met.
353     */
354    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
355
356    /**
357     * Whether verification is enabled by default.
358     */
359    private static final boolean DEFAULT_VERIFY_ENABLE = true;
360
361    /**
362     * The default maximum time to wait for the verification agent to return in
363     * milliseconds.
364     */
365    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
366
367    /**
368     * The default response for package verification timeout.
369     *
370     * This can be either PackageManager.VERIFICATION_ALLOW or
371     * PackageManager.VERIFICATION_REJECT.
372     */
373    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
374
375    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
376
377    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
378            DEFAULT_CONTAINER_PACKAGE,
379            "com.android.defcontainer.DefaultContainerService");
380
381    private static final String KILL_APP_REASON_GIDS_CHANGED =
382            "permission grant or revoke changed gids";
383
384    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
385            "permissions revoked";
386
387    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
388
389    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
390
391    /** Permission grant: not grant the permission. */
392    private static final int GRANT_DENIED = 1;
393
394    /** Permission grant: grant the permission as an install permission. */
395    private static final int GRANT_INSTALL = 2;
396
397    /** Permission grant: grant the permission as an install permission for a legacy app. */
398    private static final int GRANT_INSTALL_LEGACY = 3;
399
400    /** Permission grant: grant the permission as a runtime one. */
401    private static final int GRANT_RUNTIME = 4;
402
403    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
404    private static final int GRANT_UPGRADE = 5;
405
406    /** Canonical intent used to identify what counts as a "web browser" app */
407    private static final Intent sBrowserIntent;
408    static {
409        sBrowserIntent = new Intent();
410        sBrowserIntent.setAction(Intent.ACTION_VIEW);
411        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
412        sBrowserIntent.setData(Uri.parse("http:"));
413    }
414
415    final ServiceThread mHandlerThread;
416
417    final PackageHandler mHandler;
418
419    /**
420     * Messages for {@link #mHandler} that need to wait for system ready before
421     * being dispatched.
422     */
423    private ArrayList<Message> mPostSystemReadyMessages;
424
425    final int mSdkVersion = Build.VERSION.SDK_INT;
426
427    final Context mContext;
428    final boolean mFactoryTest;
429    final boolean mOnlyCore;
430    final boolean mLazyDexOpt;
431    final long mDexOptLRUThresholdInMills;
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.OWNER)) {
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                        try {
1150                            Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindMCS",
1151                                    System.identityHashCode(params));
1152                            // If this is the only one pending we might
1153                            // have to bind to the service again.
1154                            if (!connectToService()) {
1155                                Slog.e(TAG, "Failed to bind to media container service");
1156                                params.serviceError();
1157                                return;
1158                            } else {
1159                                // Once we bind to the service, the first
1160                                // pending request will be processed.
1161                                mPendingInstalls.add(idx, params);
1162                            }
1163                        } finally {
1164                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindMCS",
1165                                    System.identityHashCode(params));
1166                        }
1167                    } else {
1168                        mPendingInstalls.add(idx, params);
1169                        // Already bound to the service. Just make
1170                        // sure we trigger off processing the first request.
1171                        if (idx == 0) {
1172                            mHandler.sendEmptyMessage(MCS_BOUND);
1173                        }
1174                    }
1175                    break;
1176                }
1177                case MCS_BOUND: {
1178                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1179                    if (msg.obj != null) {
1180                        mContainerService = (IMediaContainerService) msg.obj;
1181                    }
1182                    if (mContainerService == null) {
1183                        if (!mBound) {
1184                            // Something seriously wrong since we are not bound and we are not
1185                            // waiting for connection. Bail out.
1186                            Slog.e(TAG, "Cannot bind to media container service");
1187                            for (HandlerParams params : mPendingInstalls) {
1188                                // Indicate service bind error
1189                                params.serviceError();
1190                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1191                                        System.identityHashCode(params));
1192                            }
1193                            mPendingInstalls.clear();
1194                        } else {
1195                            Slog.w(TAG, "Waiting to connect to media container service");
1196                        }
1197                    } else if (mPendingInstalls.size() > 0) {
1198                        HandlerParams params = mPendingInstalls.get(0);
1199                        if (params != null) {
1200                            if (params.startCopy()) {
1201                                // We are done...  look for more work or to
1202                                // go idle.
1203                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                        "Checking for more work or unbind...");
1205                                // Delete pending install
1206                                if (mPendingInstalls.size() > 0) {
1207                                    mPendingInstalls.remove(0);
1208                                }
1209                                if (mPendingInstalls.size() == 0) {
1210                                    if (mBound) {
1211                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1212                                                "Posting delayed MCS_UNBIND");
1213                                        removeMessages(MCS_UNBIND);
1214                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1215                                        // Unbind after a little delay, to avoid
1216                                        // continual thrashing.
1217                                        sendMessageDelayed(ubmsg, 10000);
1218                                    }
1219                                } else {
1220                                    // There are more pending requests in queue.
1221                                    // Just post MCS_BOUND message to trigger processing
1222                                    // of next pending install.
1223                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1224                                            "Posting MCS_BOUND for next work");
1225                                    mHandler.sendEmptyMessage(MCS_BOUND);
1226                                }
1227                            }
1228                        }
1229                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1230                                System.identityHashCode(params));
1231                    } else {
1232                        // Should never happen ideally.
1233                        Slog.w(TAG, "Empty queue");
1234                    }
1235                    break;
1236                }
1237                case MCS_RECONNECT: {
1238                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1239                    if (mPendingInstalls.size() > 0) {
1240                        if (mBound) {
1241                            disconnectService();
1242                        }
1243                        if (!connectToService()) {
1244                            Slog.e(TAG, "Failed to bind to media container service");
1245                            for (HandlerParams params : mPendingInstalls) {
1246                                // Indicate service bind error
1247                                params.serviceError();
1248                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1249                                        System.identityHashCode(params));
1250                            }
1251                            mPendingInstalls.clear();
1252                        }
1253                    }
1254                    break;
1255                }
1256                case MCS_UNBIND: {
1257                    // If there is no actual work left, then time to unbind.
1258                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1259
1260                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1261                        if (mBound) {
1262                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1263
1264                            disconnectService();
1265                        }
1266                    } else if (mPendingInstalls.size() > 0) {
1267                        // There are more pending requests in queue.
1268                        // Just post MCS_BOUND message to trigger processing
1269                        // of next pending install.
1270                        mHandler.sendEmptyMessage(MCS_BOUND);
1271                    }
1272
1273                    break;
1274                }
1275                case MCS_GIVE_UP: {
1276                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1277                    HandlerParams params = mPendingInstalls.remove(0);
1278                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1279                            System.identityHashCode(params));
1280                    break;
1281                }
1282                case SEND_PENDING_BROADCAST: {
1283                    String packages[];
1284                    ArrayList<String> components[];
1285                    int size = 0;
1286                    int uids[];
1287                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1288                    synchronized (mPackages) {
1289                        if (mPendingBroadcasts == null) {
1290                            return;
1291                        }
1292                        size = mPendingBroadcasts.size();
1293                        if (size <= 0) {
1294                            // Nothing to be done. Just return
1295                            return;
1296                        }
1297                        packages = new String[size];
1298                        components = new ArrayList[size];
1299                        uids = new int[size];
1300                        int i = 0;  // filling out the above arrays
1301
1302                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1303                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1304                            Iterator<Map.Entry<String, ArrayList<String>>> it
1305                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1306                                            .entrySet().iterator();
1307                            while (it.hasNext() && i < size) {
1308                                Map.Entry<String, ArrayList<String>> ent = it.next();
1309                                packages[i] = ent.getKey();
1310                                components[i] = ent.getValue();
1311                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1312                                uids[i] = (ps != null)
1313                                        ? UserHandle.getUid(packageUserId, ps.appId)
1314                                        : -1;
1315                                i++;
1316                            }
1317                        }
1318                        size = i;
1319                        mPendingBroadcasts.clear();
1320                    }
1321                    // Send broadcasts
1322                    for (int i = 0; i < size; i++) {
1323                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1324                    }
1325                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1326                    break;
1327                }
1328                case START_CLEANING_PACKAGE: {
1329                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330                    final String packageName = (String)msg.obj;
1331                    final int userId = msg.arg1;
1332                    final boolean andCode = msg.arg2 != 0;
1333                    synchronized (mPackages) {
1334                        if (userId == UserHandle.USER_ALL) {
1335                            int[] users = sUserManager.getUserIds();
1336                            for (int user : users) {
1337                                mSettings.addPackageToCleanLPw(
1338                                        new PackageCleanItem(user, packageName, andCode));
1339                            }
1340                        } else {
1341                            mSettings.addPackageToCleanLPw(
1342                                    new PackageCleanItem(userId, packageName, andCode));
1343                        }
1344                    }
1345                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1346                    startCleaningPackages();
1347                } break;
1348                case POST_INSTALL: {
1349                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1350                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1351                    mRunningInstalls.delete(msg.arg1);
1352                    boolean deleteOld = false;
1353
1354                    if (data != null) {
1355                        InstallArgs args = data.args;
1356                        PackageInstalledInfo res = data.res;
1357
1358                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1359                            final String packageName = res.pkg.applicationInfo.packageName;
1360                            res.removedInfo.sendBroadcast(false, true, false);
1361                            Bundle extras = new Bundle(1);
1362                            extras.putInt(Intent.EXTRA_UID, res.uid);
1363
1364                            // Now that we successfully installed the package, grant runtime
1365                            // permissions if requested before broadcasting the install.
1366                            if ((args.installFlags
1367                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1368                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1369                                        args.installGrantPermissions);
1370                            }
1371
1372                            // Determine the set of users who are adding this
1373                            // package for the first time vs. those who are seeing
1374                            // an update.
1375                            int[] firstUsers;
1376                            int[] updateUsers = new int[0];
1377                            if (res.origUsers == null || res.origUsers.length == 0) {
1378                                firstUsers = res.newUsers;
1379                            } else {
1380                                firstUsers = new int[0];
1381                                for (int i=0; i<res.newUsers.length; i++) {
1382                                    int user = res.newUsers[i];
1383                                    boolean isNew = true;
1384                                    for (int j=0; j<res.origUsers.length; j++) {
1385                                        if (res.origUsers[j] == user) {
1386                                            isNew = false;
1387                                            break;
1388                                        }
1389                                    }
1390                                    if (isNew) {
1391                                        int[] newFirst = new int[firstUsers.length+1];
1392                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1393                                                firstUsers.length);
1394                                        newFirst[firstUsers.length] = user;
1395                                        firstUsers = newFirst;
1396                                    } else {
1397                                        int[] newUpdate = new int[updateUsers.length+1];
1398                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1399                                                updateUsers.length);
1400                                        newUpdate[updateUsers.length] = user;
1401                                        updateUsers = newUpdate;
1402                                    }
1403                                }
1404                            }
1405                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1406                                    packageName, extras, null, null, firstUsers);
1407                            final boolean update = res.removedInfo.removedPackage != null;
1408                            if (update) {
1409                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1410                            }
1411                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1412                                    packageName, extras, null, null, updateUsers);
1413                            if (update) {
1414                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1415                                        packageName, extras, null, null, updateUsers);
1416                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1417                                        null, null, packageName, null, updateUsers);
1418
1419                                // treat asec-hosted packages like removable media on upgrade
1420                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1421                                    if (DEBUG_INSTALL) {
1422                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1423                                                + " is ASEC-hosted -> AVAILABLE");
1424                                    }
1425                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1426                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1427                                    pkgList.add(packageName);
1428                                    sendResourcesChangedBroadcast(true, true,
1429                                            pkgList,uidArray, null);
1430                                }
1431                            }
1432                            if (res.removedInfo.args != null) {
1433                                // Remove the replaced package's older resources safely now
1434                                deleteOld = true;
1435                            }
1436
1437                            // If this app is a browser and it's newly-installed for some
1438                            // users, clear any default-browser state in those users
1439                            if (firstUsers.length > 0) {
1440                                // the app's nature doesn't depend on the user, so we can just
1441                                // check its browser nature in any user and generalize.
1442                                if (packageIsBrowser(packageName, firstUsers[0])) {
1443                                    synchronized (mPackages) {
1444                                        for (int userId : firstUsers) {
1445                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1446                                        }
1447                                    }
1448                                }
1449                            }
1450                            // Log current value of "unknown sources" setting
1451                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1452                                getUnknownSourcesSettings());
1453                        }
1454                        // Force a gc to clear up things
1455                        Runtime.getRuntime().gc();
1456                        // We delete after a gc for applications  on sdcard.
1457                        if (deleteOld) {
1458                            synchronized (mInstallLock) {
1459                                res.removedInfo.args.doPostDeleteLI(true);
1460                            }
1461                        }
1462                        if (args.observer != null) {
1463                            try {
1464                                Bundle extras = extrasForInstallResult(res);
1465                                args.observer.onPackageInstalled(res.name, res.returnCode,
1466                                        res.returnMsg, extras);
1467                            } catch (RemoteException e) {
1468                                Slog.i(TAG, "Observer no longer exists.");
1469                            }
1470                        }
1471                    } else {
1472                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1473                    }
1474
1475                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1476                } break;
1477                case UPDATED_MEDIA_STATUS: {
1478                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1479                    boolean reportStatus = msg.arg1 == 1;
1480                    boolean doGc = msg.arg2 == 1;
1481                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1482                    if (doGc) {
1483                        // Force a gc to clear up stale containers.
1484                        Runtime.getRuntime().gc();
1485                    }
1486                    if (msg.obj != null) {
1487                        @SuppressWarnings("unchecked")
1488                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1489                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1490                        // Unload containers
1491                        unloadAllContainers(args);
1492                    }
1493                    if (reportStatus) {
1494                        try {
1495                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1496                            PackageHelper.getMountService().finishMediaUpdate();
1497                        } catch (RemoteException e) {
1498                            Log.e(TAG, "MountService not running?");
1499                        }
1500                    }
1501                } break;
1502                case WRITE_SETTINGS: {
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1504                    synchronized (mPackages) {
1505                        removeMessages(WRITE_SETTINGS);
1506                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1507                        mSettings.writeLPr();
1508                        mDirtyUsers.clear();
1509                    }
1510                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1511                } break;
1512                case WRITE_PACKAGE_RESTRICTIONS: {
1513                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1514                    synchronized (mPackages) {
1515                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1516                        for (int userId : mDirtyUsers) {
1517                            mSettings.writePackageRestrictionsLPr(userId);
1518                        }
1519                        mDirtyUsers.clear();
1520                    }
1521                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1522                } break;
1523                case CHECK_PENDING_VERIFICATION: {
1524                    final int verificationId = msg.arg1;
1525                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1526
1527                    if ((state != null) && !state.timeoutExtended()) {
1528                        final InstallArgs args = state.getInstallArgs();
1529                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1530
1531                        Slog.i(TAG, "Verification timed out for " + originUri);
1532                        mPendingVerification.remove(verificationId);
1533
1534                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1535
1536                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1537                            Slog.i(TAG, "Continuing with installation of " + originUri);
1538                            state.setVerifierResponse(Binder.getCallingUid(),
1539                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1540                            broadcastPackageVerified(verificationId, originUri,
1541                                    PackageManager.VERIFICATION_ALLOW,
1542                                    state.getInstallArgs().getUser());
1543                            try {
1544                                ret = args.copyApk(mContainerService, true);
1545                            } catch (RemoteException e) {
1546                                Slog.e(TAG, "Could not contact the ContainerService");
1547                            }
1548                        } else {
1549                            broadcastPackageVerified(verificationId, originUri,
1550                                    PackageManager.VERIFICATION_REJECT,
1551                                    state.getInstallArgs().getUser());
1552                        }
1553
1554                        processPendingInstall(args, ret);
1555                        mHandler.sendEmptyMessage(MCS_UNBIND);
1556                    }
1557                    Trace.asyncTraceEnd(
1558                            TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId);
1559                    break;
1560                }
1561                case PACKAGE_VERIFIED: {
1562                    final int verificationId = msg.arg1;
1563
1564                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1565                    if (state == null) {
1566                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1567                        break;
1568                    }
1569
1570                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1571
1572                    state.setVerifierResponse(response.callerUid, response.code);
1573
1574                    if (state.isVerificationComplete()) {
1575                        mPendingVerification.remove(verificationId);
1576
1577                        final InstallArgs args = state.getInstallArgs();
1578                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1579
1580                        int ret;
1581                        if (state.isInstallAllowed()) {
1582                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1583                            broadcastPackageVerified(verificationId, originUri,
1584                                    response.code, state.getInstallArgs().getUser());
1585                            try {
1586                                ret = args.copyApk(mContainerService, true);
1587                            } catch (RemoteException e) {
1588                                Slog.e(TAG, "Could not contact the ContainerService");
1589                            }
1590                        } else {
1591                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1592                        }
1593
1594                        processPendingInstall(args, ret);
1595
1596                        mHandler.sendEmptyMessage(MCS_UNBIND);
1597                    }
1598
1599                    break;
1600                }
1601                case START_INTENT_FILTER_VERIFICATIONS: {
1602                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1603                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1604                            params.replacing, params.pkg);
1605                    break;
1606                }
1607                case INTENT_FILTER_VERIFIED: {
1608                    final int verificationId = msg.arg1;
1609
1610                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1611                            verificationId);
1612                    if (state == null) {
1613                        Slog.w(TAG, "Invalid IntentFilter verification token "
1614                                + verificationId + " received");
1615                        break;
1616                    }
1617
1618                    final int userId = state.getUserId();
1619
1620                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1621                            "Processing IntentFilter verification with token:"
1622                            + verificationId + " and userId:" + userId);
1623
1624                    final IntentFilterVerificationResponse response =
1625                            (IntentFilterVerificationResponse) msg.obj;
1626
1627                    state.setVerifierResponse(response.callerUid, response.code);
1628
1629                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1630                            "IntentFilter verification with token:" + verificationId
1631                            + " and userId:" + userId
1632                            + " is settings verifier response with response code:"
1633                            + response.code);
1634
1635                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1636                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1637                                + response.getFailedDomainsString());
1638                    }
1639
1640                    if (state.isVerificationComplete()) {
1641                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1642                    } else {
1643                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1644                                "IntentFilter verification with token:" + verificationId
1645                                + " was not said to be complete");
1646                    }
1647
1648                    break;
1649                }
1650            }
1651        }
1652    }
1653
1654    private StorageEventListener mStorageListener = new StorageEventListener() {
1655        @Override
1656        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1657            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1658                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1659                    final String volumeUuid = vol.getFsUuid();
1660
1661                    // Clean up any users or apps that were removed or recreated
1662                    // while this volume was missing
1663                    reconcileUsers(volumeUuid);
1664                    reconcileApps(volumeUuid);
1665
1666                    // Clean up any install sessions that expired or were
1667                    // cancelled while this volume was missing
1668                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1669
1670                    loadPrivatePackages(vol);
1671
1672                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1673                    unloadPrivatePackages(vol);
1674                }
1675            }
1676
1677            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1678                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1679                    updateExternalMediaStatus(true, false);
1680                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1681                    updateExternalMediaStatus(false, false);
1682                }
1683            }
1684        }
1685
1686        @Override
1687        public void onVolumeForgotten(String fsUuid) {
1688            if (TextUtils.isEmpty(fsUuid)) {
1689                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1690                return;
1691            }
1692
1693            // Remove any apps installed on the forgotten volume
1694            synchronized (mPackages) {
1695                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1696                for (PackageSetting ps : packages) {
1697                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1698                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1699                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1700                }
1701
1702                mSettings.onVolumeForgotten(fsUuid);
1703                mSettings.writeLPr();
1704            }
1705        }
1706    };
1707
1708    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1709            String[] grantedPermissions) {
1710        if (userId >= UserHandle.USER_OWNER) {
1711            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1712        } else if (userId == UserHandle.USER_ALL) {
1713            final int[] userIds;
1714            synchronized (mPackages) {
1715                userIds = UserManagerService.getInstance().getUserIds();
1716            }
1717            for (int someUserId : userIds) {
1718                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1719            }
1720        }
1721
1722        // We could have touched GID membership, so flush out packages.list
1723        synchronized (mPackages) {
1724            mSettings.writePackageListLPr();
1725        }
1726    }
1727
1728    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1729            String[] grantedPermissions) {
1730        SettingBase sb = (SettingBase) pkg.mExtras;
1731        if (sb == null) {
1732            return;
1733        }
1734
1735        PermissionsState permissionsState = sb.getPermissionsState();
1736
1737        for (String permission : pkg.requestedPermissions) {
1738            BasePermission bp = mSettings.mPermissions.get(permission);
1739            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1740                    || ArrayUtils.contains(grantedPermissions, permission))) {
1741                permissionsState.grantRuntimePermission(bp, userId);
1742            }
1743        }
1744    }
1745
1746    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1747        Bundle extras = null;
1748        switch (res.returnCode) {
1749            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1750                extras = new Bundle();
1751                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1752                        res.origPermission);
1753                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1754                        res.origPackage);
1755                break;
1756            }
1757            case PackageManager.INSTALL_SUCCEEDED: {
1758                extras = new Bundle();
1759                extras.putBoolean(Intent.EXTRA_REPLACING,
1760                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1761                break;
1762            }
1763        }
1764        return extras;
1765    }
1766
1767    void scheduleWriteSettingsLocked() {
1768        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1769            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1770        }
1771    }
1772
1773    void scheduleWritePackageRestrictionsLocked(int userId) {
1774        if (!sUserManager.exists(userId)) return;
1775        mDirtyUsers.add(userId);
1776        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1777            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1778        }
1779    }
1780
1781    public static PackageManagerService main(Context context, Installer installer,
1782            boolean factoryTest, boolean onlyCore) {
1783        PackageManagerService m = new PackageManagerService(context, installer,
1784                factoryTest, onlyCore);
1785        ServiceManager.addService("package", m);
1786        return m;
1787    }
1788
1789    static String[] splitString(String str, char sep) {
1790        int count = 1;
1791        int i = 0;
1792        while ((i=str.indexOf(sep, i)) >= 0) {
1793            count++;
1794            i++;
1795        }
1796
1797        String[] res = new String[count];
1798        i=0;
1799        count = 0;
1800        int lastI=0;
1801        while ((i=str.indexOf(sep, i)) >= 0) {
1802            res[count] = str.substring(lastI, i);
1803            count++;
1804            i++;
1805            lastI = i;
1806        }
1807        res[count] = str.substring(lastI, str.length());
1808        return res;
1809    }
1810
1811    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1812        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1813                Context.DISPLAY_SERVICE);
1814        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1815    }
1816
1817    public PackageManagerService(Context context, Installer installer,
1818            boolean factoryTest, boolean onlyCore) {
1819        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1820                SystemClock.uptimeMillis());
1821
1822        if (mSdkVersion <= 0) {
1823            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1824        }
1825
1826        mContext = context;
1827        mFactoryTest = factoryTest;
1828        mOnlyCore = onlyCore;
1829        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1830        mMetrics = new DisplayMetrics();
1831        mSettings = new Settings(mPackages);
1832        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1833                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1834        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1835                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1836        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1837                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1838        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1839                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1840        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1841                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1842        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1843                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1844
1845        // TODO: add a property to control this?
1846        long dexOptLRUThresholdInMinutes;
1847        if (mLazyDexOpt) {
1848            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1849        } else {
1850            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1851        }
1852        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1853
1854        String separateProcesses = SystemProperties.get("debug.separate_processes");
1855        if (separateProcesses != null && separateProcesses.length() > 0) {
1856            if ("*".equals(separateProcesses)) {
1857                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1858                mSeparateProcesses = null;
1859                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1860            } else {
1861                mDefParseFlags = 0;
1862                mSeparateProcesses = separateProcesses.split(",");
1863                Slog.w(TAG, "Running with debug.separate_processes: "
1864                        + separateProcesses);
1865            }
1866        } else {
1867            mDefParseFlags = 0;
1868            mSeparateProcesses = null;
1869        }
1870
1871        mInstaller = installer;
1872        mPackageDexOptimizer = new PackageDexOptimizer(this);
1873        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1874
1875        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1876                FgThread.get().getLooper());
1877
1878        getDefaultDisplayMetrics(context, mMetrics);
1879
1880        SystemConfig systemConfig = SystemConfig.getInstance();
1881        mGlobalGids = systemConfig.getGlobalGids();
1882        mSystemPermissions = systemConfig.getSystemPermissions();
1883        mAvailableFeatures = systemConfig.getAvailableFeatures();
1884
1885        synchronized (mInstallLock) {
1886        // writer
1887        synchronized (mPackages) {
1888            mHandlerThread = new ServiceThread(TAG,
1889                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1890            mHandlerThread.start();
1891            mHandler = new PackageHandler(mHandlerThread.getLooper());
1892            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1893
1894            File dataDir = Environment.getDataDirectory();
1895            mAppDataDir = new File(dataDir, "data");
1896            mAppInstallDir = new File(dataDir, "app");
1897            mAppLib32InstallDir = new File(dataDir, "app-lib");
1898            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1899            mUserAppDataDir = new File(dataDir, "user");
1900            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1901
1902            sUserManager = new UserManagerService(context, this,
1903                    mInstallLock, mPackages);
1904
1905            // Propagate permission configuration in to package manager.
1906            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1907                    = systemConfig.getPermissions();
1908            for (int i=0; i<permConfig.size(); i++) {
1909                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1910                BasePermission bp = mSettings.mPermissions.get(perm.name);
1911                if (bp == null) {
1912                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1913                    mSettings.mPermissions.put(perm.name, bp);
1914                }
1915                if (perm.gids != null) {
1916                    bp.setGids(perm.gids, perm.perUser);
1917                }
1918            }
1919
1920            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1921            for (int i=0; i<libConfig.size(); i++) {
1922                mSharedLibraries.put(libConfig.keyAt(i),
1923                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1924            }
1925
1926            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1927
1928            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1929                    mSdkVersion, mOnlyCore);
1930
1931            String customResolverActivity = Resources.getSystem().getString(
1932                    R.string.config_customResolverActivity);
1933            if (TextUtils.isEmpty(customResolverActivity)) {
1934                customResolverActivity = null;
1935            } else {
1936                mCustomResolverComponentName = ComponentName.unflattenFromString(
1937                        customResolverActivity);
1938            }
1939
1940            long startTime = SystemClock.uptimeMillis();
1941
1942            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1943                    startTime);
1944
1945            // Set flag to monitor and not change apk file paths when
1946            // scanning install directories.
1947            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1948
1949            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1950
1951            /**
1952             * Add everything in the in the boot class path to the
1953             * list of process files because dexopt will have been run
1954             * if necessary during zygote startup.
1955             */
1956            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1957            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1958
1959            if (bootClassPath != null) {
1960                String[] bootClassPathElements = splitString(bootClassPath, ':');
1961                for (String element : bootClassPathElements) {
1962                    alreadyDexOpted.add(element);
1963                }
1964            } else {
1965                Slog.w(TAG, "No BOOTCLASSPATH found!");
1966            }
1967
1968            if (systemServerClassPath != null) {
1969                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1970                for (String element : systemServerClassPathElements) {
1971                    alreadyDexOpted.add(element);
1972                }
1973            } else {
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                                alreadyDexOpted.add(lib);
2001                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
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            // Gross hack for now: we know this file doesn't contain any
2016            // code, so don't dexopt it to avoid the resulting log spew.
2017            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2018
2019            // Gross hack for now: we know this file is only part of
2020            // the boot class path for art, so don't dexopt it to
2021            // avoid the resulting log spew.
2022            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2023
2024            /**
2025             * There are a number of commands implemented in Java, which
2026             * we currently need to do the dexopt on so that they can be
2027             * run from a non-root shell.
2028             */
2029            String[] frameworkFiles = frameworkDir.list();
2030            if (frameworkFiles != null) {
2031                // TODO: We could compile these only for the most preferred ABI. We should
2032                // first double check that the dex files for these commands are not referenced
2033                // by other system apps.
2034                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2035                    for (int i=0; i<frameworkFiles.length; i++) {
2036                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2037                        String path = libPath.getPath();
2038                        // Skip the file if we already did it.
2039                        if (alreadyDexOpted.contains(path)) {
2040                            continue;
2041                        }
2042                        // Skip the file if it is not a type we want to dexopt.
2043                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2044                            continue;
2045                        }
2046                        try {
2047                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2048                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2049                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2050                            }
2051                        } catch (FileNotFoundException e) {
2052                            Slog.w(TAG, "Jar not found: " + path);
2053                        } catch (IOException e) {
2054                            Slog.w(TAG, "Exception reading jar: " + path, e);
2055                        }
2056                    }
2057                }
2058            }
2059
2060            final VersionInfo ver = mSettings.getInternalVersion();
2061            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2062            // when upgrading from pre-M, promote system app permissions from install to runtime
2063            mPromoteSystemApps =
2064                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2065
2066            // save off the names of pre-existing system packages prior to scanning; we don't
2067            // want to automatically grant runtime permissions for new system apps
2068            if (mPromoteSystemApps) {
2069                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2070                while (pkgSettingIter.hasNext()) {
2071                    PackageSetting ps = pkgSettingIter.next();
2072                    if (isSystemApp(ps)) {
2073                        mExistingSystemPackages.add(ps.name);
2074                    }
2075                }
2076            }
2077
2078            // Collect vendor overlay packages.
2079            // (Do this before scanning any apps.)
2080            // For security and version matching reason, only consider
2081            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2082            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2083            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2084                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2085
2086            // Find base frameworks (resource packages without code).
2087            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2088                    | PackageParser.PARSE_IS_SYSTEM_DIR
2089                    | PackageParser.PARSE_IS_PRIVILEGED,
2090                    scanFlags | SCAN_NO_DEX, 0);
2091
2092            // Collected privileged system packages.
2093            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2094            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2095                    | PackageParser.PARSE_IS_SYSTEM_DIR
2096                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2097
2098            // Collect ordinary system packages.
2099            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2100            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2101                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2102
2103            // Collect all vendor packages.
2104            File vendorAppDir = new File("/vendor/app");
2105            try {
2106                vendorAppDir = vendorAppDir.getCanonicalFile();
2107            } catch (IOException e) {
2108                // failed to look up canonical path, continue with original one
2109            }
2110            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2111                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2112
2113            // Collect all OEM packages.
2114            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2115            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2116                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2117
2118            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2119            mInstaller.moveFiles();
2120
2121            // Prune any system packages that no longer exist.
2122            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2123            if (!mOnlyCore) {
2124                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2125                while (psit.hasNext()) {
2126                    PackageSetting ps = psit.next();
2127
2128                    /*
2129                     * If this is not a system app, it can't be a
2130                     * disable system app.
2131                     */
2132                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2133                        continue;
2134                    }
2135
2136                    /*
2137                     * If the package is scanned, it's not erased.
2138                     */
2139                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2140                    if (scannedPkg != null) {
2141                        /*
2142                         * If the system app is both scanned and in the
2143                         * disabled packages list, then it must have been
2144                         * added via OTA. Remove it from the currently
2145                         * scanned package so the previously user-installed
2146                         * application can be scanned.
2147                         */
2148                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2149                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2150                                    + ps.name + "; removing system app.  Last known codePath="
2151                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2152                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2153                                    + scannedPkg.mVersionCode);
2154                            removePackageLI(ps, true);
2155                            mExpectingBetter.put(ps.name, ps.codePath);
2156                        }
2157
2158                        continue;
2159                    }
2160
2161                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2162                        psit.remove();
2163                        logCriticalInfo(Log.WARN, "System package " + ps.name
2164                                + " no longer exists; wiping its data");
2165                        removeDataDirsLI(null, ps.name);
2166                    } else {
2167                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2168                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2169                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2170                        }
2171                    }
2172                }
2173            }
2174
2175            //look for any incomplete package installations
2176            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2177            //clean up list
2178            for(int i = 0; i < deletePkgsList.size(); i++) {
2179                //clean up here
2180                cleanupInstallFailedPackage(deletePkgsList.get(i));
2181            }
2182            //delete tmp files
2183            deleteTempPackageFiles();
2184
2185            // Remove any shared userIDs that have no associated packages
2186            mSettings.pruneSharedUsersLPw();
2187
2188            if (!mOnlyCore) {
2189                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2190                        SystemClock.uptimeMillis());
2191                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2192
2193                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2194                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2195
2196                /**
2197                 * Remove disable package settings for any updated system
2198                 * apps that were removed via an OTA. If they're not a
2199                 * previously-updated app, remove them completely.
2200                 * Otherwise, just revoke their system-level permissions.
2201                 */
2202                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2203                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2204                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2205
2206                    String msg;
2207                    if (deletedPkg == null) {
2208                        msg = "Updated system package " + deletedAppName
2209                                + " no longer exists; wiping its data";
2210                        removeDataDirsLI(null, deletedAppName);
2211                    } else {
2212                        msg = "Updated system app + " + deletedAppName
2213                                + " no longer present; removing system privileges for "
2214                                + deletedAppName;
2215
2216                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2217
2218                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2219                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2220                    }
2221                    logCriticalInfo(Log.WARN, msg);
2222                }
2223
2224                /**
2225                 * Make sure all system apps that we expected to appear on
2226                 * the userdata partition actually showed up. If they never
2227                 * appeared, crawl back and revive the system version.
2228                 */
2229                for (int i = 0; i < mExpectingBetter.size(); i++) {
2230                    final String packageName = mExpectingBetter.keyAt(i);
2231                    if (!mPackages.containsKey(packageName)) {
2232                        final File scanFile = mExpectingBetter.valueAt(i);
2233
2234                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2235                                + " but never showed up; reverting to system");
2236
2237                        final int reparseFlags;
2238                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2239                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2240                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2241                                    | PackageParser.PARSE_IS_PRIVILEGED;
2242                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2243                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2244                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2245                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2246                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2247                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2248                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2249                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2250                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2251                        } else {
2252                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2253                            continue;
2254                        }
2255
2256                        mSettings.enableSystemPackageLPw(packageName);
2257
2258                        try {
2259                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2260                        } catch (PackageManagerException e) {
2261                            Slog.e(TAG, "Failed to parse original system package: "
2262                                    + e.getMessage());
2263                        }
2264                    }
2265                }
2266            }
2267            mExpectingBetter.clear();
2268
2269            // Now that we know all of the shared libraries, update all clients to have
2270            // the correct library paths.
2271            updateAllSharedLibrariesLPw();
2272
2273            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2274                // NOTE: We ignore potential failures here during a system scan (like
2275                // the rest of the commands above) because there's precious little we
2276                // can do about it. A settings error is reported, though.
2277                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2278                        false /* force dexopt */, false /* defer dexopt */);
2279            }
2280
2281            // Now that we know all the packages we are keeping,
2282            // read and update their last usage times.
2283            mPackageUsage.readLP();
2284
2285            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2286                    SystemClock.uptimeMillis());
2287            Slog.i(TAG, "Time to scan packages: "
2288                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2289                    + " seconds");
2290
2291            // If the platform SDK has changed since the last time we booted,
2292            // we need to re-grant app permission to catch any new ones that
2293            // appear.  This is really a hack, and means that apps can in some
2294            // cases get permissions that the user didn't initially explicitly
2295            // allow...  it would be nice to have some better way to handle
2296            // this situation.
2297            int updateFlags = UPDATE_PERMISSIONS_ALL;
2298            if (ver.sdkVersion != mSdkVersion) {
2299                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2300                        + mSdkVersion + "; regranting permissions for internal storage");
2301                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2302            }
2303            updatePermissionsLPw(null, null, updateFlags);
2304            ver.sdkVersion = mSdkVersion;
2305            // clear only after permissions have been updated
2306            mExistingSystemPackages.clear();
2307            mPromoteSystemApps = false;
2308
2309            // If this is the first boot, and it is a normal boot, then
2310            // we need to initialize the default preferred apps.
2311            if (!mRestoredSettings && !onlyCore) {
2312                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2313                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2314                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2315            }
2316
2317            // If this is first boot after an OTA, and a normal boot, then
2318            // we need to clear code cache directories.
2319            if (mIsUpgrade && !onlyCore) {
2320                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2321                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2322                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2323                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2324                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2325                    }
2326                }
2327                ver.fingerprint = Build.FINGERPRINT;
2328            }
2329
2330            checkDefaultBrowser();
2331
2332            // All the changes are done during package scanning.
2333            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2334
2335            // can downgrade to reader
2336            mSettings.writeLPr();
2337
2338            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2339                    SystemClock.uptimeMillis());
2340
2341            mRequiredVerifierPackage = getRequiredVerifierLPr();
2342            mRequiredInstallerPackage = getRequiredInstallerLPr();
2343
2344            mInstallerService = new PackageInstallerService(context, this);
2345
2346            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2347            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2348                    mIntentFilterVerifierComponent);
2349
2350        } // synchronized (mPackages)
2351        } // synchronized (mInstallLock)
2352
2353        // Now after opening every single application zip, make sure they
2354        // are all flushed.  Not really needed, but keeps things nice and
2355        // tidy.
2356        Runtime.getRuntime().gc();
2357
2358        // Expose private service for system components to use.
2359        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2360    }
2361
2362    @Override
2363    public boolean isFirstBoot() {
2364        return !mRestoredSettings;
2365    }
2366
2367    @Override
2368    public boolean isOnlyCoreApps() {
2369        return mOnlyCore;
2370    }
2371
2372    @Override
2373    public boolean isUpgrade() {
2374        return mIsUpgrade;
2375    }
2376
2377    private String getRequiredVerifierLPr() {
2378        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2379        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2380                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2381
2382        String requiredVerifier = null;
2383
2384        final int N = receivers.size();
2385        for (int i = 0; i < N; i++) {
2386            final ResolveInfo info = receivers.get(i);
2387
2388            if (info.activityInfo == null) {
2389                continue;
2390            }
2391
2392            final String packageName = info.activityInfo.packageName;
2393
2394            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2395                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2396                continue;
2397            }
2398
2399            if (requiredVerifier != null) {
2400                throw new RuntimeException("There can be only one required verifier");
2401            }
2402
2403            requiredVerifier = packageName;
2404        }
2405
2406        return requiredVerifier;
2407    }
2408
2409    private String getRequiredInstallerLPr() {
2410        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2411        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2412        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2413
2414        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2415                PACKAGE_MIME_TYPE, 0, 0);
2416
2417        String requiredInstaller = null;
2418
2419        final int N = installers.size();
2420        for (int i = 0; i < N; i++) {
2421            final ResolveInfo info = installers.get(i);
2422            final String packageName = info.activityInfo.packageName;
2423
2424            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2425                continue;
2426            }
2427
2428            if (requiredInstaller != null) {
2429                throw new RuntimeException("There must be one required installer");
2430            }
2431
2432            requiredInstaller = packageName;
2433        }
2434
2435        if (requiredInstaller == null) {
2436            throw new RuntimeException("There must be one required installer");
2437        }
2438
2439        return requiredInstaller;
2440    }
2441
2442    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2443        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2444        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2445                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2446
2447        ComponentName verifierComponentName = null;
2448
2449        int priority = -1000;
2450        final int N = receivers.size();
2451        for (int i = 0; i < N; i++) {
2452            final ResolveInfo info = receivers.get(i);
2453
2454            if (info.activityInfo == null) {
2455                continue;
2456            }
2457
2458            final String packageName = info.activityInfo.packageName;
2459
2460            final PackageSetting ps = mSettings.mPackages.get(packageName);
2461            if (ps == null) {
2462                continue;
2463            }
2464
2465            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2466                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2467                continue;
2468            }
2469
2470            // Select the IntentFilterVerifier with the highest priority
2471            if (priority < info.priority) {
2472                priority = info.priority;
2473                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2474                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2475                        + verifierComponentName + " with priority: " + info.priority);
2476            }
2477        }
2478
2479        return verifierComponentName;
2480    }
2481
2482    private void primeDomainVerificationsLPw(int userId) {
2483        if (DEBUG_DOMAIN_VERIFICATION) {
2484            Slog.d(TAG, "Priming domain verifications in user " + userId);
2485        }
2486
2487        SystemConfig systemConfig = SystemConfig.getInstance();
2488        ArraySet<String> packages = systemConfig.getLinkedApps();
2489        ArraySet<String> domains = new ArraySet<String>();
2490
2491        for (String packageName : packages) {
2492            PackageParser.Package pkg = mPackages.get(packageName);
2493            if (pkg != null) {
2494                if (!pkg.isSystemApp()) {
2495                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2496                    continue;
2497                }
2498
2499                domains.clear();
2500                for (PackageParser.Activity a : pkg.activities) {
2501                    for (ActivityIntentInfo filter : a.intents) {
2502                        if (hasValidDomains(filter)) {
2503                            domains.addAll(filter.getHostsList());
2504                        }
2505                    }
2506                }
2507
2508                if (domains.size() > 0) {
2509                    if (DEBUG_DOMAIN_VERIFICATION) {
2510                        Slog.v(TAG, "      + " + packageName);
2511                    }
2512                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2513                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2514                    // and then 'always' in the per-user state actually used for intent resolution.
2515                    final IntentFilterVerificationInfo ivi;
2516                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2517                            new ArrayList<String>(domains));
2518                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2519                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2520                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2521                } else {
2522                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2523                            + "' does not handle web links");
2524                }
2525            } else {
2526                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2527            }
2528        }
2529
2530        scheduleWritePackageRestrictionsLocked(userId);
2531        scheduleWriteSettingsLocked();
2532    }
2533
2534    private void applyFactoryDefaultBrowserLPw(int userId) {
2535        // The default browser app's package name is stored in a string resource,
2536        // with a product-specific overlay used for vendor customization.
2537        String browserPkg = mContext.getResources().getString(
2538                com.android.internal.R.string.default_browser);
2539        if (!TextUtils.isEmpty(browserPkg)) {
2540            // non-empty string => required to be a known package
2541            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2542            if (ps == null) {
2543                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2544                browserPkg = null;
2545            } else {
2546                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2547            }
2548        }
2549
2550        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2551        // default.  If there's more than one, just leave everything alone.
2552        if (browserPkg == null) {
2553            calculateDefaultBrowserLPw(userId);
2554        }
2555    }
2556
2557    private void calculateDefaultBrowserLPw(int userId) {
2558        List<String> allBrowsers = resolveAllBrowserApps(userId);
2559        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2560        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2561    }
2562
2563    private List<String> resolveAllBrowserApps(int userId) {
2564        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2565        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2566                PackageManager.MATCH_ALL, userId);
2567
2568        final int count = list.size();
2569        List<String> result = new ArrayList<String>(count);
2570        for (int i=0; i<count; i++) {
2571            ResolveInfo info = list.get(i);
2572            if (info.activityInfo == null
2573                    || !info.handleAllWebDataURI
2574                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2575                    || result.contains(info.activityInfo.packageName)) {
2576                continue;
2577            }
2578            result.add(info.activityInfo.packageName);
2579        }
2580
2581        return result;
2582    }
2583
2584    private boolean packageIsBrowser(String packageName, int userId) {
2585        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2586                PackageManager.MATCH_ALL, userId);
2587        final int N = list.size();
2588        for (int i = 0; i < N; i++) {
2589            ResolveInfo info = list.get(i);
2590            if (packageName.equals(info.activityInfo.packageName)) {
2591                return true;
2592            }
2593        }
2594        return false;
2595    }
2596
2597    private void checkDefaultBrowser() {
2598        final int myUserId = UserHandle.myUserId();
2599        final String packageName = getDefaultBrowserPackageName(myUserId);
2600        if (packageName != null) {
2601            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2602            if (info == null) {
2603                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2604                synchronized (mPackages) {
2605                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2606                }
2607            }
2608        }
2609    }
2610
2611    @Override
2612    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2613            throws RemoteException {
2614        try {
2615            return super.onTransact(code, data, reply, flags);
2616        } catch (RuntimeException e) {
2617            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2618                Slog.wtf(TAG, "Package Manager Crash", e);
2619            }
2620            throw e;
2621        }
2622    }
2623
2624    void cleanupInstallFailedPackage(PackageSetting ps) {
2625        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2626
2627        removeDataDirsLI(ps.volumeUuid, ps.name);
2628        if (ps.codePath != null) {
2629            if (ps.codePath.isDirectory()) {
2630                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2631            } else {
2632                ps.codePath.delete();
2633            }
2634        }
2635        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2636            if (ps.resourcePath.isDirectory()) {
2637                FileUtils.deleteContents(ps.resourcePath);
2638            }
2639            ps.resourcePath.delete();
2640        }
2641        mSettings.removePackageLPw(ps.name);
2642    }
2643
2644    static int[] appendInts(int[] cur, int[] add) {
2645        if (add == null) return cur;
2646        if (cur == null) return add;
2647        final int N = add.length;
2648        for (int i=0; i<N; i++) {
2649            cur = appendInt(cur, add[i]);
2650        }
2651        return cur;
2652    }
2653
2654    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2655        if (!sUserManager.exists(userId)) return null;
2656        final PackageSetting ps = (PackageSetting) p.mExtras;
2657        if (ps == null) {
2658            return null;
2659        }
2660
2661        final PermissionsState permissionsState = ps.getPermissionsState();
2662
2663        final int[] gids = permissionsState.computeGids(userId);
2664        final Set<String> permissions = permissionsState.getPermissions(userId);
2665        final PackageUserState state = ps.readUserState(userId);
2666
2667        return PackageParser.generatePackageInfo(p, gids, flags,
2668                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2669    }
2670
2671    @Override
2672    public boolean isPackageFrozen(String packageName) {
2673        synchronized (mPackages) {
2674            final PackageSetting ps = mSettings.mPackages.get(packageName);
2675            if (ps != null) {
2676                return ps.frozen;
2677            }
2678        }
2679        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2680        return true;
2681    }
2682
2683    @Override
2684    public boolean isPackageAvailable(String packageName, int userId) {
2685        if (!sUserManager.exists(userId)) return false;
2686        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2687        synchronized (mPackages) {
2688            PackageParser.Package p = mPackages.get(packageName);
2689            if (p != null) {
2690                final PackageSetting ps = (PackageSetting) p.mExtras;
2691                if (ps != null) {
2692                    final PackageUserState state = ps.readUserState(userId);
2693                    if (state != null) {
2694                        return PackageParser.isAvailable(state);
2695                    }
2696                }
2697            }
2698        }
2699        return false;
2700    }
2701
2702    @Override
2703    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2704        if (!sUserManager.exists(userId)) return null;
2705        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2706        // reader
2707        synchronized (mPackages) {
2708            PackageParser.Package p = mPackages.get(packageName);
2709            if (DEBUG_PACKAGE_INFO)
2710                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2711            if (p != null) {
2712                return generatePackageInfo(p, flags, userId);
2713            }
2714            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2715                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2716            }
2717        }
2718        return null;
2719    }
2720
2721    @Override
2722    public String[] currentToCanonicalPackageNames(String[] names) {
2723        String[] out = new String[names.length];
2724        // reader
2725        synchronized (mPackages) {
2726            for (int i=names.length-1; i>=0; i--) {
2727                PackageSetting ps = mSettings.mPackages.get(names[i]);
2728                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2729            }
2730        }
2731        return out;
2732    }
2733
2734    @Override
2735    public String[] canonicalToCurrentPackageNames(String[] names) {
2736        String[] out = new String[names.length];
2737        // reader
2738        synchronized (mPackages) {
2739            for (int i=names.length-1; i>=0; i--) {
2740                String cur = mSettings.mRenamedPackages.get(names[i]);
2741                out[i] = cur != null ? cur : names[i];
2742            }
2743        }
2744        return out;
2745    }
2746
2747    @Override
2748    public int getPackageUid(String packageName, int userId) {
2749        if (!sUserManager.exists(userId)) return -1;
2750        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2751
2752        // reader
2753        synchronized (mPackages) {
2754            PackageParser.Package p = mPackages.get(packageName);
2755            if(p != null) {
2756                return UserHandle.getUid(userId, p.applicationInfo.uid);
2757            }
2758            PackageSetting ps = mSettings.mPackages.get(packageName);
2759            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2760                return -1;
2761            }
2762            p = ps.pkg;
2763            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2764        }
2765    }
2766
2767    @Override
2768    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2769        if (!sUserManager.exists(userId)) {
2770            return null;
2771        }
2772
2773        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2774                "getPackageGids");
2775
2776        // reader
2777        synchronized (mPackages) {
2778            PackageParser.Package p = mPackages.get(packageName);
2779            if (DEBUG_PACKAGE_INFO) {
2780                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2781            }
2782            if (p != null) {
2783                PackageSetting ps = (PackageSetting) p.mExtras;
2784                return ps.getPermissionsState().computeGids(userId);
2785            }
2786        }
2787
2788        return null;
2789    }
2790
2791    static PermissionInfo generatePermissionInfo(
2792            BasePermission bp, int flags) {
2793        if (bp.perm != null) {
2794            return PackageParser.generatePermissionInfo(bp.perm, flags);
2795        }
2796        PermissionInfo pi = new PermissionInfo();
2797        pi.name = bp.name;
2798        pi.packageName = bp.sourcePackage;
2799        pi.nonLocalizedLabel = bp.name;
2800        pi.protectionLevel = bp.protectionLevel;
2801        return pi;
2802    }
2803
2804    @Override
2805    public PermissionInfo getPermissionInfo(String name, int flags) {
2806        // reader
2807        synchronized (mPackages) {
2808            final BasePermission p = mSettings.mPermissions.get(name);
2809            if (p != null) {
2810                return generatePermissionInfo(p, flags);
2811            }
2812            return null;
2813        }
2814    }
2815
2816    @Override
2817    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2818        // reader
2819        synchronized (mPackages) {
2820            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2821            for (BasePermission p : mSettings.mPermissions.values()) {
2822                if (group == null) {
2823                    if (p.perm == null || p.perm.info.group == null) {
2824                        out.add(generatePermissionInfo(p, flags));
2825                    }
2826                } else {
2827                    if (p.perm != null && group.equals(p.perm.info.group)) {
2828                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2829                    }
2830                }
2831            }
2832
2833            if (out.size() > 0) {
2834                return out;
2835            }
2836            return mPermissionGroups.containsKey(group) ? out : null;
2837        }
2838    }
2839
2840    @Override
2841    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2842        // reader
2843        synchronized (mPackages) {
2844            return PackageParser.generatePermissionGroupInfo(
2845                    mPermissionGroups.get(name), flags);
2846        }
2847    }
2848
2849    @Override
2850    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2851        // reader
2852        synchronized (mPackages) {
2853            final int N = mPermissionGroups.size();
2854            ArrayList<PermissionGroupInfo> out
2855                    = new ArrayList<PermissionGroupInfo>(N);
2856            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2857                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2858            }
2859            return out;
2860        }
2861    }
2862
2863    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2864            int userId) {
2865        if (!sUserManager.exists(userId)) return null;
2866        PackageSetting ps = mSettings.mPackages.get(packageName);
2867        if (ps != null) {
2868            if (ps.pkg == null) {
2869                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2870                        flags, userId);
2871                if (pInfo != null) {
2872                    return pInfo.applicationInfo;
2873                }
2874                return null;
2875            }
2876            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2877                    ps.readUserState(userId), userId);
2878        }
2879        return null;
2880    }
2881
2882    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2883            int userId) {
2884        if (!sUserManager.exists(userId)) return null;
2885        PackageSetting ps = mSettings.mPackages.get(packageName);
2886        if (ps != null) {
2887            PackageParser.Package pkg = ps.pkg;
2888            if (pkg == null) {
2889                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2890                    return null;
2891                }
2892                // Only data remains, so we aren't worried about code paths
2893                pkg = new PackageParser.Package(packageName);
2894                pkg.applicationInfo.packageName = packageName;
2895                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2896                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2897                pkg.applicationInfo.dataDir = Environment
2898                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2899                        .getAbsolutePath();
2900                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2901                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2902            }
2903            return generatePackageInfo(pkg, flags, userId);
2904        }
2905        return null;
2906    }
2907
2908    @Override
2909    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2910        if (!sUserManager.exists(userId)) return null;
2911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2912        // writer
2913        synchronized (mPackages) {
2914            PackageParser.Package p = mPackages.get(packageName);
2915            if (DEBUG_PACKAGE_INFO) Log.v(
2916                    TAG, "getApplicationInfo " + packageName
2917                    + ": " + p);
2918            if (p != null) {
2919                PackageSetting ps = mSettings.mPackages.get(packageName);
2920                if (ps == null) return null;
2921                // Note: isEnabledLP() does not apply here - always return info
2922                return PackageParser.generateApplicationInfo(
2923                        p, flags, ps.readUserState(userId), userId);
2924            }
2925            if ("android".equals(packageName)||"system".equals(packageName)) {
2926                return mAndroidApplication;
2927            }
2928            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2929                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2930            }
2931        }
2932        return null;
2933    }
2934
2935    @Override
2936    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2937            final IPackageDataObserver observer) {
2938        mContext.enforceCallingOrSelfPermission(
2939                android.Manifest.permission.CLEAR_APP_CACHE, null);
2940        // Queue up an async operation since clearing cache may take a little while.
2941        mHandler.post(new Runnable() {
2942            public void run() {
2943                mHandler.removeCallbacks(this);
2944                int retCode = -1;
2945                synchronized (mInstallLock) {
2946                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2947                    if (retCode < 0) {
2948                        Slog.w(TAG, "Couldn't clear application caches");
2949                    }
2950                }
2951                if (observer != null) {
2952                    try {
2953                        observer.onRemoveCompleted(null, (retCode >= 0));
2954                    } catch (RemoteException e) {
2955                        Slog.w(TAG, "RemoveException when invoking call back");
2956                    }
2957                }
2958            }
2959        });
2960    }
2961
2962    @Override
2963    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2964            final IntentSender pi) {
2965        mContext.enforceCallingOrSelfPermission(
2966                android.Manifest.permission.CLEAR_APP_CACHE, null);
2967        // Queue up an async operation since clearing cache may take a little while.
2968        mHandler.post(new Runnable() {
2969            public void run() {
2970                mHandler.removeCallbacks(this);
2971                int retCode = -1;
2972                synchronized (mInstallLock) {
2973                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2974                    if (retCode < 0) {
2975                        Slog.w(TAG, "Couldn't clear application caches");
2976                    }
2977                }
2978                if(pi != null) {
2979                    try {
2980                        // Callback via pending intent
2981                        int code = (retCode >= 0) ? 1 : 0;
2982                        pi.sendIntent(null, code, null,
2983                                null, null);
2984                    } catch (SendIntentException e1) {
2985                        Slog.i(TAG, "Failed to send pending intent");
2986                    }
2987                }
2988            }
2989        });
2990    }
2991
2992    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2993        synchronized (mInstallLock) {
2994            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2995                throw new IOException("Failed to free enough space");
2996            }
2997        }
2998    }
2999
3000    @Override
3001    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3002        if (!sUserManager.exists(userId)) return null;
3003        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3004        synchronized (mPackages) {
3005            PackageParser.Activity a = mActivities.mActivities.get(component);
3006
3007            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3008            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3009                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3010                if (ps == null) return null;
3011                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3012                        userId);
3013            }
3014            if (mResolveComponentName.equals(component)) {
3015                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3016                        new PackageUserState(), userId);
3017            }
3018        }
3019        return null;
3020    }
3021
3022    @Override
3023    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3024            String resolvedType) {
3025        synchronized (mPackages) {
3026            if (component.equals(mResolveComponentName)) {
3027                // The resolver supports EVERYTHING!
3028                return true;
3029            }
3030            PackageParser.Activity a = mActivities.mActivities.get(component);
3031            if (a == null) {
3032                return false;
3033            }
3034            for (int i=0; i<a.intents.size(); i++) {
3035                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3036                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3037                    return true;
3038                }
3039            }
3040            return false;
3041        }
3042    }
3043
3044    @Override
3045    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3046        if (!sUserManager.exists(userId)) return null;
3047        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3048        synchronized (mPackages) {
3049            PackageParser.Activity a = mReceivers.mActivities.get(component);
3050            if (DEBUG_PACKAGE_INFO) Log.v(
3051                TAG, "getReceiverInfo " + component + ": " + a);
3052            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3053                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3054                if (ps == null) return null;
3055                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3056                        userId);
3057            }
3058        }
3059        return null;
3060    }
3061
3062    @Override
3063    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3064        if (!sUserManager.exists(userId)) return null;
3065        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3066        synchronized (mPackages) {
3067            PackageParser.Service s = mServices.mServices.get(component);
3068            if (DEBUG_PACKAGE_INFO) Log.v(
3069                TAG, "getServiceInfo " + component + ": " + s);
3070            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3071                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3072                if (ps == null) return null;
3073                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3074                        userId);
3075            }
3076        }
3077        return null;
3078    }
3079
3080    @Override
3081    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3082        if (!sUserManager.exists(userId)) return null;
3083        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3084        synchronized (mPackages) {
3085            PackageParser.Provider p = mProviders.mProviders.get(component);
3086            if (DEBUG_PACKAGE_INFO) Log.v(
3087                TAG, "getProviderInfo " + component + ": " + p);
3088            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3089                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3090                if (ps == null) return null;
3091                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3092                        userId);
3093            }
3094        }
3095        return null;
3096    }
3097
3098    @Override
3099    public String[] getSystemSharedLibraryNames() {
3100        Set<String> libSet;
3101        synchronized (mPackages) {
3102            libSet = mSharedLibraries.keySet();
3103            int size = libSet.size();
3104            if (size > 0) {
3105                String[] libs = new String[size];
3106                libSet.toArray(libs);
3107                return libs;
3108            }
3109        }
3110        return null;
3111    }
3112
3113    /**
3114     * @hide
3115     */
3116    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3117        synchronized (mPackages) {
3118            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3119            if (lib != null && lib.apk != null) {
3120                return mPackages.get(lib.apk);
3121            }
3122        }
3123        return null;
3124    }
3125
3126    @Override
3127    public FeatureInfo[] getSystemAvailableFeatures() {
3128        Collection<FeatureInfo> featSet;
3129        synchronized (mPackages) {
3130            featSet = mAvailableFeatures.values();
3131            int size = featSet.size();
3132            if (size > 0) {
3133                FeatureInfo[] features = new FeatureInfo[size+1];
3134                featSet.toArray(features);
3135                FeatureInfo fi = new FeatureInfo();
3136                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3137                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3138                features[size] = fi;
3139                return features;
3140            }
3141        }
3142        return null;
3143    }
3144
3145    @Override
3146    public boolean hasSystemFeature(String name) {
3147        synchronized (mPackages) {
3148            return mAvailableFeatures.containsKey(name);
3149        }
3150    }
3151
3152    private void checkValidCaller(int uid, int userId) {
3153        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3154            return;
3155
3156        throw new SecurityException("Caller uid=" + uid
3157                + " is not privileged to communicate with user=" + userId);
3158    }
3159
3160    @Override
3161    public int checkPermission(String permName, String pkgName, int userId) {
3162        if (!sUserManager.exists(userId)) {
3163            return PackageManager.PERMISSION_DENIED;
3164        }
3165
3166        synchronized (mPackages) {
3167            final PackageParser.Package p = mPackages.get(pkgName);
3168            if (p != null && p.mExtras != null) {
3169                final PackageSetting ps = (PackageSetting) p.mExtras;
3170                final PermissionsState permissionsState = ps.getPermissionsState();
3171                if (permissionsState.hasPermission(permName, userId)) {
3172                    return PackageManager.PERMISSION_GRANTED;
3173                }
3174                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3175                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3176                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3177                    return PackageManager.PERMISSION_GRANTED;
3178                }
3179            }
3180        }
3181
3182        return PackageManager.PERMISSION_DENIED;
3183    }
3184
3185    @Override
3186    public int checkUidPermission(String permName, int uid) {
3187        final int userId = UserHandle.getUserId(uid);
3188
3189        if (!sUserManager.exists(userId)) {
3190            return PackageManager.PERMISSION_DENIED;
3191        }
3192
3193        synchronized (mPackages) {
3194            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3195            if (obj != null) {
3196                final SettingBase ps = (SettingBase) obj;
3197                final PermissionsState permissionsState = ps.getPermissionsState();
3198                if (permissionsState.hasPermission(permName, userId)) {
3199                    return PackageManager.PERMISSION_GRANTED;
3200                }
3201                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3202                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3203                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3204                    return PackageManager.PERMISSION_GRANTED;
3205                }
3206            } else {
3207                ArraySet<String> perms = mSystemPermissions.get(uid);
3208                if (perms != null) {
3209                    if (perms.contains(permName)) {
3210                        return PackageManager.PERMISSION_GRANTED;
3211                    }
3212                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3213                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3214                        return PackageManager.PERMISSION_GRANTED;
3215                    }
3216                }
3217            }
3218        }
3219
3220        return PackageManager.PERMISSION_DENIED;
3221    }
3222
3223    @Override
3224    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3225        if (UserHandle.getCallingUserId() != userId) {
3226            mContext.enforceCallingPermission(
3227                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3228                    "isPermissionRevokedByPolicy for user " + userId);
3229        }
3230
3231        if (checkPermission(permission, packageName, userId)
3232                == PackageManager.PERMISSION_GRANTED) {
3233            return false;
3234        }
3235
3236        final long identity = Binder.clearCallingIdentity();
3237        try {
3238            final int flags = getPermissionFlags(permission, packageName, userId);
3239            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3240        } finally {
3241            Binder.restoreCallingIdentity(identity);
3242        }
3243    }
3244
3245    @Override
3246    public String getPermissionControllerPackageName() {
3247        synchronized (mPackages) {
3248            return mRequiredInstallerPackage;
3249        }
3250    }
3251
3252    /**
3253     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3254     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3255     * @param checkShell TODO(yamasani):
3256     * @param message the message to log on security exception
3257     */
3258    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3259            boolean checkShell, String message) {
3260        if (userId < 0) {
3261            throw new IllegalArgumentException("Invalid userId " + userId);
3262        }
3263        if (checkShell) {
3264            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3265        }
3266        if (userId == UserHandle.getUserId(callingUid)) return;
3267        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3268            if (requireFullPermission) {
3269                mContext.enforceCallingOrSelfPermission(
3270                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3271            } else {
3272                try {
3273                    mContext.enforceCallingOrSelfPermission(
3274                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3275                } catch (SecurityException se) {
3276                    mContext.enforceCallingOrSelfPermission(
3277                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3278                }
3279            }
3280        }
3281    }
3282
3283    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3284        if (callingUid == Process.SHELL_UID) {
3285            if (userHandle >= 0
3286                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3287                throw new SecurityException("Shell does not have permission to access user "
3288                        + userHandle);
3289            } else if (userHandle < 0) {
3290                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3291                        + Debug.getCallers(3));
3292            }
3293        }
3294    }
3295
3296    private BasePermission findPermissionTreeLP(String permName) {
3297        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3298            if (permName.startsWith(bp.name) &&
3299                    permName.length() > bp.name.length() &&
3300                    permName.charAt(bp.name.length()) == '.') {
3301                return bp;
3302            }
3303        }
3304        return null;
3305    }
3306
3307    private BasePermission checkPermissionTreeLP(String permName) {
3308        if (permName != null) {
3309            BasePermission bp = findPermissionTreeLP(permName);
3310            if (bp != null) {
3311                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3312                    return bp;
3313                }
3314                throw new SecurityException("Calling uid "
3315                        + Binder.getCallingUid()
3316                        + " is not allowed to add to permission tree "
3317                        + bp.name + " owned by uid " + bp.uid);
3318            }
3319        }
3320        throw new SecurityException("No permission tree found for " + permName);
3321    }
3322
3323    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3324        if (s1 == null) {
3325            return s2 == null;
3326        }
3327        if (s2 == null) {
3328            return false;
3329        }
3330        if (s1.getClass() != s2.getClass()) {
3331            return false;
3332        }
3333        return s1.equals(s2);
3334    }
3335
3336    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3337        if (pi1.icon != pi2.icon) return false;
3338        if (pi1.logo != pi2.logo) return false;
3339        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3340        if (!compareStrings(pi1.name, pi2.name)) return false;
3341        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3342        // We'll take care of setting this one.
3343        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3344        // These are not currently stored in settings.
3345        //if (!compareStrings(pi1.group, pi2.group)) return false;
3346        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3347        //if (pi1.labelRes != pi2.labelRes) return false;
3348        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3349        return true;
3350    }
3351
3352    int permissionInfoFootprint(PermissionInfo info) {
3353        int size = info.name.length();
3354        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3355        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3356        return size;
3357    }
3358
3359    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3360        int size = 0;
3361        for (BasePermission perm : mSettings.mPermissions.values()) {
3362            if (perm.uid == tree.uid) {
3363                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3364            }
3365        }
3366        return size;
3367    }
3368
3369    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3370        // We calculate the max size of permissions defined by this uid and throw
3371        // if that plus the size of 'info' would exceed our stated maximum.
3372        if (tree.uid != Process.SYSTEM_UID) {
3373            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3374            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3375                throw new SecurityException("Permission tree size cap exceeded");
3376            }
3377        }
3378    }
3379
3380    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3381        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3382            throw new SecurityException("Label must be specified in permission");
3383        }
3384        BasePermission tree = checkPermissionTreeLP(info.name);
3385        BasePermission bp = mSettings.mPermissions.get(info.name);
3386        boolean added = bp == null;
3387        boolean changed = true;
3388        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3389        if (added) {
3390            enforcePermissionCapLocked(info, tree);
3391            bp = new BasePermission(info.name, tree.sourcePackage,
3392                    BasePermission.TYPE_DYNAMIC);
3393        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3394            throw new SecurityException(
3395                    "Not allowed to modify non-dynamic permission "
3396                    + info.name);
3397        } else {
3398            if (bp.protectionLevel == fixedLevel
3399                    && bp.perm.owner.equals(tree.perm.owner)
3400                    && bp.uid == tree.uid
3401                    && comparePermissionInfos(bp.perm.info, info)) {
3402                changed = false;
3403            }
3404        }
3405        bp.protectionLevel = fixedLevel;
3406        info = new PermissionInfo(info);
3407        info.protectionLevel = fixedLevel;
3408        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3409        bp.perm.info.packageName = tree.perm.info.packageName;
3410        bp.uid = tree.uid;
3411        if (added) {
3412            mSettings.mPermissions.put(info.name, bp);
3413        }
3414        if (changed) {
3415            if (!async) {
3416                mSettings.writeLPr();
3417            } else {
3418                scheduleWriteSettingsLocked();
3419            }
3420        }
3421        return added;
3422    }
3423
3424    @Override
3425    public boolean addPermission(PermissionInfo info) {
3426        synchronized (mPackages) {
3427            return addPermissionLocked(info, false);
3428        }
3429    }
3430
3431    @Override
3432    public boolean addPermissionAsync(PermissionInfo info) {
3433        synchronized (mPackages) {
3434            return addPermissionLocked(info, true);
3435        }
3436    }
3437
3438    @Override
3439    public void removePermission(String name) {
3440        synchronized (mPackages) {
3441            checkPermissionTreeLP(name);
3442            BasePermission bp = mSettings.mPermissions.get(name);
3443            if (bp != null) {
3444                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3445                    throw new SecurityException(
3446                            "Not allowed to modify non-dynamic permission "
3447                            + name);
3448                }
3449                mSettings.mPermissions.remove(name);
3450                mSettings.writeLPr();
3451            }
3452        }
3453    }
3454
3455    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3456            BasePermission bp) {
3457        int index = pkg.requestedPermissions.indexOf(bp.name);
3458        if (index == -1) {
3459            throw new SecurityException("Package " + pkg.packageName
3460                    + " has not requested permission " + bp.name);
3461        }
3462        if (!bp.isRuntime() && !bp.isDevelopment()) {
3463            throw new SecurityException("Permission " + bp.name
3464                    + " is not a changeable permission type");
3465        }
3466    }
3467
3468    @Override
3469    public void grantRuntimePermission(String packageName, String name, final int userId) {
3470        if (!sUserManager.exists(userId)) {
3471            Log.e(TAG, "No such user:" + userId);
3472            return;
3473        }
3474
3475        mContext.enforceCallingOrSelfPermission(
3476                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3477                "grantRuntimePermission");
3478
3479        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3480                "grantRuntimePermission");
3481
3482        final int uid;
3483        final SettingBase sb;
3484
3485        synchronized (mPackages) {
3486            final PackageParser.Package pkg = mPackages.get(packageName);
3487            if (pkg == null) {
3488                throw new IllegalArgumentException("Unknown package: " + packageName);
3489            }
3490
3491            final BasePermission bp = mSettings.mPermissions.get(name);
3492            if (bp == null) {
3493                throw new IllegalArgumentException("Unknown permission: " + name);
3494            }
3495
3496            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3497
3498            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3499            sb = (SettingBase) pkg.mExtras;
3500            if (sb == null) {
3501                throw new IllegalArgumentException("Unknown package: " + packageName);
3502            }
3503
3504            final PermissionsState permissionsState = sb.getPermissionsState();
3505
3506            final int flags = permissionsState.getPermissionFlags(name, userId);
3507            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3508                throw new SecurityException("Cannot grant system fixed permission: "
3509                        + name + " for package: " + packageName);
3510            }
3511
3512            if (bp.isDevelopment()) {
3513                // Development permissions must be handled specially, since they are not
3514                // normal runtime permissions.  For now they apply to all users.
3515                if (permissionsState.grantInstallPermission(bp) !=
3516                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3517                    scheduleWriteSettingsLocked();
3518                }
3519                return;
3520            }
3521
3522            final int result = permissionsState.grantRuntimePermission(bp, userId);
3523            switch (result) {
3524                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3525                    return;
3526                }
3527
3528                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3529                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3530                    mHandler.post(new Runnable() {
3531                        @Override
3532                        public void run() {
3533                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3534                        }
3535                    });
3536                } break;
3537            }
3538
3539            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3540
3541            // Not critical if that is lost - app has to request again.
3542            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3543        }
3544
3545        // Only need to do this if user is initialized. Otherwise it's a new user
3546        // and there are no processes running as the user yet and there's no need
3547        // to make an expensive call to remount processes for the changed permissions.
3548        if (READ_EXTERNAL_STORAGE.equals(name)
3549                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3550            final long token = Binder.clearCallingIdentity();
3551            try {
3552                if (sUserManager.isInitialized(userId)) {
3553                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3554                            MountServiceInternal.class);
3555                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3556                }
3557            } finally {
3558                Binder.restoreCallingIdentity(token);
3559            }
3560        }
3561    }
3562
3563    @Override
3564    public void revokeRuntimePermission(String packageName, String name, int userId) {
3565        if (!sUserManager.exists(userId)) {
3566            Log.e(TAG, "No such user:" + userId);
3567            return;
3568        }
3569
3570        mContext.enforceCallingOrSelfPermission(
3571                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3572                "revokeRuntimePermission");
3573
3574        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3575                "revokeRuntimePermission");
3576
3577        final int appId;
3578
3579        synchronized (mPackages) {
3580            final PackageParser.Package pkg = mPackages.get(packageName);
3581            if (pkg == null) {
3582                throw new IllegalArgumentException("Unknown package: " + packageName);
3583            }
3584
3585            final BasePermission bp = mSettings.mPermissions.get(name);
3586            if (bp == null) {
3587                throw new IllegalArgumentException("Unknown permission: " + name);
3588            }
3589
3590            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3591
3592            SettingBase sb = (SettingBase) pkg.mExtras;
3593            if (sb == null) {
3594                throw new IllegalArgumentException("Unknown package: " + packageName);
3595            }
3596
3597            final PermissionsState permissionsState = sb.getPermissionsState();
3598
3599            final int flags = permissionsState.getPermissionFlags(name, userId);
3600            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3601                throw new SecurityException("Cannot revoke system fixed permission: "
3602                        + name + " for package: " + packageName);
3603            }
3604
3605            if (bp.isDevelopment()) {
3606                // Development permissions must be handled specially, since they are not
3607                // normal runtime permissions.  For now they apply to all users.
3608                if (permissionsState.revokeInstallPermission(bp) !=
3609                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3610                    scheduleWriteSettingsLocked();
3611                }
3612                return;
3613            }
3614
3615            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3616                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3617                return;
3618            }
3619
3620            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3621
3622            // Critical, after this call app should never have the permission.
3623            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3624
3625            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3626        }
3627
3628        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3629    }
3630
3631    @Override
3632    public void resetRuntimePermissions() {
3633        mContext.enforceCallingOrSelfPermission(
3634                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3635                "revokeRuntimePermission");
3636
3637        int callingUid = Binder.getCallingUid();
3638        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3639            mContext.enforceCallingOrSelfPermission(
3640                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3641                    "resetRuntimePermissions");
3642        }
3643
3644        synchronized (mPackages) {
3645            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3646            for (int userId : UserManagerService.getInstance().getUserIds()) {
3647                final int packageCount = mPackages.size();
3648                for (int i = 0; i < packageCount; i++) {
3649                    PackageParser.Package pkg = mPackages.valueAt(i);
3650                    if (!(pkg.mExtras instanceof PackageSetting)) {
3651                        continue;
3652                    }
3653                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3654                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3655                }
3656            }
3657        }
3658    }
3659
3660    @Override
3661    public int getPermissionFlags(String name, String packageName, int userId) {
3662        if (!sUserManager.exists(userId)) {
3663            return 0;
3664        }
3665
3666        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3667
3668        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3669                "getPermissionFlags");
3670
3671        synchronized (mPackages) {
3672            final PackageParser.Package pkg = mPackages.get(packageName);
3673            if (pkg == null) {
3674                throw new IllegalArgumentException("Unknown package: " + packageName);
3675            }
3676
3677            final BasePermission bp = mSettings.mPermissions.get(name);
3678            if (bp == null) {
3679                throw new IllegalArgumentException("Unknown permission: " + name);
3680            }
3681
3682            SettingBase sb = (SettingBase) pkg.mExtras;
3683            if (sb == null) {
3684                throw new IllegalArgumentException("Unknown package: " + packageName);
3685            }
3686
3687            PermissionsState permissionsState = sb.getPermissionsState();
3688            return permissionsState.getPermissionFlags(name, userId);
3689        }
3690    }
3691
3692    @Override
3693    public void updatePermissionFlags(String name, String packageName, int flagMask,
3694            int flagValues, int userId) {
3695        if (!sUserManager.exists(userId)) {
3696            return;
3697        }
3698
3699        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3700
3701        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3702                "updatePermissionFlags");
3703
3704        // Only the system can change these flags and nothing else.
3705        if (getCallingUid() != Process.SYSTEM_UID) {
3706            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3707            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3708            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3709            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3710        }
3711
3712        synchronized (mPackages) {
3713            final PackageParser.Package pkg = mPackages.get(packageName);
3714            if (pkg == null) {
3715                throw new IllegalArgumentException("Unknown package: " + packageName);
3716            }
3717
3718            final BasePermission bp = mSettings.mPermissions.get(name);
3719            if (bp == null) {
3720                throw new IllegalArgumentException("Unknown permission: " + name);
3721            }
3722
3723            SettingBase sb = (SettingBase) pkg.mExtras;
3724            if (sb == null) {
3725                throw new IllegalArgumentException("Unknown package: " + packageName);
3726            }
3727
3728            PermissionsState permissionsState = sb.getPermissionsState();
3729
3730            // Only the package manager can change flags for system component permissions.
3731            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3732            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3733                return;
3734            }
3735
3736            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3737
3738            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3739                // Install and runtime permissions are stored in different places,
3740                // so figure out what permission changed and persist the change.
3741                if (permissionsState.getInstallPermissionState(name) != null) {
3742                    scheduleWriteSettingsLocked();
3743                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3744                        || hadState) {
3745                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3746                }
3747            }
3748        }
3749    }
3750
3751    /**
3752     * Update the permission flags for all packages and runtime permissions of a user in order
3753     * to allow device or profile owner to remove POLICY_FIXED.
3754     */
3755    @Override
3756    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3757        if (!sUserManager.exists(userId)) {
3758            return;
3759        }
3760
3761        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3762
3763        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3764                "updatePermissionFlagsForAllApps");
3765
3766        // Only the system can change system fixed flags.
3767        if (getCallingUid() != Process.SYSTEM_UID) {
3768            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3769            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3770        }
3771
3772        synchronized (mPackages) {
3773            boolean changed = false;
3774            final int packageCount = mPackages.size();
3775            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3776                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3777                SettingBase sb = (SettingBase) pkg.mExtras;
3778                if (sb == null) {
3779                    continue;
3780                }
3781                PermissionsState permissionsState = sb.getPermissionsState();
3782                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3783                        userId, flagMask, flagValues);
3784            }
3785            if (changed) {
3786                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3787            }
3788        }
3789    }
3790
3791    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3792        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3793                != PackageManager.PERMISSION_GRANTED
3794            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3795                != PackageManager.PERMISSION_GRANTED) {
3796            throw new SecurityException(message + " requires "
3797                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3798                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3799        }
3800    }
3801
3802    @Override
3803    public boolean shouldShowRequestPermissionRationale(String permissionName,
3804            String packageName, int userId) {
3805        if (UserHandle.getCallingUserId() != userId) {
3806            mContext.enforceCallingPermission(
3807                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3808                    "canShowRequestPermissionRationale for user " + userId);
3809        }
3810
3811        final int uid = getPackageUid(packageName, userId);
3812        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3813            return false;
3814        }
3815
3816        if (checkPermission(permissionName, packageName, userId)
3817                == PackageManager.PERMISSION_GRANTED) {
3818            return false;
3819        }
3820
3821        final int flags;
3822
3823        final long identity = Binder.clearCallingIdentity();
3824        try {
3825            flags = getPermissionFlags(permissionName,
3826                    packageName, userId);
3827        } finally {
3828            Binder.restoreCallingIdentity(identity);
3829        }
3830
3831        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3832                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3833                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3834
3835        if ((flags & fixedFlags) != 0) {
3836            return false;
3837        }
3838
3839        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3840    }
3841
3842    @Override
3843    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3844        mContext.enforceCallingOrSelfPermission(
3845                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3846                "addOnPermissionsChangeListener");
3847
3848        synchronized (mPackages) {
3849            mOnPermissionChangeListeners.addListenerLocked(listener);
3850        }
3851    }
3852
3853    @Override
3854    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3855        synchronized (mPackages) {
3856            mOnPermissionChangeListeners.removeListenerLocked(listener);
3857        }
3858    }
3859
3860    @Override
3861    public boolean isProtectedBroadcast(String actionName) {
3862        synchronized (mPackages) {
3863            return mProtectedBroadcasts.contains(actionName);
3864        }
3865    }
3866
3867    @Override
3868    public int checkSignatures(String pkg1, String pkg2) {
3869        synchronized (mPackages) {
3870            final PackageParser.Package p1 = mPackages.get(pkg1);
3871            final PackageParser.Package p2 = mPackages.get(pkg2);
3872            if (p1 == null || p1.mExtras == null
3873                    || p2 == null || p2.mExtras == null) {
3874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3875            }
3876            return compareSignatures(p1.mSignatures, p2.mSignatures);
3877        }
3878    }
3879
3880    @Override
3881    public int checkUidSignatures(int uid1, int uid2) {
3882        // Map to base uids.
3883        uid1 = UserHandle.getAppId(uid1);
3884        uid2 = UserHandle.getAppId(uid2);
3885        // reader
3886        synchronized (mPackages) {
3887            Signature[] s1;
3888            Signature[] s2;
3889            Object obj = mSettings.getUserIdLPr(uid1);
3890            if (obj != null) {
3891                if (obj instanceof SharedUserSetting) {
3892                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3893                } else if (obj instanceof PackageSetting) {
3894                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3895                } else {
3896                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897                }
3898            } else {
3899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3900            }
3901            obj = mSettings.getUserIdLPr(uid2);
3902            if (obj != null) {
3903                if (obj instanceof SharedUserSetting) {
3904                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3905                } else if (obj instanceof PackageSetting) {
3906                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3907                } else {
3908                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3909                }
3910            } else {
3911                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3912            }
3913            return compareSignatures(s1, s2);
3914        }
3915    }
3916
3917    private void killUid(int appId, int userId, String reason) {
3918        final long identity = Binder.clearCallingIdentity();
3919        try {
3920            IActivityManager am = ActivityManagerNative.getDefault();
3921            if (am != null) {
3922                try {
3923                    am.killUid(appId, userId, reason);
3924                } catch (RemoteException e) {
3925                    /* ignore - same process */
3926                }
3927            }
3928        } finally {
3929            Binder.restoreCallingIdentity(identity);
3930        }
3931    }
3932
3933    /**
3934     * Compares two sets of signatures. Returns:
3935     * <br />
3936     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3937     * <br />
3938     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3939     * <br />
3940     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3941     * <br />
3942     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3943     * <br />
3944     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3945     */
3946    static int compareSignatures(Signature[] s1, Signature[] s2) {
3947        if (s1 == null) {
3948            return s2 == null
3949                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3950                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3951        }
3952
3953        if (s2 == null) {
3954            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3955        }
3956
3957        if (s1.length != s2.length) {
3958            return PackageManager.SIGNATURE_NO_MATCH;
3959        }
3960
3961        // Since both signature sets are of size 1, we can compare without HashSets.
3962        if (s1.length == 1) {
3963            return s1[0].equals(s2[0]) ?
3964                    PackageManager.SIGNATURE_MATCH :
3965                    PackageManager.SIGNATURE_NO_MATCH;
3966        }
3967
3968        ArraySet<Signature> set1 = new ArraySet<Signature>();
3969        for (Signature sig : s1) {
3970            set1.add(sig);
3971        }
3972        ArraySet<Signature> set2 = new ArraySet<Signature>();
3973        for (Signature sig : s2) {
3974            set2.add(sig);
3975        }
3976        // Make sure s2 contains all signatures in s1.
3977        if (set1.equals(set2)) {
3978            return PackageManager.SIGNATURE_MATCH;
3979        }
3980        return PackageManager.SIGNATURE_NO_MATCH;
3981    }
3982
3983    /**
3984     * If the database version for this type of package (internal storage or
3985     * external storage) is less than the version where package signatures
3986     * were updated, return true.
3987     */
3988    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3989        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3990        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3991    }
3992
3993    /**
3994     * Used for backward compatibility to make sure any packages with
3995     * certificate chains get upgraded to the new style. {@code existingSigs}
3996     * will be in the old format (since they were stored on disk from before the
3997     * system upgrade) and {@code scannedSigs} will be in the newer format.
3998     */
3999    private int compareSignaturesCompat(PackageSignatures existingSigs,
4000            PackageParser.Package scannedPkg) {
4001        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4002            return PackageManager.SIGNATURE_NO_MATCH;
4003        }
4004
4005        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4006        for (Signature sig : existingSigs.mSignatures) {
4007            existingSet.add(sig);
4008        }
4009        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4010        for (Signature sig : scannedPkg.mSignatures) {
4011            try {
4012                Signature[] chainSignatures = sig.getChainSignatures();
4013                for (Signature chainSig : chainSignatures) {
4014                    scannedCompatSet.add(chainSig);
4015                }
4016            } catch (CertificateEncodingException e) {
4017                scannedCompatSet.add(sig);
4018            }
4019        }
4020        /*
4021         * Make sure the expanded scanned set contains all signatures in the
4022         * existing one.
4023         */
4024        if (scannedCompatSet.equals(existingSet)) {
4025            // Migrate the old signatures to the new scheme.
4026            existingSigs.assignSignatures(scannedPkg.mSignatures);
4027            // The new KeySets will be re-added later in the scanning process.
4028            synchronized (mPackages) {
4029                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4030            }
4031            return PackageManager.SIGNATURE_MATCH;
4032        }
4033        return PackageManager.SIGNATURE_NO_MATCH;
4034    }
4035
4036    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4037        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4038        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4039    }
4040
4041    private int compareSignaturesRecover(PackageSignatures existingSigs,
4042            PackageParser.Package scannedPkg) {
4043        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4044            return PackageManager.SIGNATURE_NO_MATCH;
4045        }
4046
4047        String msg = null;
4048        try {
4049            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4050                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4051                        + scannedPkg.packageName);
4052                return PackageManager.SIGNATURE_MATCH;
4053            }
4054        } catch (CertificateException e) {
4055            msg = e.getMessage();
4056        }
4057
4058        logCriticalInfo(Log.INFO,
4059                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4060        return PackageManager.SIGNATURE_NO_MATCH;
4061    }
4062
4063    @Override
4064    public String[] getPackagesForUid(int uid) {
4065        uid = UserHandle.getAppId(uid);
4066        // reader
4067        synchronized (mPackages) {
4068            Object obj = mSettings.getUserIdLPr(uid);
4069            if (obj instanceof SharedUserSetting) {
4070                final SharedUserSetting sus = (SharedUserSetting) obj;
4071                final int N = sus.packages.size();
4072                final String[] res = new String[N];
4073                final Iterator<PackageSetting> it = sus.packages.iterator();
4074                int i = 0;
4075                while (it.hasNext()) {
4076                    res[i++] = it.next().name;
4077                }
4078                return res;
4079            } else if (obj instanceof PackageSetting) {
4080                final PackageSetting ps = (PackageSetting) obj;
4081                return new String[] { ps.name };
4082            }
4083        }
4084        return null;
4085    }
4086
4087    @Override
4088    public String getNameForUid(int uid) {
4089        // reader
4090        synchronized (mPackages) {
4091            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4092            if (obj instanceof SharedUserSetting) {
4093                final SharedUserSetting sus = (SharedUserSetting) obj;
4094                return sus.name + ":" + sus.userId;
4095            } else if (obj instanceof PackageSetting) {
4096                final PackageSetting ps = (PackageSetting) obj;
4097                return ps.name;
4098            }
4099        }
4100        return null;
4101    }
4102
4103    @Override
4104    public int getUidForSharedUser(String sharedUserName) {
4105        if(sharedUserName == null) {
4106            return -1;
4107        }
4108        // reader
4109        synchronized (mPackages) {
4110            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4111            if (suid == null) {
4112                return -1;
4113            }
4114            return suid.userId;
4115        }
4116    }
4117
4118    @Override
4119    public int getFlagsForUid(int uid) {
4120        synchronized (mPackages) {
4121            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4122            if (obj instanceof SharedUserSetting) {
4123                final SharedUserSetting sus = (SharedUserSetting) obj;
4124                return sus.pkgFlags;
4125            } else if (obj instanceof PackageSetting) {
4126                final PackageSetting ps = (PackageSetting) obj;
4127                return ps.pkgFlags;
4128            }
4129        }
4130        return 0;
4131    }
4132
4133    @Override
4134    public int getPrivateFlagsForUid(int uid) {
4135        synchronized (mPackages) {
4136            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4137            if (obj instanceof SharedUserSetting) {
4138                final SharedUserSetting sus = (SharedUserSetting) obj;
4139                return sus.pkgPrivateFlags;
4140            } else if (obj instanceof PackageSetting) {
4141                final PackageSetting ps = (PackageSetting) obj;
4142                return ps.pkgPrivateFlags;
4143            }
4144        }
4145        return 0;
4146    }
4147
4148    @Override
4149    public boolean isUidPrivileged(int uid) {
4150        uid = UserHandle.getAppId(uid);
4151        // reader
4152        synchronized (mPackages) {
4153            Object obj = mSettings.getUserIdLPr(uid);
4154            if (obj instanceof SharedUserSetting) {
4155                final SharedUserSetting sus = (SharedUserSetting) obj;
4156                final Iterator<PackageSetting> it = sus.packages.iterator();
4157                while (it.hasNext()) {
4158                    if (it.next().isPrivileged()) {
4159                        return true;
4160                    }
4161                }
4162            } else if (obj instanceof PackageSetting) {
4163                final PackageSetting ps = (PackageSetting) obj;
4164                return ps.isPrivileged();
4165            }
4166        }
4167        return false;
4168    }
4169
4170    @Override
4171    public String[] getAppOpPermissionPackages(String permissionName) {
4172        synchronized (mPackages) {
4173            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4174            if (pkgs == null) {
4175                return null;
4176            }
4177            return pkgs.toArray(new String[pkgs.size()]);
4178        }
4179    }
4180
4181    @Override
4182    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4183            int flags, int userId) {
4184        if (!sUserManager.exists(userId)) return null;
4185        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4186        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4187        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4188    }
4189
4190    @Override
4191    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4192            IntentFilter filter, int match, ComponentName activity) {
4193        final int userId = UserHandle.getCallingUserId();
4194        if (DEBUG_PREFERRED) {
4195            Log.v(TAG, "setLastChosenActivity intent=" + intent
4196                + " resolvedType=" + resolvedType
4197                + " flags=" + flags
4198                + " filter=" + filter
4199                + " match=" + match
4200                + " activity=" + activity);
4201            filter.dump(new PrintStreamPrinter(System.out), "    ");
4202        }
4203        intent.setComponent(null);
4204        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4205        // Find any earlier preferred or last chosen entries and nuke them
4206        findPreferredActivity(intent, resolvedType,
4207                flags, query, 0, false, true, false, userId);
4208        // Add the new activity as the last chosen for this filter
4209        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4210                "Setting last chosen");
4211    }
4212
4213    @Override
4214    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4215        final int userId = UserHandle.getCallingUserId();
4216        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4217        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4218        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4219                false, false, false, userId);
4220    }
4221
4222    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4223            int flags, List<ResolveInfo> query, int userId) {
4224        if (query != null) {
4225            final int N = query.size();
4226            if (N == 1) {
4227                return query.get(0);
4228            } else if (N > 1) {
4229                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4230                // If there is more than one activity with the same priority,
4231                // then let the user decide between them.
4232                ResolveInfo r0 = query.get(0);
4233                ResolveInfo r1 = query.get(1);
4234                if (DEBUG_INTENT_MATCHING || debug) {
4235                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4236                            + r1.activityInfo.name + "=" + r1.priority);
4237                }
4238                // If the first activity has a higher priority, or a different
4239                // default, then it is always desireable to pick it.
4240                if (r0.priority != r1.priority
4241                        || r0.preferredOrder != r1.preferredOrder
4242                        || r0.isDefault != r1.isDefault) {
4243                    return query.get(0);
4244                }
4245                // If we have saved a preference for a preferred activity for
4246                // this Intent, use that.
4247                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4248                        flags, query, r0.priority, true, false, debug, userId);
4249                if (ri != null) {
4250                    return ri;
4251                }
4252                if (userId != 0) {
4253                    ri = new ResolveInfo(mResolveInfo);
4254                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4255                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4256                            ri.activityInfo.applicationInfo);
4257                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4258                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4259                    return ri;
4260                }
4261                return mResolveInfo;
4262            }
4263        }
4264        return null;
4265    }
4266
4267    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4268            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4269        final int N = query.size();
4270        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4271                .get(userId);
4272        // Get the list of persistent preferred activities that handle the intent
4273        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4274        List<PersistentPreferredActivity> pprefs = ppir != null
4275                ? ppir.queryIntent(intent, resolvedType,
4276                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4277                : null;
4278        if (pprefs != null && pprefs.size() > 0) {
4279            final int M = pprefs.size();
4280            for (int i=0; i<M; i++) {
4281                final PersistentPreferredActivity ppa = pprefs.get(i);
4282                if (DEBUG_PREFERRED || debug) {
4283                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4284                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4285                            + "\n  component=" + ppa.mComponent);
4286                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4287                }
4288                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4289                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4290                if (DEBUG_PREFERRED || debug) {
4291                    Slog.v(TAG, "Found persistent preferred activity:");
4292                    if (ai != null) {
4293                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4294                    } else {
4295                        Slog.v(TAG, "  null");
4296                    }
4297                }
4298                if (ai == null) {
4299                    // This previously registered persistent preferred activity
4300                    // component is no longer known. Ignore it and do NOT remove it.
4301                    continue;
4302                }
4303                for (int j=0; j<N; j++) {
4304                    final ResolveInfo ri = query.get(j);
4305                    if (!ri.activityInfo.applicationInfo.packageName
4306                            .equals(ai.applicationInfo.packageName)) {
4307                        continue;
4308                    }
4309                    if (!ri.activityInfo.name.equals(ai.name)) {
4310                        continue;
4311                    }
4312                    //  Found a persistent preference that can handle the intent.
4313                    if (DEBUG_PREFERRED || debug) {
4314                        Slog.v(TAG, "Returning persistent preferred activity: " +
4315                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4316                    }
4317                    return ri;
4318                }
4319            }
4320        }
4321        return null;
4322    }
4323
4324    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4325            List<ResolveInfo> query, int priority, boolean always,
4326            boolean removeMatches, boolean debug, int userId) {
4327        if (!sUserManager.exists(userId)) return null;
4328        // writer
4329        synchronized (mPackages) {
4330            if (intent.getSelector() != null) {
4331                intent = intent.getSelector();
4332            }
4333            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4334
4335            // Try to find a matching persistent preferred activity.
4336            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4337                    debug, userId);
4338
4339            // If a persistent preferred activity matched, use it.
4340            if (pri != null) {
4341                return pri;
4342            }
4343
4344            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4345            // Get the list of preferred activities that handle the intent
4346            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4347            List<PreferredActivity> prefs = pir != null
4348                    ? pir.queryIntent(intent, resolvedType,
4349                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4350                    : null;
4351            if (prefs != null && prefs.size() > 0) {
4352                boolean changed = false;
4353                try {
4354                    // First figure out how good the original match set is.
4355                    // We will only allow preferred activities that came
4356                    // from the same match quality.
4357                    int match = 0;
4358
4359                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4360
4361                    final int N = query.size();
4362                    for (int j=0; j<N; j++) {
4363                        final ResolveInfo ri = query.get(j);
4364                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4365                                + ": 0x" + Integer.toHexString(match));
4366                        if (ri.match > match) {
4367                            match = ri.match;
4368                        }
4369                    }
4370
4371                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4372                            + Integer.toHexString(match));
4373
4374                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4375                    final int M = prefs.size();
4376                    for (int i=0; i<M; i++) {
4377                        final PreferredActivity pa = prefs.get(i);
4378                        if (DEBUG_PREFERRED || debug) {
4379                            Slog.v(TAG, "Checking PreferredActivity ds="
4380                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4381                                    + "\n  component=" + pa.mPref.mComponent);
4382                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4383                        }
4384                        if (pa.mPref.mMatch != match) {
4385                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4386                                    + Integer.toHexString(pa.mPref.mMatch));
4387                            continue;
4388                        }
4389                        // If it's not an "always" type preferred activity and that's what we're
4390                        // looking for, skip it.
4391                        if (always && !pa.mPref.mAlways) {
4392                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4393                            continue;
4394                        }
4395                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4396                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4397                        if (DEBUG_PREFERRED || debug) {
4398                            Slog.v(TAG, "Found preferred activity:");
4399                            if (ai != null) {
4400                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4401                            } else {
4402                                Slog.v(TAG, "  null");
4403                            }
4404                        }
4405                        if (ai == null) {
4406                            // This previously registered preferred activity
4407                            // component is no longer known.  Most likely an update
4408                            // to the app was installed and in the new version this
4409                            // component no longer exists.  Clean it up by removing
4410                            // it from the preferred activities list, and skip it.
4411                            Slog.w(TAG, "Removing dangling preferred activity: "
4412                                    + pa.mPref.mComponent);
4413                            pir.removeFilter(pa);
4414                            changed = true;
4415                            continue;
4416                        }
4417                        for (int j=0; j<N; j++) {
4418                            final ResolveInfo ri = query.get(j);
4419                            if (!ri.activityInfo.applicationInfo.packageName
4420                                    .equals(ai.applicationInfo.packageName)) {
4421                                continue;
4422                            }
4423                            if (!ri.activityInfo.name.equals(ai.name)) {
4424                                continue;
4425                            }
4426
4427                            if (removeMatches) {
4428                                pir.removeFilter(pa);
4429                                changed = true;
4430                                if (DEBUG_PREFERRED) {
4431                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4432                                }
4433                                break;
4434                            }
4435
4436                            // Okay we found a previously set preferred or last chosen app.
4437                            // If the result set is different from when this
4438                            // was created, we need to clear it and re-ask the
4439                            // user their preference, if we're looking for an "always" type entry.
4440                            if (always && !pa.mPref.sameSet(query)) {
4441                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4442                                        + intent + " type " + resolvedType);
4443                                if (DEBUG_PREFERRED) {
4444                                    Slog.v(TAG, "Removing preferred activity since set changed "
4445                                            + pa.mPref.mComponent);
4446                                }
4447                                pir.removeFilter(pa);
4448                                // Re-add the filter as a "last chosen" entry (!always)
4449                                PreferredActivity lastChosen = new PreferredActivity(
4450                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4451                                pir.addFilter(lastChosen);
4452                                changed = true;
4453                                return null;
4454                            }
4455
4456                            // Yay! Either the set matched or we're looking for the last chosen
4457                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4458                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4459                            return ri;
4460                        }
4461                    }
4462                } finally {
4463                    if (changed) {
4464                        if (DEBUG_PREFERRED) {
4465                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4466                        }
4467                        scheduleWritePackageRestrictionsLocked(userId);
4468                    }
4469                }
4470            }
4471        }
4472        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4473        return null;
4474    }
4475
4476    /*
4477     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4478     */
4479    @Override
4480    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4481            int targetUserId) {
4482        mContext.enforceCallingOrSelfPermission(
4483                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4484        List<CrossProfileIntentFilter> matches =
4485                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4486        if (matches != null) {
4487            int size = matches.size();
4488            for (int i = 0; i < size; i++) {
4489                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4490            }
4491        }
4492        if (hasWebURI(intent)) {
4493            // cross-profile app linking works only towards the parent.
4494            final UserInfo parent = getProfileParent(sourceUserId);
4495            synchronized(mPackages) {
4496                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4497                        intent, resolvedType, 0, sourceUserId, parent.id);
4498                return xpDomainInfo != null;
4499            }
4500        }
4501        return false;
4502    }
4503
4504    private UserInfo getProfileParent(int userId) {
4505        final long identity = Binder.clearCallingIdentity();
4506        try {
4507            return sUserManager.getProfileParent(userId);
4508        } finally {
4509            Binder.restoreCallingIdentity(identity);
4510        }
4511    }
4512
4513    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4514            String resolvedType, int userId) {
4515        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4516        if (resolver != null) {
4517            return resolver.queryIntent(intent, resolvedType, false, userId);
4518        }
4519        return null;
4520    }
4521
4522    @Override
4523    public List<ResolveInfo> queryIntentActivities(Intent intent,
4524            String resolvedType, int flags, int userId) {
4525        if (!sUserManager.exists(userId)) return Collections.emptyList();
4526        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4527        ComponentName comp = intent.getComponent();
4528        if (comp == null) {
4529            if (intent.getSelector() != null) {
4530                intent = intent.getSelector();
4531                comp = intent.getComponent();
4532            }
4533        }
4534
4535        if (comp != null) {
4536            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4537            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4538            if (ai != null) {
4539                final ResolveInfo ri = new ResolveInfo();
4540                ri.activityInfo = ai;
4541                list.add(ri);
4542            }
4543            return list;
4544        }
4545
4546        // reader
4547        synchronized (mPackages) {
4548            final String pkgName = intent.getPackage();
4549            if (pkgName == null) {
4550                List<CrossProfileIntentFilter> matchingFilters =
4551                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4552                // Check for results that need to skip the current profile.
4553                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4554                        resolvedType, flags, userId);
4555                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4556                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4557                    result.add(xpResolveInfo);
4558                    return filterIfNotPrimaryUser(result, userId);
4559                }
4560
4561                // Check for results in the current profile.
4562                List<ResolveInfo> result = mActivities.queryIntent(
4563                        intent, resolvedType, flags, userId);
4564
4565                // Check for cross profile results.
4566                xpResolveInfo = queryCrossProfileIntents(
4567                        matchingFilters, intent, resolvedType, flags, userId);
4568                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4569                    result.add(xpResolveInfo);
4570                    Collections.sort(result, mResolvePrioritySorter);
4571                }
4572                result = filterIfNotPrimaryUser(result, userId);
4573                if (hasWebURI(intent)) {
4574                    CrossProfileDomainInfo xpDomainInfo = null;
4575                    final UserInfo parent = getProfileParent(userId);
4576                    if (parent != null) {
4577                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4578                                flags, userId, parent.id);
4579                    }
4580                    if (xpDomainInfo != null) {
4581                        if (xpResolveInfo != null) {
4582                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4583                            // in the result.
4584                            result.remove(xpResolveInfo);
4585                        }
4586                        if (result.size() == 0) {
4587                            result.add(xpDomainInfo.resolveInfo);
4588                            return result;
4589                        }
4590                    } else if (result.size() <= 1) {
4591                        return result;
4592                    }
4593                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4594                            xpDomainInfo, userId);
4595                    Collections.sort(result, mResolvePrioritySorter);
4596                }
4597                return result;
4598            }
4599            final PackageParser.Package pkg = mPackages.get(pkgName);
4600            if (pkg != null) {
4601                return filterIfNotPrimaryUser(
4602                        mActivities.queryIntentForPackage(
4603                                intent, resolvedType, flags, pkg.activities, userId),
4604                        userId);
4605            }
4606            return new ArrayList<ResolveInfo>();
4607        }
4608    }
4609
4610    private static class CrossProfileDomainInfo {
4611        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4612        ResolveInfo resolveInfo;
4613        /* Best domain verification status of the activities found in the other profile */
4614        int bestDomainVerificationStatus;
4615    }
4616
4617    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4618            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4619        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4620                sourceUserId)) {
4621            return null;
4622        }
4623        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4624                resolvedType, flags, parentUserId);
4625
4626        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4627            return null;
4628        }
4629        CrossProfileDomainInfo result = null;
4630        int size = resultTargetUser.size();
4631        for (int i = 0; i < size; i++) {
4632            ResolveInfo riTargetUser = resultTargetUser.get(i);
4633            // Intent filter verification is only for filters that specify a host. So don't return
4634            // those that handle all web uris.
4635            if (riTargetUser.handleAllWebDataURI) {
4636                continue;
4637            }
4638            String packageName = riTargetUser.activityInfo.packageName;
4639            PackageSetting ps = mSettings.mPackages.get(packageName);
4640            if (ps == null) {
4641                continue;
4642            }
4643            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4644            int status = (int)(verificationState >> 32);
4645            if (result == null) {
4646                result = new CrossProfileDomainInfo();
4647                result.resolveInfo =
4648                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4649                result.bestDomainVerificationStatus = status;
4650            } else {
4651                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4652                        result.bestDomainVerificationStatus);
4653            }
4654        }
4655        // Don't consider matches with status NEVER across profiles.
4656        if (result != null && result.bestDomainVerificationStatus
4657                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4658            return null;
4659        }
4660        return result;
4661    }
4662
4663    /**
4664     * Verification statuses are ordered from the worse to the best, except for
4665     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4666     */
4667    private int bestDomainVerificationStatus(int status1, int status2) {
4668        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4669            return status2;
4670        }
4671        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4672            return status1;
4673        }
4674        return (int) MathUtils.max(status1, status2);
4675    }
4676
4677    private boolean isUserEnabled(int userId) {
4678        long callingId = Binder.clearCallingIdentity();
4679        try {
4680            UserInfo userInfo = sUserManager.getUserInfo(userId);
4681            return userInfo != null && userInfo.isEnabled();
4682        } finally {
4683            Binder.restoreCallingIdentity(callingId);
4684        }
4685    }
4686
4687    /**
4688     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4689     *
4690     * @return filtered list
4691     */
4692    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4693        if (userId == UserHandle.USER_OWNER) {
4694            return resolveInfos;
4695        }
4696        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4697            ResolveInfo info = resolveInfos.get(i);
4698            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4699                resolveInfos.remove(i);
4700            }
4701        }
4702        return resolveInfos;
4703    }
4704
4705    private static boolean hasWebURI(Intent intent) {
4706        if (intent.getData() == null) {
4707            return false;
4708        }
4709        final String scheme = intent.getScheme();
4710        if (TextUtils.isEmpty(scheme)) {
4711            return false;
4712        }
4713        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4714    }
4715
4716    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4717            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4718            int userId) {
4719        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4720
4721        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4722            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4723                    candidates.size());
4724        }
4725
4726        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4727        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4728        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4729        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4730        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4731        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4732
4733        synchronized (mPackages) {
4734            final int count = candidates.size();
4735            // First, try to use linked apps. Partition the candidates into four lists:
4736            // one for the final results, one for the "do not use ever", one for "undefined status"
4737            // and finally one for "browser app type".
4738            for (int n=0; n<count; n++) {
4739                ResolveInfo info = candidates.get(n);
4740                String packageName = info.activityInfo.packageName;
4741                PackageSetting ps = mSettings.mPackages.get(packageName);
4742                if (ps != null) {
4743                    // Add to the special match all list (Browser use case)
4744                    if (info.handleAllWebDataURI) {
4745                        matchAllList.add(info);
4746                        continue;
4747                    }
4748                    // Try to get the status from User settings first
4749                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4750                    int status = (int)(packedStatus >> 32);
4751                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4752                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4753                        if (DEBUG_DOMAIN_VERIFICATION) {
4754                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4755                                    + " : linkgen=" + linkGeneration);
4756                        }
4757                        // Use link-enabled generation as preferredOrder, i.e.
4758                        // prefer newly-enabled over earlier-enabled.
4759                        info.preferredOrder = linkGeneration;
4760                        alwaysList.add(info);
4761                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4762                        if (DEBUG_DOMAIN_VERIFICATION) {
4763                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4764                        }
4765                        neverList.add(info);
4766                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4767                        if (DEBUG_DOMAIN_VERIFICATION) {
4768                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4769                        }
4770                        alwaysAskList.add(info);
4771                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4772                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4773                        if (DEBUG_DOMAIN_VERIFICATION) {
4774                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4775                        }
4776                        undefinedList.add(info);
4777                    }
4778                }
4779            }
4780
4781            // We'll want to include browser possibilities in a few cases
4782            boolean includeBrowser = false;
4783
4784            // First try to add the "always" resolution(s) for the current user, if any
4785            if (alwaysList.size() > 0) {
4786                result.addAll(alwaysList);
4787            // if there is an "always" for the parent user, add it.
4788            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4789                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4790                result.add(xpDomainInfo.resolveInfo);
4791            } else {
4792                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4793                result.addAll(undefinedList);
4794                if (xpDomainInfo != null && (
4795                        xpDomainInfo.bestDomainVerificationStatus
4796                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4797                        || xpDomainInfo.bestDomainVerificationStatus
4798                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4799                    result.add(xpDomainInfo.resolveInfo);
4800                }
4801                includeBrowser = true;
4802            }
4803
4804            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4805            // If there were 'always' entries their preferred order has been set, so we also
4806            // back that off to make the alternatives equivalent
4807            if (alwaysAskList.size() > 0) {
4808                for (ResolveInfo i : result) {
4809                    i.preferredOrder = 0;
4810                }
4811                result.addAll(alwaysAskList);
4812                includeBrowser = true;
4813            }
4814
4815            if (includeBrowser) {
4816                // Also add browsers (all of them or only the default one)
4817                if (DEBUG_DOMAIN_VERIFICATION) {
4818                    Slog.v(TAG, "   ...including browsers in candidate set");
4819                }
4820                if ((matchFlags & MATCH_ALL) != 0) {
4821                    result.addAll(matchAllList);
4822                } else {
4823                    // Browser/generic handling case.  If there's a default browser, go straight
4824                    // to that (but only if there is no other higher-priority match).
4825                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4826                    int maxMatchPrio = 0;
4827                    ResolveInfo defaultBrowserMatch = null;
4828                    final int numCandidates = matchAllList.size();
4829                    for (int n = 0; n < numCandidates; n++) {
4830                        ResolveInfo info = matchAllList.get(n);
4831                        // track the highest overall match priority...
4832                        if (info.priority > maxMatchPrio) {
4833                            maxMatchPrio = info.priority;
4834                        }
4835                        // ...and the highest-priority default browser match
4836                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4837                            if (defaultBrowserMatch == null
4838                                    || (defaultBrowserMatch.priority < info.priority)) {
4839                                if (debug) {
4840                                    Slog.v(TAG, "Considering default browser match " + info);
4841                                }
4842                                defaultBrowserMatch = info;
4843                            }
4844                        }
4845                    }
4846                    if (defaultBrowserMatch != null
4847                            && defaultBrowserMatch.priority >= maxMatchPrio
4848                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4849                    {
4850                        if (debug) {
4851                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4852                        }
4853                        result.add(defaultBrowserMatch);
4854                    } else {
4855                        result.addAll(matchAllList);
4856                    }
4857                }
4858
4859                // If there is nothing selected, add all candidates and remove the ones that the user
4860                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4861                if (result.size() == 0) {
4862                    result.addAll(candidates);
4863                    result.removeAll(neverList);
4864                }
4865            }
4866        }
4867        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4868            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4869                    result.size());
4870            for (ResolveInfo info : result) {
4871                Slog.v(TAG, "  + " + info.activityInfo);
4872            }
4873        }
4874        return result;
4875    }
4876
4877    // Returns a packed value as a long:
4878    //
4879    // high 'int'-sized word: link status: undefined/ask/never/always.
4880    // low 'int'-sized word: relative priority among 'always' results.
4881    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4882        long result = ps.getDomainVerificationStatusForUser(userId);
4883        // if none available, get the master status
4884        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4885            if (ps.getIntentFilterVerificationInfo() != null) {
4886                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4887            }
4888        }
4889        return result;
4890    }
4891
4892    private ResolveInfo querySkipCurrentProfileIntents(
4893            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4894            int flags, int sourceUserId) {
4895        if (matchingFilters != null) {
4896            int size = matchingFilters.size();
4897            for (int i = 0; i < size; i ++) {
4898                CrossProfileIntentFilter filter = matchingFilters.get(i);
4899                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4900                    // Checking if there are activities in the target user that can handle the
4901                    // intent.
4902                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4903                            flags, sourceUserId);
4904                    if (resolveInfo != null) {
4905                        return resolveInfo;
4906                    }
4907                }
4908            }
4909        }
4910        return null;
4911    }
4912
4913    // Return matching ResolveInfo if any for skip current profile intent filters.
4914    private ResolveInfo queryCrossProfileIntents(
4915            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4916            int flags, int sourceUserId) {
4917        if (matchingFilters != null) {
4918            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4919            // match the same intent. For performance reasons, it is better not to
4920            // run queryIntent twice for the same userId
4921            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4922            int size = matchingFilters.size();
4923            for (int i = 0; i < size; i++) {
4924                CrossProfileIntentFilter filter = matchingFilters.get(i);
4925                int targetUserId = filter.getTargetUserId();
4926                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4927                        && !alreadyTriedUserIds.get(targetUserId)) {
4928                    // Checking if there are activities in the target user that can handle the
4929                    // intent.
4930                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4931                            flags, sourceUserId);
4932                    if (resolveInfo != null) return resolveInfo;
4933                    alreadyTriedUserIds.put(targetUserId, true);
4934                }
4935            }
4936        }
4937        return null;
4938    }
4939
4940    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4941            String resolvedType, int flags, int sourceUserId) {
4942        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4943                resolvedType, flags, filter.getTargetUserId());
4944        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4945            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4946        }
4947        return null;
4948    }
4949
4950    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4951            int sourceUserId, int targetUserId) {
4952        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4953        String className;
4954        if (targetUserId == UserHandle.USER_OWNER) {
4955            className = FORWARD_INTENT_TO_USER_OWNER;
4956        } else {
4957            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4958        }
4959        ComponentName forwardingActivityComponentName = new ComponentName(
4960                mAndroidApplication.packageName, className);
4961        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4962                sourceUserId);
4963        if (targetUserId == UserHandle.USER_OWNER) {
4964            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4965            forwardingResolveInfo.noResourceId = true;
4966        }
4967        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4968        forwardingResolveInfo.priority = 0;
4969        forwardingResolveInfo.preferredOrder = 0;
4970        forwardingResolveInfo.match = 0;
4971        forwardingResolveInfo.isDefault = true;
4972        forwardingResolveInfo.filter = filter;
4973        forwardingResolveInfo.targetUserId = targetUserId;
4974        return forwardingResolveInfo;
4975    }
4976
4977    @Override
4978    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4979            Intent[] specifics, String[] specificTypes, Intent intent,
4980            String resolvedType, int flags, int userId) {
4981        if (!sUserManager.exists(userId)) return Collections.emptyList();
4982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4983                false, "query intent activity options");
4984        final String resultsAction = intent.getAction();
4985
4986        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4987                | PackageManager.GET_RESOLVED_FILTER, userId);
4988
4989        if (DEBUG_INTENT_MATCHING) {
4990            Log.v(TAG, "Query " + intent + ": " + results);
4991        }
4992
4993        int specificsPos = 0;
4994        int N;
4995
4996        // todo: note that the algorithm used here is O(N^2).  This
4997        // isn't a problem in our current environment, but if we start running
4998        // into situations where we have more than 5 or 10 matches then this
4999        // should probably be changed to something smarter...
5000
5001        // First we go through and resolve each of the specific items
5002        // that were supplied, taking care of removing any corresponding
5003        // duplicate items in the generic resolve list.
5004        if (specifics != null) {
5005            for (int i=0; i<specifics.length; i++) {
5006                final Intent sintent = specifics[i];
5007                if (sintent == null) {
5008                    continue;
5009                }
5010
5011                if (DEBUG_INTENT_MATCHING) {
5012                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5013                }
5014
5015                String action = sintent.getAction();
5016                if (resultsAction != null && resultsAction.equals(action)) {
5017                    // If this action was explicitly requested, then don't
5018                    // remove things that have it.
5019                    action = null;
5020                }
5021
5022                ResolveInfo ri = null;
5023                ActivityInfo ai = null;
5024
5025                ComponentName comp = sintent.getComponent();
5026                if (comp == null) {
5027                    ri = resolveIntent(
5028                        sintent,
5029                        specificTypes != null ? specificTypes[i] : null,
5030                            flags, userId);
5031                    if (ri == null) {
5032                        continue;
5033                    }
5034                    if (ri == mResolveInfo) {
5035                        // ACK!  Must do something better with this.
5036                    }
5037                    ai = ri.activityInfo;
5038                    comp = new ComponentName(ai.applicationInfo.packageName,
5039                            ai.name);
5040                } else {
5041                    ai = getActivityInfo(comp, flags, userId);
5042                    if (ai == null) {
5043                        continue;
5044                    }
5045                }
5046
5047                // Look for any generic query activities that are duplicates
5048                // of this specific one, and remove them from the results.
5049                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5050                N = results.size();
5051                int j;
5052                for (j=specificsPos; j<N; j++) {
5053                    ResolveInfo sri = results.get(j);
5054                    if ((sri.activityInfo.name.equals(comp.getClassName())
5055                            && sri.activityInfo.applicationInfo.packageName.equals(
5056                                    comp.getPackageName()))
5057                        || (action != null && sri.filter.matchAction(action))) {
5058                        results.remove(j);
5059                        if (DEBUG_INTENT_MATCHING) Log.v(
5060                            TAG, "Removing duplicate item from " + j
5061                            + " due to specific " + specificsPos);
5062                        if (ri == null) {
5063                            ri = sri;
5064                        }
5065                        j--;
5066                        N--;
5067                    }
5068                }
5069
5070                // Add this specific item to its proper place.
5071                if (ri == null) {
5072                    ri = new ResolveInfo();
5073                    ri.activityInfo = ai;
5074                }
5075                results.add(specificsPos, ri);
5076                ri.specificIndex = i;
5077                specificsPos++;
5078            }
5079        }
5080
5081        // Now we go through the remaining generic results and remove any
5082        // duplicate actions that are found here.
5083        N = results.size();
5084        for (int i=specificsPos; i<N-1; i++) {
5085            final ResolveInfo rii = results.get(i);
5086            if (rii.filter == null) {
5087                continue;
5088            }
5089
5090            // Iterate over all of the actions of this result's intent
5091            // filter...  typically this should be just one.
5092            final Iterator<String> it = rii.filter.actionsIterator();
5093            if (it == null) {
5094                continue;
5095            }
5096            while (it.hasNext()) {
5097                final String action = it.next();
5098                if (resultsAction != null && resultsAction.equals(action)) {
5099                    // If this action was explicitly requested, then don't
5100                    // remove things that have it.
5101                    continue;
5102                }
5103                for (int j=i+1; j<N; j++) {
5104                    final ResolveInfo rij = results.get(j);
5105                    if (rij.filter != null && rij.filter.hasAction(action)) {
5106                        results.remove(j);
5107                        if (DEBUG_INTENT_MATCHING) Log.v(
5108                            TAG, "Removing duplicate item from " + j
5109                            + " due to action " + action + " at " + i);
5110                        j--;
5111                        N--;
5112                    }
5113                }
5114            }
5115
5116            // If the caller didn't request filter information, drop it now
5117            // so we don't have to marshall/unmarshall it.
5118            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5119                rii.filter = null;
5120            }
5121        }
5122
5123        // Filter out the caller activity if so requested.
5124        if (caller != null) {
5125            N = results.size();
5126            for (int i=0; i<N; i++) {
5127                ActivityInfo ainfo = results.get(i).activityInfo;
5128                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5129                        && caller.getClassName().equals(ainfo.name)) {
5130                    results.remove(i);
5131                    break;
5132                }
5133            }
5134        }
5135
5136        // If the caller didn't request filter information,
5137        // drop them now so we don't have to
5138        // marshall/unmarshall it.
5139        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5140            N = results.size();
5141            for (int i=0; i<N; i++) {
5142                results.get(i).filter = null;
5143            }
5144        }
5145
5146        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5147        return results;
5148    }
5149
5150    @Override
5151    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5152            int userId) {
5153        if (!sUserManager.exists(userId)) return Collections.emptyList();
5154        ComponentName comp = intent.getComponent();
5155        if (comp == null) {
5156            if (intent.getSelector() != null) {
5157                intent = intent.getSelector();
5158                comp = intent.getComponent();
5159            }
5160        }
5161        if (comp != null) {
5162            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5163            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5164            if (ai != null) {
5165                ResolveInfo ri = new ResolveInfo();
5166                ri.activityInfo = ai;
5167                list.add(ri);
5168            }
5169            return list;
5170        }
5171
5172        // reader
5173        synchronized (mPackages) {
5174            String pkgName = intent.getPackage();
5175            if (pkgName == null) {
5176                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5177            }
5178            final PackageParser.Package pkg = mPackages.get(pkgName);
5179            if (pkg != null) {
5180                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5181                        userId);
5182            }
5183            return null;
5184        }
5185    }
5186
5187    @Override
5188    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5189        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5190        if (!sUserManager.exists(userId)) return null;
5191        if (query != null) {
5192            if (query.size() >= 1) {
5193                // If there is more than one service with the same priority,
5194                // just arbitrarily pick the first one.
5195                return query.get(0);
5196            }
5197        }
5198        return null;
5199    }
5200
5201    @Override
5202    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5203            int userId) {
5204        if (!sUserManager.exists(userId)) return Collections.emptyList();
5205        ComponentName comp = intent.getComponent();
5206        if (comp == null) {
5207            if (intent.getSelector() != null) {
5208                intent = intent.getSelector();
5209                comp = intent.getComponent();
5210            }
5211        }
5212        if (comp != null) {
5213            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5214            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5215            if (si != null) {
5216                final ResolveInfo ri = new ResolveInfo();
5217                ri.serviceInfo = si;
5218                list.add(ri);
5219            }
5220            return list;
5221        }
5222
5223        // reader
5224        synchronized (mPackages) {
5225            String pkgName = intent.getPackage();
5226            if (pkgName == null) {
5227                return mServices.queryIntent(intent, resolvedType, flags, userId);
5228            }
5229            final PackageParser.Package pkg = mPackages.get(pkgName);
5230            if (pkg != null) {
5231                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5232                        userId);
5233            }
5234            return null;
5235        }
5236    }
5237
5238    @Override
5239    public List<ResolveInfo> queryIntentContentProviders(
5240            Intent intent, String resolvedType, int flags, int userId) {
5241        if (!sUserManager.exists(userId)) return Collections.emptyList();
5242        ComponentName comp = intent.getComponent();
5243        if (comp == null) {
5244            if (intent.getSelector() != null) {
5245                intent = intent.getSelector();
5246                comp = intent.getComponent();
5247            }
5248        }
5249        if (comp != null) {
5250            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5251            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5252            if (pi != null) {
5253                final ResolveInfo ri = new ResolveInfo();
5254                ri.providerInfo = pi;
5255                list.add(ri);
5256            }
5257            return list;
5258        }
5259
5260        // reader
5261        synchronized (mPackages) {
5262            String pkgName = intent.getPackage();
5263            if (pkgName == null) {
5264                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5265            }
5266            final PackageParser.Package pkg = mPackages.get(pkgName);
5267            if (pkg != null) {
5268                return mProviders.queryIntentForPackage(
5269                        intent, resolvedType, flags, pkg.providers, userId);
5270            }
5271            return null;
5272        }
5273    }
5274
5275    @Override
5276    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5277        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5278
5279        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5280
5281        // writer
5282        synchronized (mPackages) {
5283            ArrayList<PackageInfo> list;
5284            if (listUninstalled) {
5285                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5286                for (PackageSetting ps : mSettings.mPackages.values()) {
5287                    PackageInfo pi;
5288                    if (ps.pkg != null) {
5289                        pi = generatePackageInfo(ps.pkg, flags, userId);
5290                    } else {
5291                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5292                    }
5293                    if (pi != null) {
5294                        list.add(pi);
5295                    }
5296                }
5297            } else {
5298                list = new ArrayList<PackageInfo>(mPackages.size());
5299                for (PackageParser.Package p : mPackages.values()) {
5300                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5301                    if (pi != null) {
5302                        list.add(pi);
5303                    }
5304                }
5305            }
5306
5307            return new ParceledListSlice<PackageInfo>(list);
5308        }
5309    }
5310
5311    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5312            String[] permissions, boolean[] tmp, int flags, int userId) {
5313        int numMatch = 0;
5314        final PermissionsState permissionsState = ps.getPermissionsState();
5315        for (int i=0; i<permissions.length; i++) {
5316            final String permission = permissions[i];
5317            if (permissionsState.hasPermission(permission, userId)) {
5318                tmp[i] = true;
5319                numMatch++;
5320            } else {
5321                tmp[i] = false;
5322            }
5323        }
5324        if (numMatch == 0) {
5325            return;
5326        }
5327        PackageInfo pi;
5328        if (ps.pkg != null) {
5329            pi = generatePackageInfo(ps.pkg, flags, userId);
5330        } else {
5331            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5332        }
5333        // The above might return null in cases of uninstalled apps or install-state
5334        // skew across users/profiles.
5335        if (pi != null) {
5336            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5337                if (numMatch == permissions.length) {
5338                    pi.requestedPermissions = permissions;
5339                } else {
5340                    pi.requestedPermissions = new String[numMatch];
5341                    numMatch = 0;
5342                    for (int i=0; i<permissions.length; i++) {
5343                        if (tmp[i]) {
5344                            pi.requestedPermissions[numMatch] = permissions[i];
5345                            numMatch++;
5346                        }
5347                    }
5348                }
5349            }
5350            list.add(pi);
5351        }
5352    }
5353
5354    @Override
5355    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5356            String[] permissions, int flags, int userId) {
5357        if (!sUserManager.exists(userId)) return null;
5358        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5359
5360        // writer
5361        synchronized (mPackages) {
5362            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5363            boolean[] tmpBools = new boolean[permissions.length];
5364            if (listUninstalled) {
5365                for (PackageSetting ps : mSettings.mPackages.values()) {
5366                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5367                }
5368            } else {
5369                for (PackageParser.Package pkg : mPackages.values()) {
5370                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5371                    if (ps != null) {
5372                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5373                                userId);
5374                    }
5375                }
5376            }
5377
5378            return new ParceledListSlice<PackageInfo>(list);
5379        }
5380    }
5381
5382    @Override
5383    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5384        if (!sUserManager.exists(userId)) return null;
5385        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5386
5387        // writer
5388        synchronized (mPackages) {
5389            ArrayList<ApplicationInfo> list;
5390            if (listUninstalled) {
5391                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5392                for (PackageSetting ps : mSettings.mPackages.values()) {
5393                    ApplicationInfo ai;
5394                    if (ps.pkg != null) {
5395                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5396                                ps.readUserState(userId), userId);
5397                    } else {
5398                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5399                    }
5400                    if (ai != null) {
5401                        list.add(ai);
5402                    }
5403                }
5404            } else {
5405                list = new ArrayList<ApplicationInfo>(mPackages.size());
5406                for (PackageParser.Package p : mPackages.values()) {
5407                    if (p.mExtras != null) {
5408                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5409                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5410                        if (ai != null) {
5411                            list.add(ai);
5412                        }
5413                    }
5414                }
5415            }
5416
5417            return new ParceledListSlice<ApplicationInfo>(list);
5418        }
5419    }
5420
5421    public List<ApplicationInfo> getPersistentApplications(int flags) {
5422        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5423
5424        // reader
5425        synchronized (mPackages) {
5426            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5427            final int userId = UserHandle.getCallingUserId();
5428            while (i.hasNext()) {
5429                final PackageParser.Package p = i.next();
5430                if (p.applicationInfo != null
5431                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5432                        && (!mSafeMode || isSystemApp(p))) {
5433                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5434                    if (ps != null) {
5435                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5436                                ps.readUserState(userId), userId);
5437                        if (ai != null) {
5438                            finalList.add(ai);
5439                        }
5440                    }
5441                }
5442            }
5443        }
5444
5445        return finalList;
5446    }
5447
5448    @Override
5449    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5450        if (!sUserManager.exists(userId)) return null;
5451        // reader
5452        synchronized (mPackages) {
5453            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5454            PackageSetting ps = provider != null
5455                    ? mSettings.mPackages.get(provider.owner.packageName)
5456                    : null;
5457            return ps != null
5458                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5459                    && (!mSafeMode || (provider.info.applicationInfo.flags
5460                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5461                    ? PackageParser.generateProviderInfo(provider, flags,
5462                            ps.readUserState(userId), userId)
5463                    : null;
5464        }
5465    }
5466
5467    /**
5468     * @deprecated
5469     */
5470    @Deprecated
5471    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5472        // reader
5473        synchronized (mPackages) {
5474            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5475                    .entrySet().iterator();
5476            final int userId = UserHandle.getCallingUserId();
5477            while (i.hasNext()) {
5478                Map.Entry<String, PackageParser.Provider> entry = i.next();
5479                PackageParser.Provider p = entry.getValue();
5480                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5481
5482                if (ps != null && p.syncable
5483                        && (!mSafeMode || (p.info.applicationInfo.flags
5484                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5485                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5486                            ps.readUserState(userId), userId);
5487                    if (info != null) {
5488                        outNames.add(entry.getKey());
5489                        outInfo.add(info);
5490                    }
5491                }
5492            }
5493        }
5494    }
5495
5496    @Override
5497    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5498            int uid, int flags) {
5499        ArrayList<ProviderInfo> finalList = null;
5500        // reader
5501        synchronized (mPackages) {
5502            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5503            final int userId = processName != null ?
5504                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5505            while (i.hasNext()) {
5506                final PackageParser.Provider p = i.next();
5507                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5508                if (ps != null && p.info.authority != null
5509                        && (processName == null
5510                                || (p.info.processName.equals(processName)
5511                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5512                        && mSettings.isEnabledLPr(p.info, flags, userId)
5513                        && (!mSafeMode
5514                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5515                    if (finalList == null) {
5516                        finalList = new ArrayList<ProviderInfo>(3);
5517                    }
5518                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5519                            ps.readUserState(userId), userId);
5520                    if (info != null) {
5521                        finalList.add(info);
5522                    }
5523                }
5524            }
5525        }
5526
5527        if (finalList != null) {
5528            Collections.sort(finalList, mProviderInitOrderSorter);
5529            return new ParceledListSlice<ProviderInfo>(finalList);
5530        }
5531
5532        return null;
5533    }
5534
5535    @Override
5536    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5537            int flags) {
5538        // reader
5539        synchronized (mPackages) {
5540            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5541            return PackageParser.generateInstrumentationInfo(i, flags);
5542        }
5543    }
5544
5545    @Override
5546    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5547            int flags) {
5548        ArrayList<InstrumentationInfo> finalList =
5549            new ArrayList<InstrumentationInfo>();
5550
5551        // reader
5552        synchronized (mPackages) {
5553            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5554            while (i.hasNext()) {
5555                final PackageParser.Instrumentation p = i.next();
5556                if (targetPackage == null
5557                        || targetPackage.equals(p.info.targetPackage)) {
5558                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5559                            flags);
5560                    if (ii != null) {
5561                        finalList.add(ii);
5562                    }
5563                }
5564            }
5565        }
5566
5567        return finalList;
5568    }
5569
5570    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5571        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5572        if (overlays == null) {
5573            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5574            return;
5575        }
5576        for (PackageParser.Package opkg : overlays.values()) {
5577            // Not much to do if idmap fails: we already logged the error
5578            // and we certainly don't want to abort installation of pkg simply
5579            // because an overlay didn't fit properly. For these reasons,
5580            // ignore the return value of createIdmapForPackagePairLI.
5581            createIdmapForPackagePairLI(pkg, opkg);
5582        }
5583    }
5584
5585    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5586            PackageParser.Package opkg) {
5587        if (!opkg.mTrustedOverlay) {
5588            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5589                    opkg.baseCodePath + ": overlay not trusted");
5590            return false;
5591        }
5592        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5593        if (overlaySet == null) {
5594            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5595                    opkg.baseCodePath + " but target package has no known overlays");
5596            return false;
5597        }
5598        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5599        // TODO: generate idmap for split APKs
5600        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5601            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5602                    + opkg.baseCodePath);
5603            return false;
5604        }
5605        PackageParser.Package[] overlayArray =
5606            overlaySet.values().toArray(new PackageParser.Package[0]);
5607        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5608            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5609                return p1.mOverlayPriority - p2.mOverlayPriority;
5610            }
5611        };
5612        Arrays.sort(overlayArray, cmp);
5613
5614        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5615        int i = 0;
5616        for (PackageParser.Package p : overlayArray) {
5617            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5618        }
5619        return true;
5620    }
5621
5622    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5623        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5624        try {
5625            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5626        } finally {
5627            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5628        }
5629    }
5630
5631    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5632        final File[] files = dir.listFiles();
5633        if (ArrayUtils.isEmpty(files)) {
5634            Log.d(TAG, "No files in app dir " + dir);
5635            return;
5636        }
5637
5638        if (DEBUG_PACKAGE_SCANNING) {
5639            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5640                    + " flags=0x" + Integer.toHexString(parseFlags));
5641        }
5642
5643        for (File file : files) {
5644            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5645                    && !PackageInstallerService.isStageName(file.getName());
5646            if (!isPackage) {
5647                // Ignore entries which are not packages
5648                continue;
5649            }
5650            try {
5651                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5652                        scanFlags, currentTime, null);
5653            } catch (PackageManagerException e) {
5654                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5655
5656                // Delete invalid userdata apps
5657                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5658                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5659                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5660                    if (file.isDirectory()) {
5661                        mInstaller.rmPackageDir(file.getAbsolutePath());
5662                    } else {
5663                        file.delete();
5664                    }
5665                }
5666            }
5667        }
5668    }
5669
5670    private static File getSettingsProblemFile() {
5671        File dataDir = Environment.getDataDirectory();
5672        File systemDir = new File(dataDir, "system");
5673        File fname = new File(systemDir, "uiderrors.txt");
5674        return fname;
5675    }
5676
5677    static void reportSettingsProblem(int priority, String msg) {
5678        logCriticalInfo(priority, msg);
5679    }
5680
5681    static void logCriticalInfo(int priority, String msg) {
5682        Slog.println(priority, TAG, msg);
5683        EventLogTags.writePmCriticalInfo(msg);
5684        try {
5685            File fname = getSettingsProblemFile();
5686            FileOutputStream out = new FileOutputStream(fname, true);
5687            PrintWriter pw = new FastPrintWriter(out);
5688            SimpleDateFormat formatter = new SimpleDateFormat();
5689            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5690            pw.println(dateString + ": " + msg);
5691            pw.close();
5692            FileUtils.setPermissions(
5693                    fname.toString(),
5694                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5695                    -1, -1);
5696        } catch (java.io.IOException e) {
5697        }
5698    }
5699
5700    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5701            PackageParser.Package pkg, File srcFile, int parseFlags)
5702            throws PackageManagerException {
5703        if (ps != null
5704                && ps.codePath.equals(srcFile)
5705                && ps.timeStamp == srcFile.lastModified()
5706                && !isCompatSignatureUpdateNeeded(pkg)
5707                && !isRecoverSignatureUpdateNeeded(pkg)) {
5708            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5709            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5710            ArraySet<PublicKey> signingKs;
5711            synchronized (mPackages) {
5712                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5713            }
5714            if (ps.signatures.mSignatures != null
5715                    && ps.signatures.mSignatures.length != 0
5716                    && signingKs != null) {
5717                // Optimization: reuse the existing cached certificates
5718                // if the package appears to be unchanged.
5719                pkg.mSignatures = ps.signatures.mSignatures;
5720                pkg.mSigningKeys = signingKs;
5721                return;
5722            }
5723
5724            Slog.w(TAG, "PackageSetting for " + ps.name
5725                    + " is missing signatures.  Collecting certs again to recover them.");
5726        } else {
5727            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5728        }
5729
5730        try {
5731            pp.collectCertificates(pkg, parseFlags);
5732            pp.collectManifestDigest(pkg);
5733        } catch (PackageParserException e) {
5734            throw PackageManagerException.from(e);
5735        }
5736    }
5737
5738    /**
5739     *  Traces a package scan.
5740     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5741     */
5742    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5743            long currentTime, UserHandle user) throws PackageManagerException {
5744        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5745        try {
5746            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5747        } finally {
5748            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5749        }
5750    }
5751
5752    /**
5753     *  Scans a package and returns the newly parsed package.
5754     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5755     */
5756    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5757            long currentTime, UserHandle user) throws PackageManagerException {
5758        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5759        parseFlags |= mDefParseFlags;
5760        PackageParser pp = new PackageParser();
5761        pp.setSeparateProcesses(mSeparateProcesses);
5762        pp.setOnlyCoreApps(mOnlyCore);
5763        pp.setDisplayMetrics(mMetrics);
5764
5765        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5766            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5767        }
5768
5769        final PackageParser.Package pkg;
5770        try {
5771            pkg = pp.parsePackage(scanFile, parseFlags);
5772        } catch (PackageParserException e) {
5773            throw PackageManagerException.from(e);
5774        }
5775
5776        PackageSetting ps = null;
5777        PackageSetting updatedPkg;
5778        // reader
5779        synchronized (mPackages) {
5780            // Look to see if we already know about this package.
5781            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5782            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5783                // This package has been renamed to its original name.  Let's
5784                // use that.
5785                ps = mSettings.peekPackageLPr(oldName);
5786            }
5787            // If there was no original package, see one for the real package name.
5788            if (ps == null) {
5789                ps = mSettings.peekPackageLPr(pkg.packageName);
5790            }
5791            // Check to see if this package could be hiding/updating a system
5792            // package.  Must look for it either under the original or real
5793            // package name depending on our state.
5794            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5795            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5796        }
5797        boolean updatedPkgBetter = false;
5798        // First check if this is a system package that may involve an update
5799        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5800            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5801            // it needs to drop FLAG_PRIVILEGED.
5802            if (locationIsPrivileged(scanFile)) {
5803                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5804            } else {
5805                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5806            }
5807
5808            if (ps != null && !ps.codePath.equals(scanFile)) {
5809                // The path has changed from what was last scanned...  check the
5810                // version of the new path against what we have stored to determine
5811                // what to do.
5812                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5813                if (pkg.mVersionCode <= ps.versionCode) {
5814                    // The system package has been updated and the code path does not match
5815                    // Ignore entry. Skip it.
5816                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5817                            + " ignored: updated version " + ps.versionCode
5818                            + " better than this " + pkg.mVersionCode);
5819                    if (!updatedPkg.codePath.equals(scanFile)) {
5820                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5821                                + ps.name + " changing from " + updatedPkg.codePathString
5822                                + " to " + scanFile);
5823                        updatedPkg.codePath = scanFile;
5824                        updatedPkg.codePathString = scanFile.toString();
5825                        updatedPkg.resourcePath = scanFile;
5826                        updatedPkg.resourcePathString = scanFile.toString();
5827                    }
5828                    updatedPkg.pkg = pkg;
5829                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5830                            "Package " + ps.name + " at " + scanFile
5831                                    + " ignored: updated version " + ps.versionCode
5832                                    + " better than this " + pkg.mVersionCode);
5833                } else {
5834                    // The current app on the system partition is better than
5835                    // what we have updated to on the data partition; switch
5836                    // back to the system partition version.
5837                    // At this point, its safely assumed that package installation for
5838                    // apps in system partition will go through. If not there won't be a working
5839                    // version of the app
5840                    // writer
5841                    synchronized (mPackages) {
5842                        // Just remove the loaded entries from package lists.
5843                        mPackages.remove(ps.name);
5844                    }
5845
5846                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5847                            + " reverting from " + ps.codePathString
5848                            + ": new version " + pkg.mVersionCode
5849                            + " better than installed " + ps.versionCode);
5850
5851                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5852                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5853                    synchronized (mInstallLock) {
5854                        args.cleanUpResourcesLI();
5855                    }
5856                    synchronized (mPackages) {
5857                        mSettings.enableSystemPackageLPw(ps.name);
5858                    }
5859                    updatedPkgBetter = true;
5860                }
5861            }
5862        }
5863
5864        if (updatedPkg != null) {
5865            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5866            // initially
5867            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5868
5869            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5870            // flag set initially
5871            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5872                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5873            }
5874        }
5875
5876        // Verify certificates against what was last scanned
5877        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5878
5879        /*
5880         * A new system app appeared, but we already had a non-system one of the
5881         * same name installed earlier.
5882         */
5883        boolean shouldHideSystemApp = false;
5884        if (updatedPkg == null && ps != null
5885                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5886            /*
5887             * Check to make sure the signatures match first. If they don't,
5888             * wipe the installed application and its data.
5889             */
5890            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5891                    != PackageManager.SIGNATURE_MATCH) {
5892                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5893                        + " signatures don't match existing userdata copy; removing");
5894                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5895                ps = null;
5896            } else {
5897                /*
5898                 * If the newly-added system app is an older version than the
5899                 * already installed version, hide it. It will be scanned later
5900                 * and re-added like an update.
5901                 */
5902                if (pkg.mVersionCode <= ps.versionCode) {
5903                    shouldHideSystemApp = true;
5904                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5905                            + " but new version " + pkg.mVersionCode + " better than installed "
5906                            + ps.versionCode + "; hiding system");
5907                } else {
5908                    /*
5909                     * The newly found system app is a newer version that the
5910                     * one previously installed. Simply remove the
5911                     * already-installed application and replace it with our own
5912                     * while keeping the application data.
5913                     */
5914                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5915                            + " reverting from " + ps.codePathString + ": new version "
5916                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5917                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5918                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5919                    synchronized (mInstallLock) {
5920                        args.cleanUpResourcesLI();
5921                    }
5922                }
5923            }
5924        }
5925
5926        // The apk is forward locked (not public) if its code and resources
5927        // are kept in different files. (except for app in either system or
5928        // vendor path).
5929        // TODO grab this value from PackageSettings
5930        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5931            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5932                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5933            }
5934        }
5935
5936        // TODO: extend to support forward-locked splits
5937        String resourcePath = null;
5938        String baseResourcePath = null;
5939        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5940            if (ps != null && ps.resourcePathString != null) {
5941                resourcePath = ps.resourcePathString;
5942                baseResourcePath = ps.resourcePathString;
5943            } else {
5944                // Should not happen at all. Just log an error.
5945                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5946            }
5947        } else {
5948            resourcePath = pkg.codePath;
5949            baseResourcePath = pkg.baseCodePath;
5950        }
5951
5952        // Set application objects path explicitly.
5953        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5954        pkg.applicationInfo.setCodePath(pkg.codePath);
5955        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5956        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5957        pkg.applicationInfo.setResourcePath(resourcePath);
5958        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5959        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5960
5961        // Note that we invoke the following method only if we are about to unpack an application
5962        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5963                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5964
5965        /*
5966         * If the system app should be overridden by a previously installed
5967         * data, hide the system app now and let the /data/app scan pick it up
5968         * again.
5969         */
5970        if (shouldHideSystemApp) {
5971            synchronized (mPackages) {
5972                /*
5973                 * We have to grant systems permissions before we hide, because
5974                 * grantPermissions will assume the package update is trying to
5975                 * expand its permissions.
5976                 */
5977                grantPermissionsLPw(pkg, true, pkg.packageName);
5978                mSettings.disableSystemPackageLPw(pkg.packageName);
5979            }
5980        }
5981
5982        return scannedPkg;
5983    }
5984
5985    private static String fixProcessName(String defProcessName,
5986            String processName, int uid) {
5987        if (processName == null) {
5988            return defProcessName;
5989        }
5990        return processName;
5991    }
5992
5993    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5994            throws PackageManagerException {
5995        if (pkgSetting.signatures.mSignatures != null) {
5996            // Already existing package. Make sure signatures match
5997            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5998                    == PackageManager.SIGNATURE_MATCH;
5999            if (!match) {
6000                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6001                        == PackageManager.SIGNATURE_MATCH;
6002            }
6003            if (!match) {
6004                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6005                        == PackageManager.SIGNATURE_MATCH;
6006            }
6007            if (!match) {
6008                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6009                        + pkg.packageName + " signatures do not match the "
6010                        + "previously installed version; ignoring!");
6011            }
6012        }
6013
6014        // Check for shared user signatures
6015        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6016            // Already existing package. Make sure signatures match
6017            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6018                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6019            if (!match) {
6020                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6021                        == PackageManager.SIGNATURE_MATCH;
6022            }
6023            if (!match) {
6024                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6025                        == PackageManager.SIGNATURE_MATCH;
6026            }
6027            if (!match) {
6028                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6029                        "Package " + pkg.packageName
6030                        + " has no signatures that match those in shared user "
6031                        + pkgSetting.sharedUser.name + "; ignoring!");
6032            }
6033        }
6034    }
6035
6036    /**
6037     * Enforces that only the system UID or root's UID can call a method exposed
6038     * via Binder.
6039     *
6040     * @param message used as message if SecurityException is thrown
6041     * @throws SecurityException if the caller is not system or root
6042     */
6043    private static final void enforceSystemOrRoot(String message) {
6044        final int uid = Binder.getCallingUid();
6045        if (uid != Process.SYSTEM_UID && uid != 0) {
6046            throw new SecurityException(message);
6047        }
6048    }
6049
6050    @Override
6051    public void performBootDexOpt() {
6052        enforceSystemOrRoot("Only the system can request dexopt be performed");
6053
6054        // Before everything else, see whether we need to fstrim.
6055        try {
6056            IMountService ms = PackageHelper.getMountService();
6057            if (ms != null) {
6058                final boolean isUpgrade = isUpgrade();
6059                boolean doTrim = isUpgrade;
6060                if (doTrim) {
6061                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6062                } else {
6063                    final long interval = android.provider.Settings.Global.getLong(
6064                            mContext.getContentResolver(),
6065                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6066                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6067                    if (interval > 0) {
6068                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6069                        if (timeSinceLast > interval) {
6070                            doTrim = true;
6071                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6072                                    + "; running immediately");
6073                        }
6074                    }
6075                }
6076                if (doTrim) {
6077                    if (!isFirstBoot()) {
6078                        try {
6079                            ActivityManagerNative.getDefault().showBootMessage(
6080                                    mContext.getResources().getString(
6081                                            R.string.android_upgrading_fstrim), true);
6082                        } catch (RemoteException e) {
6083                        }
6084                    }
6085                    ms.runMaintenance();
6086                }
6087            } else {
6088                Slog.e(TAG, "Mount service unavailable!");
6089            }
6090        } catch (RemoteException e) {
6091            // Can't happen; MountService is local
6092        }
6093
6094        final ArraySet<PackageParser.Package> pkgs;
6095        synchronized (mPackages) {
6096            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6097        }
6098
6099        if (pkgs != null) {
6100            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6101            // in case the device runs out of space.
6102            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6103            // Give priority to core apps.
6104            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6105                PackageParser.Package pkg = it.next();
6106                if (pkg.coreApp) {
6107                    if (DEBUG_DEXOPT) {
6108                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6109                    }
6110                    sortedPkgs.add(pkg);
6111                    it.remove();
6112                }
6113            }
6114            // Give priority to system apps that listen for pre boot complete.
6115            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6116            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6117            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6118                PackageParser.Package pkg = it.next();
6119                if (pkgNames.contains(pkg.packageName)) {
6120                    if (DEBUG_DEXOPT) {
6121                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6122                    }
6123                    sortedPkgs.add(pkg);
6124                    it.remove();
6125                }
6126            }
6127            // Give priority to system apps.
6128            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6129                PackageParser.Package pkg = it.next();
6130                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6131                    if (DEBUG_DEXOPT) {
6132                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
6133                    }
6134                    sortedPkgs.add(pkg);
6135                    it.remove();
6136                }
6137            }
6138            // Give priority to updated system apps.
6139            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6140                PackageParser.Package pkg = it.next();
6141                if (pkg.isUpdatedSystemApp()) {
6142                    if (DEBUG_DEXOPT) {
6143                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
6144                    }
6145                    sortedPkgs.add(pkg);
6146                    it.remove();
6147                }
6148            }
6149            // Give priority to apps that listen for boot complete.
6150            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6151            pkgNames = getPackageNamesForIntent(intent);
6152            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6153                PackageParser.Package pkg = it.next();
6154                if (pkgNames.contains(pkg.packageName)) {
6155                    if (DEBUG_DEXOPT) {
6156                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6157                    }
6158                    sortedPkgs.add(pkg);
6159                    it.remove();
6160                }
6161            }
6162            // Filter out packages that aren't recently used.
6163            filterRecentlyUsedApps(pkgs);
6164            // Add all remaining apps.
6165            for (PackageParser.Package pkg : pkgs) {
6166                if (DEBUG_DEXOPT) {
6167                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6168                }
6169                sortedPkgs.add(pkg);
6170            }
6171
6172            // If we want to be lazy, filter everything that wasn't recently used.
6173            if (mLazyDexOpt) {
6174                filterRecentlyUsedApps(sortedPkgs);
6175            }
6176
6177            int i = 0;
6178            int total = sortedPkgs.size();
6179            File dataDir = Environment.getDataDirectory();
6180            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6181            if (lowThreshold == 0) {
6182                throw new IllegalStateException("Invalid low memory threshold");
6183            }
6184            for (PackageParser.Package pkg : sortedPkgs) {
6185                long usableSpace = dataDir.getUsableSpace();
6186                if (usableSpace < lowThreshold) {
6187                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6188                    break;
6189                }
6190                performBootDexOpt(pkg, ++i, total);
6191            }
6192        }
6193    }
6194
6195    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6196        // Filter out packages that aren't recently used.
6197        //
6198        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6199        // should do a full dexopt.
6200        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6201            int total = pkgs.size();
6202            int skipped = 0;
6203            long now = System.currentTimeMillis();
6204            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6205                PackageParser.Package pkg = i.next();
6206                long then = pkg.mLastPackageUsageTimeInMills;
6207                if (then + mDexOptLRUThresholdInMills < now) {
6208                    if (DEBUG_DEXOPT) {
6209                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6210                              ((then == 0) ? "never" : new Date(then)));
6211                    }
6212                    i.remove();
6213                    skipped++;
6214                }
6215            }
6216            if (DEBUG_DEXOPT) {
6217                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6218            }
6219        }
6220    }
6221
6222    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6223        List<ResolveInfo> ris = null;
6224        try {
6225            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6226                    intent, null, 0, UserHandle.USER_OWNER);
6227        } catch (RemoteException e) {
6228        }
6229        ArraySet<String> pkgNames = new ArraySet<String>();
6230        if (ris != null) {
6231            for (ResolveInfo ri : ris) {
6232                pkgNames.add(ri.activityInfo.packageName);
6233            }
6234        }
6235        return pkgNames;
6236    }
6237
6238    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6239        if (DEBUG_DEXOPT) {
6240            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6241        }
6242        if (!isFirstBoot()) {
6243            try {
6244                ActivityManagerNative.getDefault().showBootMessage(
6245                        mContext.getResources().getString(R.string.android_upgrading_apk,
6246                                curr, total), true);
6247            } catch (RemoteException e) {
6248            }
6249        }
6250        PackageParser.Package p = pkg;
6251        synchronized (mInstallLock) {
6252            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6253                    false /* force dex */, false /* defer */, true /* include dependencies */);
6254        }
6255    }
6256
6257    @Override
6258    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6259        return performDexOpt(packageName, instructionSet, false);
6260    }
6261
6262    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6263        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6264        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6265        if (!dexopt && !updateUsage) {
6266            // We aren't going to dexopt or update usage, so bail early.
6267            return false;
6268        }
6269        PackageParser.Package p;
6270        final String targetInstructionSet;
6271        synchronized (mPackages) {
6272            p = mPackages.get(packageName);
6273            if (p == null) {
6274                return false;
6275            }
6276            if (updateUsage) {
6277                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6278            }
6279            mPackageUsage.write(false);
6280            if (!dexopt) {
6281                // We aren't going to dexopt, so bail early.
6282                return false;
6283            }
6284
6285            targetInstructionSet = instructionSet != null ? instructionSet :
6286                    getPrimaryInstructionSet(p.applicationInfo);
6287            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6288                return false;
6289            }
6290        }
6291        long callingId = Binder.clearCallingIdentity();
6292        try {
6293            synchronized (mInstallLock) {
6294                final String[] instructionSets = new String[] { targetInstructionSet };
6295                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6296                        false /* forceDex */, false /* defer */, true /* inclDependencies */);
6297                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6298            }
6299        } finally {
6300            Binder.restoreCallingIdentity(callingId);
6301        }
6302    }
6303
6304    public ArraySet<String> getPackagesThatNeedDexOpt() {
6305        ArraySet<String> pkgs = null;
6306        synchronized (mPackages) {
6307            for (PackageParser.Package p : mPackages.values()) {
6308                if (DEBUG_DEXOPT) {
6309                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6310                }
6311                if (!p.mDexOptPerformed.isEmpty()) {
6312                    continue;
6313                }
6314                if (pkgs == null) {
6315                    pkgs = new ArraySet<String>();
6316                }
6317                pkgs.add(p.packageName);
6318            }
6319        }
6320        return pkgs;
6321    }
6322
6323    public void shutdown() {
6324        mPackageUsage.write(true);
6325    }
6326
6327    @Override
6328    public void forceDexOpt(String packageName) {
6329        enforceSystemOrRoot("forceDexOpt");
6330
6331        PackageParser.Package pkg;
6332        synchronized (mPackages) {
6333            pkg = mPackages.get(packageName);
6334            if (pkg == null) {
6335                throw new IllegalArgumentException("Missing package: " + packageName);
6336            }
6337        }
6338
6339        synchronized (mInstallLock) {
6340            final String[] instructionSets = new String[] {
6341                    getPrimaryInstructionSet(pkg.applicationInfo) };
6342            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6343                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6344            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6345                throw new IllegalStateException("Failed to dexopt: " + res);
6346            }
6347        }
6348    }
6349
6350    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6351        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6352            Slog.w(TAG, "Unable to update from " + oldPkg.name
6353                    + " to " + newPkg.packageName
6354                    + ": old package not in system partition");
6355            return false;
6356        } else if (mPackages.get(oldPkg.name) != null) {
6357            Slog.w(TAG, "Unable to update from " + oldPkg.name
6358                    + " to " + newPkg.packageName
6359                    + ": old package still exists");
6360            return false;
6361        }
6362        return true;
6363    }
6364
6365    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6366        int[] users = sUserManager.getUserIds();
6367        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6368        if (res < 0) {
6369            return res;
6370        }
6371        for (int user : users) {
6372            if (user != 0) {
6373                res = mInstaller.createUserData(volumeUuid, packageName,
6374                        UserHandle.getUid(user, uid), user, seinfo);
6375                if (res < 0) {
6376                    return res;
6377                }
6378            }
6379        }
6380        return res;
6381    }
6382
6383    private int removeDataDirsLI(String volumeUuid, String packageName) {
6384        int[] users = sUserManager.getUserIds();
6385        int res = 0;
6386        for (int user : users) {
6387            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6388            if (resInner < 0) {
6389                res = resInner;
6390            }
6391        }
6392
6393        return res;
6394    }
6395
6396    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6397        int[] users = sUserManager.getUserIds();
6398        int res = 0;
6399        for (int user : users) {
6400            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6401            if (resInner < 0) {
6402                res = resInner;
6403            }
6404        }
6405        return res;
6406    }
6407
6408    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6409            PackageParser.Package changingLib) {
6410        if (file.path != null) {
6411            usesLibraryFiles.add(file.path);
6412            return;
6413        }
6414        PackageParser.Package p = mPackages.get(file.apk);
6415        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6416            // If we are doing this while in the middle of updating a library apk,
6417            // then we need to make sure to use that new apk for determining the
6418            // dependencies here.  (We haven't yet finished committing the new apk
6419            // to the package manager state.)
6420            if (p == null || p.packageName.equals(changingLib.packageName)) {
6421                p = changingLib;
6422            }
6423        }
6424        if (p != null) {
6425            usesLibraryFiles.addAll(p.getAllCodePaths());
6426        }
6427    }
6428
6429    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6430            PackageParser.Package changingLib) throws PackageManagerException {
6431        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6432            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6433            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6434            for (int i=0; i<N; i++) {
6435                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6436                if (file == null) {
6437                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6438                            "Package " + pkg.packageName + " requires unavailable shared library "
6439                            + pkg.usesLibraries.get(i) + "; failing!");
6440                }
6441                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6442            }
6443            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6444            for (int i=0; i<N; i++) {
6445                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6446                if (file == null) {
6447                    Slog.w(TAG, "Package " + pkg.packageName
6448                            + " desires unavailable shared library "
6449                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6450                } else {
6451                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6452                }
6453            }
6454            N = usesLibraryFiles.size();
6455            if (N > 0) {
6456                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6457            } else {
6458                pkg.usesLibraryFiles = null;
6459            }
6460        }
6461    }
6462
6463    private static boolean hasString(List<String> list, List<String> which) {
6464        if (list == null) {
6465            return false;
6466        }
6467        for (int i=list.size()-1; i>=0; i--) {
6468            for (int j=which.size()-1; j>=0; j--) {
6469                if (which.get(j).equals(list.get(i))) {
6470                    return true;
6471                }
6472            }
6473        }
6474        return false;
6475    }
6476
6477    private void updateAllSharedLibrariesLPw() {
6478        for (PackageParser.Package pkg : mPackages.values()) {
6479            try {
6480                updateSharedLibrariesLPw(pkg, null);
6481            } catch (PackageManagerException e) {
6482                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6483            }
6484        }
6485    }
6486
6487    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6488            PackageParser.Package changingPkg) {
6489        ArrayList<PackageParser.Package> res = null;
6490        for (PackageParser.Package pkg : mPackages.values()) {
6491            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6492                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6493                if (res == null) {
6494                    res = new ArrayList<PackageParser.Package>();
6495                }
6496                res.add(pkg);
6497                try {
6498                    updateSharedLibrariesLPw(pkg, changingPkg);
6499                } catch (PackageManagerException e) {
6500                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6501                }
6502            }
6503        }
6504        return res;
6505    }
6506
6507    /**
6508     * Derive the value of the {@code cpuAbiOverride} based on the provided
6509     * value and an optional stored value from the package settings.
6510     */
6511    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6512        String cpuAbiOverride = null;
6513
6514        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6515            cpuAbiOverride = null;
6516        } else if (abiOverride != null) {
6517            cpuAbiOverride = abiOverride;
6518        } else if (settings != null) {
6519            cpuAbiOverride = settings.cpuAbiOverrideString;
6520        }
6521
6522        return cpuAbiOverride;
6523    }
6524
6525    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6526            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6527        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6528        try {
6529            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6530        } finally {
6531            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6532        }
6533    }
6534
6535    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6536            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6537        boolean success = false;
6538        try {
6539            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6540                    currentTime, user);
6541            success = true;
6542            return res;
6543        } finally {
6544            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6545                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6546            }
6547        }
6548    }
6549
6550    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6551            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6552        final File scanFile = new File(pkg.codePath);
6553        if (pkg.applicationInfo.getCodePath() == null ||
6554                pkg.applicationInfo.getResourcePath() == null) {
6555            // Bail out. The resource and code paths haven't been set.
6556            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6557                    "Code and resource paths haven't been set correctly");
6558        }
6559
6560        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6561            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6562        } else {
6563            // Only allow system apps to be flagged as core apps.
6564            pkg.coreApp = false;
6565        }
6566
6567        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6568            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6569        }
6570
6571        if (mCustomResolverComponentName != null &&
6572                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6573            setUpCustomResolverActivity(pkg);
6574        }
6575
6576        if (pkg.packageName.equals("android")) {
6577            synchronized (mPackages) {
6578                if (mAndroidApplication != null) {
6579                    Slog.w(TAG, "*************************************************");
6580                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6581                    Slog.w(TAG, " file=" + scanFile);
6582                    Slog.w(TAG, "*************************************************");
6583                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6584                            "Core android package being redefined.  Skipping.");
6585                }
6586
6587                // Set up information for our fall-back user intent resolution activity.
6588                mPlatformPackage = pkg;
6589                pkg.mVersionCode = mSdkVersion;
6590                mAndroidApplication = pkg.applicationInfo;
6591
6592                if (!mResolverReplaced) {
6593                    mResolveActivity.applicationInfo = mAndroidApplication;
6594                    mResolveActivity.name = ResolverActivity.class.getName();
6595                    mResolveActivity.packageName = mAndroidApplication.packageName;
6596                    mResolveActivity.processName = "system:ui";
6597                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6598                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6599                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6600                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6601                    mResolveActivity.exported = true;
6602                    mResolveActivity.enabled = true;
6603                    mResolveInfo.activityInfo = mResolveActivity;
6604                    mResolveInfo.priority = 0;
6605                    mResolveInfo.preferredOrder = 0;
6606                    mResolveInfo.match = 0;
6607                    mResolveComponentName = new ComponentName(
6608                            mAndroidApplication.packageName, mResolveActivity.name);
6609                }
6610            }
6611        }
6612
6613        if (DEBUG_PACKAGE_SCANNING) {
6614            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6615                Log.d(TAG, "Scanning package " + pkg.packageName);
6616        }
6617
6618        if (mPackages.containsKey(pkg.packageName)
6619                || mSharedLibraries.containsKey(pkg.packageName)) {
6620            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6621                    "Application package " + pkg.packageName
6622                    + " already installed.  Skipping duplicate.");
6623        }
6624
6625        // If we're only installing presumed-existing packages, require that the
6626        // scanned APK is both already known and at the path previously established
6627        // for it.  Previously unknown packages we pick up normally, but if we have an
6628        // a priori expectation about this package's install presence, enforce it.
6629        // With a singular exception for new system packages. When an OTA contains
6630        // a new system package, we allow the codepath to change from a system location
6631        // to the user-installed location. If we don't allow this change, any newer,
6632        // user-installed version of the application will be ignored.
6633        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6634            if (mExpectingBetter.containsKey(pkg.packageName)) {
6635                logCriticalInfo(Log.WARN,
6636                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6637            } else {
6638                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6639                if (known != null) {
6640                    if (DEBUG_PACKAGE_SCANNING) {
6641                        Log.d(TAG, "Examining " + pkg.codePath
6642                                + " and requiring known paths " + known.codePathString
6643                                + " & " + known.resourcePathString);
6644                    }
6645                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6646                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6647                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6648                                "Application package " + pkg.packageName
6649                                + " found at " + pkg.applicationInfo.getCodePath()
6650                                + " but expected at " + known.codePathString + "; ignoring.");
6651                    }
6652                }
6653            }
6654        }
6655
6656        // Initialize package source and resource directories
6657        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6658        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6659
6660        SharedUserSetting suid = null;
6661        PackageSetting pkgSetting = null;
6662
6663        if (!isSystemApp(pkg)) {
6664            // Only system apps can use these features.
6665            pkg.mOriginalPackages = null;
6666            pkg.mRealPackage = null;
6667            pkg.mAdoptPermissions = null;
6668        }
6669
6670        // writer
6671        synchronized (mPackages) {
6672            if (pkg.mSharedUserId != null) {
6673                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6674                if (suid == null) {
6675                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6676                            "Creating application package " + pkg.packageName
6677                            + " for shared user failed");
6678                }
6679                if (DEBUG_PACKAGE_SCANNING) {
6680                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6681                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6682                                + "): packages=" + suid.packages);
6683                }
6684            }
6685
6686            // Check if we are renaming from an original package name.
6687            PackageSetting origPackage = null;
6688            String realName = null;
6689            if (pkg.mOriginalPackages != null) {
6690                // This package may need to be renamed to a previously
6691                // installed name.  Let's check on that...
6692                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6693                if (pkg.mOriginalPackages.contains(renamed)) {
6694                    // This package had originally been installed as the
6695                    // original name, and we have already taken care of
6696                    // transitioning to the new one.  Just update the new
6697                    // one to continue using the old name.
6698                    realName = pkg.mRealPackage;
6699                    if (!pkg.packageName.equals(renamed)) {
6700                        // Callers into this function may have already taken
6701                        // care of renaming the package; only do it here if
6702                        // it is not already done.
6703                        pkg.setPackageName(renamed);
6704                    }
6705
6706                } else {
6707                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6708                        if ((origPackage = mSettings.peekPackageLPr(
6709                                pkg.mOriginalPackages.get(i))) != null) {
6710                            // We do have the package already installed under its
6711                            // original name...  should we use it?
6712                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6713                                // New package is not compatible with original.
6714                                origPackage = null;
6715                                continue;
6716                            } else if (origPackage.sharedUser != null) {
6717                                // Make sure uid is compatible between packages.
6718                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6719                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6720                                            + " to " + pkg.packageName + ": old uid "
6721                                            + origPackage.sharedUser.name
6722                                            + " differs from " + pkg.mSharedUserId);
6723                                    origPackage = null;
6724                                    continue;
6725                                }
6726                            } else {
6727                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6728                                        + pkg.packageName + " to old name " + origPackage.name);
6729                            }
6730                            break;
6731                        }
6732                    }
6733                }
6734            }
6735
6736            if (mTransferedPackages.contains(pkg.packageName)) {
6737                Slog.w(TAG, "Package " + pkg.packageName
6738                        + " was transferred to another, but its .apk remains");
6739            }
6740
6741            // Just create the setting, don't add it yet. For already existing packages
6742            // the PkgSetting exists already and doesn't have to be created.
6743            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6744                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6745                    pkg.applicationInfo.primaryCpuAbi,
6746                    pkg.applicationInfo.secondaryCpuAbi,
6747                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6748                    user, false);
6749            if (pkgSetting == null) {
6750                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6751                        "Creating application package " + pkg.packageName + " failed");
6752            }
6753
6754            if (pkgSetting.origPackage != null) {
6755                // If we are first transitioning from an original package,
6756                // fix up the new package's name now.  We need to do this after
6757                // looking up the package under its new name, so getPackageLP
6758                // can take care of fiddling things correctly.
6759                pkg.setPackageName(origPackage.name);
6760
6761                // File a report about this.
6762                String msg = "New package " + pkgSetting.realName
6763                        + " renamed to replace old package " + pkgSetting.name;
6764                reportSettingsProblem(Log.WARN, msg);
6765
6766                // Make a note of it.
6767                mTransferedPackages.add(origPackage.name);
6768
6769                // No longer need to retain this.
6770                pkgSetting.origPackage = null;
6771            }
6772
6773            if (realName != null) {
6774                // Make a note of it.
6775                mTransferedPackages.add(pkg.packageName);
6776            }
6777
6778            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6779                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6780            }
6781
6782            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6783                // Check all shared libraries and map to their actual file path.
6784                // We only do this here for apps not on a system dir, because those
6785                // are the only ones that can fail an install due to this.  We
6786                // will take care of the system apps by updating all of their
6787                // library paths after the scan is done.
6788                updateSharedLibrariesLPw(pkg, null);
6789            }
6790
6791            if (mFoundPolicyFile) {
6792                SELinuxMMAC.assignSeinfoValue(pkg);
6793            }
6794
6795            pkg.applicationInfo.uid = pkgSetting.appId;
6796            pkg.mExtras = pkgSetting;
6797            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6798                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6799                    // We just determined the app is signed correctly, so bring
6800                    // over the latest parsed certs.
6801                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6802                } else {
6803                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6804                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6805                                "Package " + pkg.packageName + " upgrade keys do not match the "
6806                                + "previously installed version");
6807                    } else {
6808                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6809                        String msg = "System package " + pkg.packageName
6810                            + " signature changed; retaining data.";
6811                        reportSettingsProblem(Log.WARN, msg);
6812                    }
6813                }
6814            } else {
6815                try {
6816                    verifySignaturesLP(pkgSetting, pkg);
6817                    // We just determined the app is signed correctly, so bring
6818                    // over the latest parsed certs.
6819                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6820                } catch (PackageManagerException e) {
6821                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6822                        throw e;
6823                    }
6824                    // The signature has changed, but this package is in the system
6825                    // image...  let's recover!
6826                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6827                    // However...  if this package is part of a shared user, but it
6828                    // doesn't match the signature of the shared user, let's fail.
6829                    // What this means is that you can't change the signatures
6830                    // associated with an overall shared user, which doesn't seem all
6831                    // that unreasonable.
6832                    if (pkgSetting.sharedUser != null) {
6833                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6834                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6835                            throw new PackageManagerException(
6836                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6837                                            "Signature mismatch for shared user : "
6838                                            + pkgSetting.sharedUser);
6839                        }
6840                    }
6841                    // File a report about this.
6842                    String msg = "System package " + pkg.packageName
6843                        + " signature changed; retaining data.";
6844                    reportSettingsProblem(Log.WARN, msg);
6845                }
6846            }
6847            // Verify that this new package doesn't have any content providers
6848            // that conflict with existing packages.  Only do this if the
6849            // package isn't already installed, since we don't want to break
6850            // things that are installed.
6851            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6852                final int N = pkg.providers.size();
6853                int i;
6854                for (i=0; i<N; i++) {
6855                    PackageParser.Provider p = pkg.providers.get(i);
6856                    if (p.info.authority != null) {
6857                        String names[] = p.info.authority.split(";");
6858                        for (int j = 0; j < names.length; j++) {
6859                            if (mProvidersByAuthority.containsKey(names[j])) {
6860                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6861                                final String otherPackageName =
6862                                        ((other != null && other.getComponentName() != null) ?
6863                                                other.getComponentName().getPackageName() : "?");
6864                                throw new PackageManagerException(
6865                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6866                                                "Can't install because provider name " + names[j]
6867                                                + " (in package " + pkg.applicationInfo.packageName
6868                                                + ") is already used by " + otherPackageName);
6869                            }
6870                        }
6871                    }
6872                }
6873            }
6874
6875            if (pkg.mAdoptPermissions != null) {
6876                // This package wants to adopt ownership of permissions from
6877                // another package.
6878                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6879                    final String origName = pkg.mAdoptPermissions.get(i);
6880                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6881                    if (orig != null) {
6882                        if (verifyPackageUpdateLPr(orig, pkg)) {
6883                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6884                                    + pkg.packageName);
6885                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6886                        }
6887                    }
6888                }
6889            }
6890        }
6891
6892        final String pkgName = pkg.packageName;
6893
6894        final long scanFileTime = scanFile.lastModified();
6895        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6896        pkg.applicationInfo.processName = fixProcessName(
6897                pkg.applicationInfo.packageName,
6898                pkg.applicationInfo.processName,
6899                pkg.applicationInfo.uid);
6900
6901        File dataPath;
6902        if (mPlatformPackage == pkg) {
6903            // The system package is special.
6904            dataPath = new File(Environment.getDataDirectory(), "system");
6905
6906            pkg.applicationInfo.dataDir = dataPath.getPath();
6907
6908        } else {
6909            // This is a normal package, need to make its data directory.
6910            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6911                    UserHandle.USER_OWNER, pkg.packageName);
6912
6913            boolean uidError = false;
6914            if (dataPath.exists()) {
6915                int currentUid = 0;
6916                try {
6917                    StructStat stat = Os.stat(dataPath.getPath());
6918                    currentUid = stat.st_uid;
6919                } catch (ErrnoException e) {
6920                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6921                }
6922
6923                // If we have mismatched owners for the data path, we have a problem.
6924                if (currentUid != pkg.applicationInfo.uid) {
6925                    boolean recovered = false;
6926                    if (currentUid == 0) {
6927                        // The directory somehow became owned by root.  Wow.
6928                        // This is probably because the system was stopped while
6929                        // installd was in the middle of messing with its libs
6930                        // directory.  Ask installd to fix that.
6931                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6932                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6933                        if (ret >= 0) {
6934                            recovered = true;
6935                            String msg = "Package " + pkg.packageName
6936                                    + " unexpectedly changed to uid 0; recovered to " +
6937                                    + pkg.applicationInfo.uid;
6938                            reportSettingsProblem(Log.WARN, msg);
6939                        }
6940                    }
6941                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6942                            || (scanFlags&SCAN_BOOTING) != 0)) {
6943                        // If this is a system app, we can at least delete its
6944                        // current data so the application will still work.
6945                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6946                        if (ret >= 0) {
6947                            // TODO: Kill the processes first
6948                            // Old data gone!
6949                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6950                                    ? "System package " : "Third party package ";
6951                            String msg = prefix + pkg.packageName
6952                                    + " has changed from uid: "
6953                                    + currentUid + " to "
6954                                    + pkg.applicationInfo.uid + "; old data erased";
6955                            reportSettingsProblem(Log.WARN, msg);
6956                            recovered = true;
6957
6958                            // And now re-install the app.
6959                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6960                                    pkg.applicationInfo.seinfo);
6961                            if (ret == -1) {
6962                                // Ack should not happen!
6963                                msg = prefix + pkg.packageName
6964                                        + " could not have data directory re-created after delete.";
6965                                reportSettingsProblem(Log.WARN, msg);
6966                                throw new PackageManagerException(
6967                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6968                            }
6969                        }
6970                        if (!recovered) {
6971                            mHasSystemUidErrors = true;
6972                        }
6973                    } else if (!recovered) {
6974                        // If we allow this install to proceed, we will be broken.
6975                        // Abort, abort!
6976                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6977                                "scanPackageLI");
6978                    }
6979                    if (!recovered) {
6980                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6981                            + pkg.applicationInfo.uid + "/fs_"
6982                            + currentUid;
6983                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6984                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6985                        String msg = "Package " + pkg.packageName
6986                                + " has mismatched uid: "
6987                                + currentUid + " on disk, "
6988                                + pkg.applicationInfo.uid + " in settings";
6989                        // writer
6990                        synchronized (mPackages) {
6991                            mSettings.mReadMessages.append(msg);
6992                            mSettings.mReadMessages.append('\n');
6993                            uidError = true;
6994                            if (!pkgSetting.uidError) {
6995                                reportSettingsProblem(Log.ERROR, msg);
6996                            }
6997                        }
6998                    }
6999                }
7000                pkg.applicationInfo.dataDir = dataPath.getPath();
7001                if (mShouldRestoreconData) {
7002                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7003                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7004                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7005                }
7006            } else {
7007                if (DEBUG_PACKAGE_SCANNING) {
7008                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7009                        Log.v(TAG, "Want this data dir: " + dataPath);
7010                }
7011                //invoke installer to do the actual installation
7012                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7013                        pkg.applicationInfo.seinfo);
7014                if (ret < 0) {
7015                    // Error from installer
7016                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7017                            "Unable to create data dirs [errorCode=" + ret + "]");
7018                }
7019
7020                if (dataPath.exists()) {
7021                    pkg.applicationInfo.dataDir = dataPath.getPath();
7022                } else {
7023                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7024                    pkg.applicationInfo.dataDir = null;
7025                }
7026            }
7027
7028            pkgSetting.uidError = uidError;
7029        }
7030
7031        final String path = scanFile.getPath();
7032        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7033
7034        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7035            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7036
7037            // Some system apps still use directory structure for native libraries
7038            // in which case we might end up not detecting abi solely based on apk
7039            // structure. Try to detect abi based on directory structure.
7040            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7041                    pkg.applicationInfo.primaryCpuAbi == null) {
7042                setBundledAppAbisAndRoots(pkg, pkgSetting);
7043                setNativeLibraryPaths(pkg);
7044            }
7045
7046        } else {
7047            if ((scanFlags & SCAN_MOVE) != 0) {
7048                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7049                // but we already have this packages package info in the PackageSetting. We just
7050                // use that and derive the native library path based on the new codepath.
7051                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7052                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7053            }
7054
7055            // Set native library paths again. For moves, the path will be updated based on the
7056            // ABIs we've determined above. For non-moves, the path will be updated based on the
7057            // ABIs we determined during compilation, but the path will depend on the final
7058            // package path (after the rename away from the stage path).
7059            setNativeLibraryPaths(pkg);
7060        }
7061
7062        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7063        final int[] userIds = sUserManager.getUserIds();
7064        synchronized (mInstallLock) {
7065            // Make sure all user data directories are ready to roll; we're okay
7066            // if they already exist
7067            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7068                for (int userId : userIds) {
7069                    if (userId != 0) {
7070                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7071                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7072                                pkg.applicationInfo.seinfo);
7073                    }
7074                }
7075            }
7076
7077            // Create a native library symlink only if we have native libraries
7078            // and if the native libraries are 32 bit libraries. We do not provide
7079            // this symlink for 64 bit libraries.
7080            if (pkg.applicationInfo.primaryCpuAbi != null &&
7081                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7082                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7083                try {
7084                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7085                    for (int userId : userIds) {
7086                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7087                                nativeLibPath, userId) < 0) {
7088                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7089                                    "Failed linking native library dir (user=" + userId + ")");
7090                        }
7091                    }
7092                } finally {
7093                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7094                }
7095            }
7096        }
7097
7098        // This is a special case for the "system" package, where the ABI is
7099        // dictated by the zygote configuration (and init.rc). We should keep track
7100        // of this ABI so that we can deal with "normal" applications that run under
7101        // the same UID correctly.
7102        if (mPlatformPackage == pkg) {
7103            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7104                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7105        }
7106
7107        // If there's a mismatch between the abi-override in the package setting
7108        // and the abiOverride specified for the install. Warn about this because we
7109        // would've already compiled the app without taking the package setting into
7110        // account.
7111        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7112            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7113                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7114                        " for package: " + pkg.packageName);
7115            }
7116        }
7117
7118        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7119        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7120        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7121
7122        // Copy the derived override back to the parsed package, so that we can
7123        // update the package settings accordingly.
7124        pkg.cpuAbiOverride = cpuAbiOverride;
7125
7126        if (DEBUG_ABI_SELECTION) {
7127            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7128                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7129                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7130        }
7131
7132        // Push the derived path down into PackageSettings so we know what to
7133        // clean up at uninstall time.
7134        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7135
7136        if (DEBUG_ABI_SELECTION) {
7137            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7138                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7139                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7140        }
7141
7142        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7143            // We don't do this here during boot because we can do it all
7144            // at once after scanning all existing packages.
7145            //
7146            // We also do this *before* we perform dexopt on this package, so that
7147            // we can avoid redundant dexopts, and also to make sure we've got the
7148            // code and package path correct.
7149            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7150                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
7151        }
7152
7153        if ((scanFlags & SCAN_NO_DEX) == 0) {
7154            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7155
7156            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7157                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
7158
7159            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7160            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7161                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7162            }
7163        }
7164        if (mFactoryTest && pkg.requestedPermissions.contains(
7165                android.Manifest.permission.FACTORY_TEST)) {
7166            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7167        }
7168
7169        ArrayList<PackageParser.Package> clientLibPkgs = null;
7170
7171        // writer
7172        synchronized (mPackages) {
7173            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7174                // Only system apps can add new shared libraries.
7175                if (pkg.libraryNames != null) {
7176                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7177                        String name = pkg.libraryNames.get(i);
7178                        boolean allowed = false;
7179                        if (pkg.isUpdatedSystemApp()) {
7180                            // New library entries can only be added through the
7181                            // system image.  This is important to get rid of a lot
7182                            // of nasty edge cases: for example if we allowed a non-
7183                            // system update of the app to add a library, then uninstalling
7184                            // the update would make the library go away, and assumptions
7185                            // we made such as through app install filtering would now
7186                            // have allowed apps on the device which aren't compatible
7187                            // with it.  Better to just have the restriction here, be
7188                            // conservative, and create many fewer cases that can negatively
7189                            // impact the user experience.
7190                            final PackageSetting sysPs = mSettings
7191                                    .getDisabledSystemPkgLPr(pkg.packageName);
7192                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7193                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7194                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7195                                        allowed = true;
7196                                        allowed = true;
7197                                        break;
7198                                    }
7199                                }
7200                            }
7201                        } else {
7202                            allowed = true;
7203                        }
7204                        if (allowed) {
7205                            if (!mSharedLibraries.containsKey(name)) {
7206                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7207                            } else if (!name.equals(pkg.packageName)) {
7208                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7209                                        + name + " already exists; skipping");
7210                            }
7211                        } else {
7212                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7213                                    + name + " that is not declared on system image; skipping");
7214                        }
7215                    }
7216                    if ((scanFlags&SCAN_BOOTING) == 0) {
7217                        // If we are not booting, we need to update any applications
7218                        // that are clients of our shared library.  If we are booting,
7219                        // this will all be done once the scan is complete.
7220                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7221                    }
7222                }
7223            }
7224        }
7225
7226        // We also need to dexopt any apps that are dependent on this library.  Note that
7227        // if these fail, we should abort the install since installing the library will
7228        // result in some apps being broken.
7229        if (clientLibPkgs != null) {
7230            if ((scanFlags & SCAN_NO_DEX) == 0) {
7231                for (int i = 0; i < clientLibPkgs.size(); i++) {
7232                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7233                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7234                            null /* instruction sets */, forceDex,
7235                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7236                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7237                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7238                                "scanPackageLI failed to dexopt clientLibPkgs");
7239                    }
7240                }
7241            }
7242        }
7243
7244        // Request the ActivityManager to kill the process(only for existing packages)
7245        // so that we do not end up in a confused state while the user is still using the older
7246        // version of the application while the new one gets installed.
7247        if ((scanFlags & SCAN_REPLACING) != 0) {
7248            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7249
7250            killApplication(pkg.applicationInfo.packageName,
7251                        pkg.applicationInfo.uid, "replace pkg");
7252
7253            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7254        }
7255
7256        // Also need to kill any apps that are dependent on the library.
7257        if (clientLibPkgs != null) {
7258            for (int i=0; i<clientLibPkgs.size(); i++) {
7259                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7260                killApplication(clientPkg.applicationInfo.packageName,
7261                        clientPkg.applicationInfo.uid, "update lib");
7262            }
7263        }
7264
7265        // Make sure we're not adding any bogus keyset info
7266        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7267        ksms.assertScannedPackageValid(pkg);
7268
7269        // writer
7270        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7271
7272        boolean createIdmapFailed = false;
7273        synchronized (mPackages) {
7274            // We don't expect installation to fail beyond this point
7275
7276            // Add the new setting to mSettings
7277            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7278            // Add the new setting to mPackages
7279            mPackages.put(pkg.applicationInfo.packageName, pkg);
7280            // Make sure we don't accidentally delete its data.
7281            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7282            while (iter.hasNext()) {
7283                PackageCleanItem item = iter.next();
7284                if (pkgName.equals(item.packageName)) {
7285                    iter.remove();
7286                }
7287            }
7288
7289            // Take care of first install / last update times.
7290            if (currentTime != 0) {
7291                if (pkgSetting.firstInstallTime == 0) {
7292                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7293                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7294                    pkgSetting.lastUpdateTime = currentTime;
7295                }
7296            } else if (pkgSetting.firstInstallTime == 0) {
7297                // We need *something*.  Take time time stamp of the file.
7298                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7299            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7300                if (scanFileTime != pkgSetting.timeStamp) {
7301                    // A package on the system image has changed; consider this
7302                    // to be an update.
7303                    pkgSetting.lastUpdateTime = scanFileTime;
7304                }
7305            }
7306
7307            // Add the package's KeySets to the global KeySetManagerService
7308            ksms.addScannedPackageLPw(pkg);
7309
7310            int N = pkg.providers.size();
7311            StringBuilder r = null;
7312            int i;
7313            for (i=0; i<N; i++) {
7314                PackageParser.Provider p = pkg.providers.get(i);
7315                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7316                        p.info.processName, pkg.applicationInfo.uid);
7317                mProviders.addProvider(p);
7318                p.syncable = p.info.isSyncable;
7319                if (p.info.authority != null) {
7320                    String names[] = p.info.authority.split(";");
7321                    p.info.authority = null;
7322                    for (int j = 0; j < names.length; j++) {
7323                        if (j == 1 && p.syncable) {
7324                            // We only want the first authority for a provider to possibly be
7325                            // syncable, so if we already added this provider using a different
7326                            // authority clear the syncable flag. We copy the provider before
7327                            // changing it because the mProviders object contains a reference
7328                            // to a provider that we don't want to change.
7329                            // Only do this for the second authority since the resulting provider
7330                            // object can be the same for all future authorities for this provider.
7331                            p = new PackageParser.Provider(p);
7332                            p.syncable = false;
7333                        }
7334                        if (!mProvidersByAuthority.containsKey(names[j])) {
7335                            mProvidersByAuthority.put(names[j], p);
7336                            if (p.info.authority == null) {
7337                                p.info.authority = names[j];
7338                            } else {
7339                                p.info.authority = p.info.authority + ";" + names[j];
7340                            }
7341                            if (DEBUG_PACKAGE_SCANNING) {
7342                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7343                                    Log.d(TAG, "Registered content provider: " + names[j]
7344                                            + ", className = " + p.info.name + ", isSyncable = "
7345                                            + p.info.isSyncable);
7346                            }
7347                        } else {
7348                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7349                            Slog.w(TAG, "Skipping provider name " + names[j] +
7350                                    " (in package " + pkg.applicationInfo.packageName +
7351                                    "): name already used by "
7352                                    + ((other != null && other.getComponentName() != null)
7353                                            ? other.getComponentName().getPackageName() : "?"));
7354                        }
7355                    }
7356                }
7357                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7358                    if (r == null) {
7359                        r = new StringBuilder(256);
7360                    } else {
7361                        r.append(' ');
7362                    }
7363                    r.append(p.info.name);
7364                }
7365            }
7366            if (r != null) {
7367                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7368            }
7369
7370            N = pkg.services.size();
7371            r = null;
7372            for (i=0; i<N; i++) {
7373                PackageParser.Service s = pkg.services.get(i);
7374                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7375                        s.info.processName, pkg.applicationInfo.uid);
7376                mServices.addService(s);
7377                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7378                    if (r == null) {
7379                        r = new StringBuilder(256);
7380                    } else {
7381                        r.append(' ');
7382                    }
7383                    r.append(s.info.name);
7384                }
7385            }
7386            if (r != null) {
7387                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7388            }
7389
7390            N = pkg.receivers.size();
7391            r = null;
7392            for (i=0; i<N; i++) {
7393                PackageParser.Activity a = pkg.receivers.get(i);
7394                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7395                        a.info.processName, pkg.applicationInfo.uid);
7396                mReceivers.addActivity(a, "receiver");
7397                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7398                    if (r == null) {
7399                        r = new StringBuilder(256);
7400                    } else {
7401                        r.append(' ');
7402                    }
7403                    r.append(a.info.name);
7404                }
7405            }
7406            if (r != null) {
7407                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7408            }
7409
7410            N = pkg.activities.size();
7411            r = null;
7412            for (i=0; i<N; i++) {
7413                PackageParser.Activity a = pkg.activities.get(i);
7414                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7415                        a.info.processName, pkg.applicationInfo.uid);
7416                mActivities.addActivity(a, "activity");
7417                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7418                    if (r == null) {
7419                        r = new StringBuilder(256);
7420                    } else {
7421                        r.append(' ');
7422                    }
7423                    r.append(a.info.name);
7424                }
7425            }
7426            if (r != null) {
7427                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7428            }
7429
7430            N = pkg.permissionGroups.size();
7431            r = null;
7432            for (i=0; i<N; i++) {
7433                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7434                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7435                if (cur == null) {
7436                    mPermissionGroups.put(pg.info.name, pg);
7437                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7438                        if (r == null) {
7439                            r = new StringBuilder(256);
7440                        } else {
7441                            r.append(' ');
7442                        }
7443                        r.append(pg.info.name);
7444                    }
7445                } else {
7446                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7447                            + pg.info.packageName + " ignored: original from "
7448                            + cur.info.packageName);
7449                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7450                        if (r == null) {
7451                            r = new StringBuilder(256);
7452                        } else {
7453                            r.append(' ');
7454                        }
7455                        r.append("DUP:");
7456                        r.append(pg.info.name);
7457                    }
7458                }
7459            }
7460            if (r != null) {
7461                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7462            }
7463
7464            N = pkg.permissions.size();
7465            r = null;
7466            for (i=0; i<N; i++) {
7467                PackageParser.Permission p = pkg.permissions.get(i);
7468
7469                // Assume by default that we did not install this permission into the system.
7470                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7471
7472                // Now that permission groups have a special meaning, we ignore permission
7473                // groups for legacy apps to prevent unexpected behavior. In particular,
7474                // permissions for one app being granted to someone just becuase they happen
7475                // to be in a group defined by another app (before this had no implications).
7476                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7477                    p.group = mPermissionGroups.get(p.info.group);
7478                    // Warn for a permission in an unknown group.
7479                    if (p.info.group != null && p.group == null) {
7480                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7481                                + p.info.packageName + " in an unknown group " + p.info.group);
7482                    }
7483                }
7484
7485                ArrayMap<String, BasePermission> permissionMap =
7486                        p.tree ? mSettings.mPermissionTrees
7487                                : mSettings.mPermissions;
7488                BasePermission bp = permissionMap.get(p.info.name);
7489
7490                // Allow system apps to redefine non-system permissions
7491                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7492                    final boolean currentOwnerIsSystem = (bp.perm != null
7493                            && isSystemApp(bp.perm.owner));
7494                    if (isSystemApp(p.owner)) {
7495                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7496                            // It's a built-in permission and no owner, take ownership now
7497                            bp.packageSetting = pkgSetting;
7498                            bp.perm = p;
7499                            bp.uid = pkg.applicationInfo.uid;
7500                            bp.sourcePackage = p.info.packageName;
7501                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7502                        } else if (!currentOwnerIsSystem) {
7503                            String msg = "New decl " + p.owner + " of permission  "
7504                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7505                            reportSettingsProblem(Log.WARN, msg);
7506                            bp = null;
7507                        }
7508                    }
7509                }
7510
7511                if (bp == null) {
7512                    bp = new BasePermission(p.info.name, p.info.packageName,
7513                            BasePermission.TYPE_NORMAL);
7514                    permissionMap.put(p.info.name, bp);
7515                }
7516
7517                if (bp.perm == null) {
7518                    if (bp.sourcePackage == null
7519                            || bp.sourcePackage.equals(p.info.packageName)) {
7520                        BasePermission tree = findPermissionTreeLP(p.info.name);
7521                        if (tree == null
7522                                || tree.sourcePackage.equals(p.info.packageName)) {
7523                            bp.packageSetting = pkgSetting;
7524                            bp.perm = p;
7525                            bp.uid = pkg.applicationInfo.uid;
7526                            bp.sourcePackage = p.info.packageName;
7527                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7528                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7529                                if (r == null) {
7530                                    r = new StringBuilder(256);
7531                                } else {
7532                                    r.append(' ');
7533                                }
7534                                r.append(p.info.name);
7535                            }
7536                        } else {
7537                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7538                                    + p.info.packageName + " ignored: base tree "
7539                                    + tree.name + " is from package "
7540                                    + tree.sourcePackage);
7541                        }
7542                    } else {
7543                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7544                                + p.info.packageName + " ignored: original from "
7545                                + bp.sourcePackage);
7546                    }
7547                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7548                    if (r == null) {
7549                        r = new StringBuilder(256);
7550                    } else {
7551                        r.append(' ');
7552                    }
7553                    r.append("DUP:");
7554                    r.append(p.info.name);
7555                }
7556                if (bp.perm == p) {
7557                    bp.protectionLevel = p.info.protectionLevel;
7558                }
7559            }
7560
7561            if (r != null) {
7562                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7563            }
7564
7565            N = pkg.instrumentation.size();
7566            r = null;
7567            for (i=0; i<N; i++) {
7568                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7569                a.info.packageName = pkg.applicationInfo.packageName;
7570                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7571                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7572                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7573                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7574                a.info.dataDir = pkg.applicationInfo.dataDir;
7575
7576                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7577                // need other information about the application, like the ABI and what not ?
7578                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7579                mInstrumentation.put(a.getComponentName(), a);
7580                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7581                    if (r == null) {
7582                        r = new StringBuilder(256);
7583                    } else {
7584                        r.append(' ');
7585                    }
7586                    r.append(a.info.name);
7587                }
7588            }
7589            if (r != null) {
7590                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7591            }
7592
7593            if (pkg.protectedBroadcasts != null) {
7594                N = pkg.protectedBroadcasts.size();
7595                for (i=0; i<N; i++) {
7596                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7597                }
7598            }
7599
7600            pkgSetting.setTimeStamp(scanFileTime);
7601
7602            // Create idmap files for pairs of (packages, overlay packages).
7603            // Note: "android", ie framework-res.apk, is handled by native layers.
7604            if (pkg.mOverlayTarget != null) {
7605                // This is an overlay package.
7606                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7607                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7608                        mOverlays.put(pkg.mOverlayTarget,
7609                                new ArrayMap<String, PackageParser.Package>());
7610                    }
7611                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7612                    map.put(pkg.packageName, pkg);
7613                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7614                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7615                        createIdmapFailed = true;
7616                    }
7617                }
7618            } else if (mOverlays.containsKey(pkg.packageName) &&
7619                    !pkg.packageName.equals("android")) {
7620                // This is a regular package, with one or more known overlay packages.
7621                createIdmapsForPackageLI(pkg);
7622            }
7623        }
7624
7625        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7626
7627        if (createIdmapFailed) {
7628            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7629                    "scanPackageLI failed to createIdmap");
7630        }
7631        return pkg;
7632    }
7633
7634    /**
7635     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7636     * is derived purely on the basis of the contents of {@code scanFile} and
7637     * {@code cpuAbiOverride}.
7638     *
7639     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7640     */
7641    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7642                                 String cpuAbiOverride, boolean extractLibs)
7643            throws PackageManagerException {
7644        // TODO: We can probably be smarter about this stuff. For installed apps,
7645        // we can calculate this information at install time once and for all. For
7646        // system apps, we can probably assume that this information doesn't change
7647        // after the first boot scan. As things stand, we do lots of unnecessary work.
7648
7649        // Give ourselves some initial paths; we'll come back for another
7650        // pass once we've determined ABI below.
7651        setNativeLibraryPaths(pkg);
7652
7653        // We would never need to extract libs for forward-locked and external packages,
7654        // since the container service will do it for us. We shouldn't attempt to
7655        // extract libs from system app when it was not updated.
7656        if (pkg.isForwardLocked() || isExternal(pkg) ||
7657            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7658            extractLibs = false;
7659        }
7660
7661        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7662        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7663
7664        NativeLibraryHelper.Handle handle = null;
7665        try {
7666            handle = NativeLibraryHelper.Handle.create(pkg);
7667            // TODO(multiArch): This can be null for apps that didn't go through the
7668            // usual installation process. We can calculate it again, like we
7669            // do during install time.
7670            //
7671            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7672            // unnecessary.
7673            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7674
7675            // Null out the abis so that they can be recalculated.
7676            pkg.applicationInfo.primaryCpuAbi = null;
7677            pkg.applicationInfo.secondaryCpuAbi = null;
7678            if (isMultiArch(pkg.applicationInfo)) {
7679                // Warn if we've set an abiOverride for multi-lib packages..
7680                // By definition, we need to copy both 32 and 64 bit libraries for
7681                // such packages.
7682                if (pkg.cpuAbiOverride != null
7683                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7684                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7685                }
7686
7687                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7688                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7689                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7690                    if (extractLibs) {
7691                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7692                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7693                                useIsaSpecificSubdirs);
7694                    } else {
7695                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7696                    }
7697                }
7698
7699                maybeThrowExceptionForMultiArchCopy(
7700                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7701
7702                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7703                    if (extractLibs) {
7704                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7705                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7706                                useIsaSpecificSubdirs);
7707                    } else {
7708                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7709                    }
7710                }
7711
7712                maybeThrowExceptionForMultiArchCopy(
7713                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7714
7715                if (abi64 >= 0) {
7716                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7717                }
7718
7719                if (abi32 >= 0) {
7720                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7721                    if (abi64 >= 0) {
7722                        pkg.applicationInfo.secondaryCpuAbi = abi;
7723                    } else {
7724                        pkg.applicationInfo.primaryCpuAbi = abi;
7725                    }
7726                }
7727            } else {
7728                String[] abiList = (cpuAbiOverride != null) ?
7729                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7730
7731                // Enable gross and lame hacks for apps that are built with old
7732                // SDK tools. We must scan their APKs for renderscript bitcode and
7733                // not launch them if it's present. Don't bother checking on devices
7734                // that don't have 64 bit support.
7735                boolean needsRenderScriptOverride = false;
7736                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7737                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7738                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7739                    needsRenderScriptOverride = true;
7740                }
7741
7742                final int copyRet;
7743                if (extractLibs) {
7744                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7745                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7746                } else {
7747                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7748                }
7749
7750                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7751                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7752                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7753                }
7754
7755                if (copyRet >= 0) {
7756                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7757                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7758                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7759                } else if (needsRenderScriptOverride) {
7760                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7761                }
7762            }
7763        } catch (IOException ioe) {
7764            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7765        } finally {
7766            IoUtils.closeQuietly(handle);
7767        }
7768
7769        // Now that we've calculated the ABIs and determined if it's an internal app,
7770        // we will go ahead and populate the nativeLibraryPath.
7771        setNativeLibraryPaths(pkg);
7772    }
7773
7774    /**
7775     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7776     * i.e, so that all packages can be run inside a single process if required.
7777     *
7778     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7779     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7780     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7781     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7782     * updating a package that belongs to a shared user.
7783     *
7784     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7785     * adds unnecessary complexity.
7786     */
7787    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7788            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7789        String requiredInstructionSet = null;
7790        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7791            requiredInstructionSet = VMRuntime.getInstructionSet(
7792                     scannedPackage.applicationInfo.primaryCpuAbi);
7793        }
7794
7795        PackageSetting requirer = null;
7796        for (PackageSetting ps : packagesForUser) {
7797            // If packagesForUser contains scannedPackage, we skip it. This will happen
7798            // when scannedPackage is an update of an existing package. Without this check,
7799            // we will never be able to change the ABI of any package belonging to a shared
7800            // user, even if it's compatible with other packages.
7801            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7802                if (ps.primaryCpuAbiString == null) {
7803                    continue;
7804                }
7805
7806                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7807                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7808                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7809                    // this but there's not much we can do.
7810                    String errorMessage = "Instruction set mismatch, "
7811                            + ((requirer == null) ? "[caller]" : requirer)
7812                            + " requires " + requiredInstructionSet + " whereas " + ps
7813                            + " requires " + instructionSet;
7814                    Slog.w(TAG, errorMessage);
7815                }
7816
7817                if (requiredInstructionSet == null) {
7818                    requiredInstructionSet = instructionSet;
7819                    requirer = ps;
7820                }
7821            }
7822        }
7823
7824        if (requiredInstructionSet != null) {
7825            String adjustedAbi;
7826            if (requirer != null) {
7827                // requirer != null implies that either scannedPackage was null or that scannedPackage
7828                // did not require an ABI, in which case we have to adjust scannedPackage to match
7829                // the ABI of the set (which is the same as requirer's ABI)
7830                adjustedAbi = requirer.primaryCpuAbiString;
7831                if (scannedPackage != null) {
7832                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7833                }
7834            } else {
7835                // requirer == null implies that we're updating all ABIs in the set to
7836                // match scannedPackage.
7837                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7838            }
7839
7840            for (PackageSetting ps : packagesForUser) {
7841                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7842                    if (ps.primaryCpuAbiString != null) {
7843                        continue;
7844                    }
7845
7846                    ps.primaryCpuAbiString = adjustedAbi;
7847                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7848                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7849                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7850
7851                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7852                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7853                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7854                            ps.primaryCpuAbiString = null;
7855                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7856                            return;
7857                        } else {
7858                            mInstaller.rmdex(ps.codePathString,
7859                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7860                        }
7861                    }
7862                }
7863            }
7864        }
7865    }
7866
7867    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7868        synchronized (mPackages) {
7869            mResolverReplaced = true;
7870            // Set up information for custom user intent resolution activity.
7871            mResolveActivity.applicationInfo = pkg.applicationInfo;
7872            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7873            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7874            mResolveActivity.processName = pkg.applicationInfo.packageName;
7875            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7876            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7877                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7878            mResolveActivity.theme = 0;
7879            mResolveActivity.exported = true;
7880            mResolveActivity.enabled = true;
7881            mResolveInfo.activityInfo = mResolveActivity;
7882            mResolveInfo.priority = 0;
7883            mResolveInfo.preferredOrder = 0;
7884            mResolveInfo.match = 0;
7885            mResolveComponentName = mCustomResolverComponentName;
7886            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7887                    mResolveComponentName);
7888        }
7889    }
7890
7891    private static String calculateBundledApkRoot(final String codePathString) {
7892        final File codePath = new File(codePathString);
7893        final File codeRoot;
7894        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7895            codeRoot = Environment.getRootDirectory();
7896        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7897            codeRoot = Environment.getOemDirectory();
7898        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7899            codeRoot = Environment.getVendorDirectory();
7900        } else {
7901            // Unrecognized code path; take its top real segment as the apk root:
7902            // e.g. /something/app/blah.apk => /something
7903            try {
7904                File f = codePath.getCanonicalFile();
7905                File parent = f.getParentFile();    // non-null because codePath is a file
7906                File tmp;
7907                while ((tmp = parent.getParentFile()) != null) {
7908                    f = parent;
7909                    parent = tmp;
7910                }
7911                codeRoot = f;
7912                Slog.w(TAG, "Unrecognized code path "
7913                        + codePath + " - using " + codeRoot);
7914            } catch (IOException e) {
7915                // Can't canonicalize the code path -- shenanigans?
7916                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7917                return Environment.getRootDirectory().getPath();
7918            }
7919        }
7920        return codeRoot.getPath();
7921    }
7922
7923    /**
7924     * Derive and set the location of native libraries for the given package,
7925     * which varies depending on where and how the package was installed.
7926     */
7927    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7928        final ApplicationInfo info = pkg.applicationInfo;
7929        final String codePath = pkg.codePath;
7930        final File codeFile = new File(codePath);
7931        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7932        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7933
7934        info.nativeLibraryRootDir = null;
7935        info.nativeLibraryRootRequiresIsa = false;
7936        info.nativeLibraryDir = null;
7937        info.secondaryNativeLibraryDir = null;
7938
7939        if (isApkFile(codeFile)) {
7940            // Monolithic install
7941            if (bundledApp) {
7942                // If "/system/lib64/apkname" exists, assume that is the per-package
7943                // native library directory to use; otherwise use "/system/lib/apkname".
7944                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7945                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7946                        getPrimaryInstructionSet(info));
7947
7948                // This is a bundled system app so choose the path based on the ABI.
7949                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7950                // is just the default path.
7951                final String apkName = deriveCodePathName(codePath);
7952                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7953                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7954                        apkName).getAbsolutePath();
7955
7956                if (info.secondaryCpuAbi != null) {
7957                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7958                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7959                            secondaryLibDir, apkName).getAbsolutePath();
7960                }
7961            } else if (asecApp) {
7962                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7963                        .getAbsolutePath();
7964            } else {
7965                final String apkName = deriveCodePathName(codePath);
7966                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7967                        .getAbsolutePath();
7968            }
7969
7970            info.nativeLibraryRootRequiresIsa = false;
7971            info.nativeLibraryDir = info.nativeLibraryRootDir;
7972        } else {
7973            // Cluster install
7974            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7975            info.nativeLibraryRootRequiresIsa = true;
7976
7977            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7978                    getPrimaryInstructionSet(info)).getAbsolutePath();
7979
7980            if (info.secondaryCpuAbi != null) {
7981                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7982                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7983            }
7984        }
7985    }
7986
7987    /**
7988     * Calculate the abis and roots for a bundled app. These can uniquely
7989     * be determined from the contents of the system partition, i.e whether
7990     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7991     * of this information, and instead assume that the system was built
7992     * sensibly.
7993     */
7994    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7995                                           PackageSetting pkgSetting) {
7996        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7997
7998        // If "/system/lib64/apkname" exists, assume that is the per-package
7999        // native library directory to use; otherwise use "/system/lib/apkname".
8000        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8001        setBundledAppAbi(pkg, apkRoot, apkName);
8002        // pkgSetting might be null during rescan following uninstall of updates
8003        // to a bundled app, so accommodate that possibility.  The settings in
8004        // that case will be established later from the parsed package.
8005        //
8006        // If the settings aren't null, sync them up with what we've just derived.
8007        // note that apkRoot isn't stored in the package settings.
8008        if (pkgSetting != null) {
8009            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8010            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8011        }
8012    }
8013
8014    /**
8015     * Deduces the ABI of a bundled app and sets the relevant fields on the
8016     * parsed pkg object.
8017     *
8018     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8019     *        under which system libraries are installed.
8020     * @param apkName the name of the installed package.
8021     */
8022    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8023        final File codeFile = new File(pkg.codePath);
8024
8025        final boolean has64BitLibs;
8026        final boolean has32BitLibs;
8027        if (isApkFile(codeFile)) {
8028            // Monolithic install
8029            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8030            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8031        } else {
8032            // Cluster install
8033            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8034            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8035                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8036                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8037                has64BitLibs = (new File(rootDir, isa)).exists();
8038            } else {
8039                has64BitLibs = false;
8040            }
8041            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8042                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8043                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8044                has32BitLibs = (new File(rootDir, isa)).exists();
8045            } else {
8046                has32BitLibs = false;
8047            }
8048        }
8049
8050        if (has64BitLibs && !has32BitLibs) {
8051            // The package has 64 bit libs, but not 32 bit libs. Its primary
8052            // ABI should be 64 bit. We can safely assume here that the bundled
8053            // native libraries correspond to the most preferred ABI in the list.
8054
8055            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8056            pkg.applicationInfo.secondaryCpuAbi = null;
8057        } else if (has32BitLibs && !has64BitLibs) {
8058            // The package has 32 bit libs but not 64 bit libs. Its primary
8059            // ABI should be 32 bit.
8060
8061            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8062            pkg.applicationInfo.secondaryCpuAbi = null;
8063        } else if (has32BitLibs && has64BitLibs) {
8064            // The application has both 64 and 32 bit bundled libraries. We check
8065            // here that the app declares multiArch support, and warn if it doesn't.
8066            //
8067            // We will be lenient here and record both ABIs. The primary will be the
8068            // ABI that's higher on the list, i.e, a device that's configured to prefer
8069            // 64 bit apps will see a 64 bit primary ABI,
8070
8071            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8072                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8073            }
8074
8075            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8076                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8077                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8078            } else {
8079                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8080                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8081            }
8082        } else {
8083            pkg.applicationInfo.primaryCpuAbi = null;
8084            pkg.applicationInfo.secondaryCpuAbi = null;
8085        }
8086    }
8087
8088    private void killApplication(String pkgName, int appId, String reason) {
8089        // Request the ActivityManager to kill the process(only for existing packages)
8090        // so that we do not end up in a confused state while the user is still using the older
8091        // version of the application while the new one gets installed.
8092        IActivityManager am = ActivityManagerNative.getDefault();
8093        if (am != null) {
8094            try {
8095                am.killApplicationWithAppId(pkgName, appId, reason);
8096            } catch (RemoteException e) {
8097            }
8098        }
8099    }
8100
8101    void removePackageLI(PackageSetting ps, boolean chatty) {
8102        if (DEBUG_INSTALL) {
8103            if (chatty)
8104                Log.d(TAG, "Removing package " + ps.name);
8105        }
8106
8107        // writer
8108        synchronized (mPackages) {
8109            mPackages.remove(ps.name);
8110            final PackageParser.Package pkg = ps.pkg;
8111            if (pkg != null) {
8112                cleanPackageDataStructuresLILPw(pkg, chatty);
8113            }
8114        }
8115    }
8116
8117    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8118        if (DEBUG_INSTALL) {
8119            if (chatty)
8120                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8121        }
8122
8123        // writer
8124        synchronized (mPackages) {
8125            mPackages.remove(pkg.applicationInfo.packageName);
8126            cleanPackageDataStructuresLILPw(pkg, chatty);
8127        }
8128    }
8129
8130    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8131        int N = pkg.providers.size();
8132        StringBuilder r = null;
8133        int i;
8134        for (i=0; i<N; i++) {
8135            PackageParser.Provider p = pkg.providers.get(i);
8136            mProviders.removeProvider(p);
8137            if (p.info.authority == null) {
8138
8139                /* There was another ContentProvider with this authority when
8140                 * this app was installed so this authority is null,
8141                 * Ignore it as we don't have to unregister the provider.
8142                 */
8143                continue;
8144            }
8145            String names[] = p.info.authority.split(";");
8146            for (int j = 0; j < names.length; j++) {
8147                if (mProvidersByAuthority.get(names[j]) == p) {
8148                    mProvidersByAuthority.remove(names[j]);
8149                    if (DEBUG_REMOVE) {
8150                        if (chatty)
8151                            Log.d(TAG, "Unregistered content provider: " + names[j]
8152                                    + ", className = " + p.info.name + ", isSyncable = "
8153                                    + p.info.isSyncable);
8154                    }
8155                }
8156            }
8157            if (DEBUG_REMOVE && chatty) {
8158                if (r == null) {
8159                    r = new StringBuilder(256);
8160                } else {
8161                    r.append(' ');
8162                }
8163                r.append(p.info.name);
8164            }
8165        }
8166        if (r != null) {
8167            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8168        }
8169
8170        N = pkg.services.size();
8171        r = null;
8172        for (i=0; i<N; i++) {
8173            PackageParser.Service s = pkg.services.get(i);
8174            mServices.removeService(s);
8175            if (chatty) {
8176                if (r == null) {
8177                    r = new StringBuilder(256);
8178                } else {
8179                    r.append(' ');
8180                }
8181                r.append(s.info.name);
8182            }
8183        }
8184        if (r != null) {
8185            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8186        }
8187
8188        N = pkg.receivers.size();
8189        r = null;
8190        for (i=0; i<N; i++) {
8191            PackageParser.Activity a = pkg.receivers.get(i);
8192            mReceivers.removeActivity(a, "receiver");
8193            if (DEBUG_REMOVE && chatty) {
8194                if (r == null) {
8195                    r = new StringBuilder(256);
8196                } else {
8197                    r.append(' ');
8198                }
8199                r.append(a.info.name);
8200            }
8201        }
8202        if (r != null) {
8203            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8204        }
8205
8206        N = pkg.activities.size();
8207        r = null;
8208        for (i=0; i<N; i++) {
8209            PackageParser.Activity a = pkg.activities.get(i);
8210            mActivities.removeActivity(a, "activity");
8211            if (DEBUG_REMOVE && chatty) {
8212                if (r == null) {
8213                    r = new StringBuilder(256);
8214                } else {
8215                    r.append(' ');
8216                }
8217                r.append(a.info.name);
8218            }
8219        }
8220        if (r != null) {
8221            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8222        }
8223
8224        N = pkg.permissions.size();
8225        r = null;
8226        for (i=0; i<N; i++) {
8227            PackageParser.Permission p = pkg.permissions.get(i);
8228            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8229            if (bp == null) {
8230                bp = mSettings.mPermissionTrees.get(p.info.name);
8231            }
8232            if (bp != null && bp.perm == p) {
8233                bp.perm = null;
8234                if (DEBUG_REMOVE && chatty) {
8235                    if (r == null) {
8236                        r = new StringBuilder(256);
8237                    } else {
8238                        r.append(' ');
8239                    }
8240                    r.append(p.info.name);
8241                }
8242            }
8243            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8244                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8245                if (appOpPerms != null) {
8246                    appOpPerms.remove(pkg.packageName);
8247                }
8248            }
8249        }
8250        if (r != null) {
8251            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8252        }
8253
8254        N = pkg.requestedPermissions.size();
8255        r = null;
8256        for (i=0; i<N; i++) {
8257            String perm = pkg.requestedPermissions.get(i);
8258            BasePermission bp = mSettings.mPermissions.get(perm);
8259            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8260                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8261                if (appOpPerms != null) {
8262                    appOpPerms.remove(pkg.packageName);
8263                    if (appOpPerms.isEmpty()) {
8264                        mAppOpPermissionPackages.remove(perm);
8265                    }
8266                }
8267            }
8268        }
8269        if (r != null) {
8270            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8271        }
8272
8273        N = pkg.instrumentation.size();
8274        r = null;
8275        for (i=0; i<N; i++) {
8276            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8277            mInstrumentation.remove(a.getComponentName());
8278            if (DEBUG_REMOVE && chatty) {
8279                if (r == null) {
8280                    r = new StringBuilder(256);
8281                } else {
8282                    r.append(' ');
8283                }
8284                r.append(a.info.name);
8285            }
8286        }
8287        if (r != null) {
8288            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8289        }
8290
8291        r = null;
8292        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8293            // Only system apps can hold shared libraries.
8294            if (pkg.libraryNames != null) {
8295                for (i=0; i<pkg.libraryNames.size(); i++) {
8296                    String name = pkg.libraryNames.get(i);
8297                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8298                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8299                        mSharedLibraries.remove(name);
8300                        if (DEBUG_REMOVE && chatty) {
8301                            if (r == null) {
8302                                r = new StringBuilder(256);
8303                            } else {
8304                                r.append(' ');
8305                            }
8306                            r.append(name);
8307                        }
8308                    }
8309                }
8310            }
8311        }
8312        if (r != null) {
8313            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8314        }
8315    }
8316
8317    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8318        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8319            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8320                return true;
8321            }
8322        }
8323        return false;
8324    }
8325
8326    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8327    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8328    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8329
8330    private void updatePermissionsLPw(String changingPkg,
8331            PackageParser.Package pkgInfo, int flags) {
8332        // Make sure there are no dangling permission trees.
8333        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8334        while (it.hasNext()) {
8335            final BasePermission bp = it.next();
8336            if (bp.packageSetting == null) {
8337                // We may not yet have parsed the package, so just see if
8338                // we still know about its settings.
8339                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8340            }
8341            if (bp.packageSetting == null) {
8342                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8343                        + " from package " + bp.sourcePackage);
8344                it.remove();
8345            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8346                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8347                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8348                            + " from package " + bp.sourcePackage);
8349                    flags |= UPDATE_PERMISSIONS_ALL;
8350                    it.remove();
8351                }
8352            }
8353        }
8354
8355        // Make sure all dynamic permissions have been assigned to a package,
8356        // and make sure there are no dangling permissions.
8357        it = mSettings.mPermissions.values().iterator();
8358        while (it.hasNext()) {
8359            final BasePermission bp = it.next();
8360            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8361                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8362                        + bp.name + " pkg=" + bp.sourcePackage
8363                        + " info=" + bp.pendingInfo);
8364                if (bp.packageSetting == null && bp.pendingInfo != null) {
8365                    final BasePermission tree = findPermissionTreeLP(bp.name);
8366                    if (tree != null && tree.perm != null) {
8367                        bp.packageSetting = tree.packageSetting;
8368                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8369                                new PermissionInfo(bp.pendingInfo));
8370                        bp.perm.info.packageName = tree.perm.info.packageName;
8371                        bp.perm.info.name = bp.name;
8372                        bp.uid = tree.uid;
8373                    }
8374                }
8375            }
8376            if (bp.packageSetting == null) {
8377                // We may not yet have parsed the package, so just see if
8378                // we still know about its settings.
8379                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8380            }
8381            if (bp.packageSetting == null) {
8382                Slog.w(TAG, "Removing dangling permission: " + bp.name
8383                        + " from package " + bp.sourcePackage);
8384                it.remove();
8385            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8386                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8387                    Slog.i(TAG, "Removing old permission: " + bp.name
8388                            + " from package " + bp.sourcePackage);
8389                    flags |= UPDATE_PERMISSIONS_ALL;
8390                    it.remove();
8391                }
8392            }
8393        }
8394
8395        // Now update the permissions for all packages, in particular
8396        // replace the granted permissions of the system packages.
8397        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8398            for (PackageParser.Package pkg : mPackages.values()) {
8399                if (pkg != pkgInfo) {
8400                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8401                            changingPkg);
8402                }
8403            }
8404        }
8405
8406        if (pkgInfo != null) {
8407            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8408        }
8409    }
8410
8411    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8412            String packageOfInterest) {
8413        // IMPORTANT: There are two types of permissions: install and runtime.
8414        // Install time permissions are granted when the app is installed to
8415        // all device users and users added in the future. Runtime permissions
8416        // are granted at runtime explicitly to specific users. Normal and signature
8417        // protected permissions are install time permissions. Dangerous permissions
8418        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8419        // otherwise they are runtime permissions. This function does not manage
8420        // runtime permissions except for the case an app targeting Lollipop MR1
8421        // being upgraded to target a newer SDK, in which case dangerous permissions
8422        // are transformed from install time to runtime ones.
8423
8424        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8425        if (ps == null) {
8426            return;
8427        }
8428
8429        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8430
8431        PermissionsState permissionsState = ps.getPermissionsState();
8432        PermissionsState origPermissions = permissionsState;
8433
8434        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8435
8436        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8437
8438        boolean changedInstallPermission = false;
8439
8440        if (replace) {
8441            ps.installPermissionsFixed = false;
8442            if (!ps.isSharedUser()) {
8443                origPermissions = new PermissionsState(permissionsState);
8444                permissionsState.reset();
8445            }
8446        }
8447
8448        permissionsState.setGlobalGids(mGlobalGids);
8449
8450        final int N = pkg.requestedPermissions.size();
8451        for (int i=0; i<N; i++) {
8452            final String name = pkg.requestedPermissions.get(i);
8453            final BasePermission bp = mSettings.mPermissions.get(name);
8454
8455            if (DEBUG_INSTALL) {
8456                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8457            }
8458
8459            if (bp == null || bp.packageSetting == null) {
8460                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8461                    Slog.w(TAG, "Unknown permission " + name
8462                            + " in package " + pkg.packageName);
8463                }
8464                continue;
8465            }
8466
8467            final String perm = bp.name;
8468            boolean allowedSig = false;
8469            int grant = GRANT_DENIED;
8470
8471            // Keep track of app op permissions.
8472            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8473                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8474                if (pkgs == null) {
8475                    pkgs = new ArraySet<>();
8476                    mAppOpPermissionPackages.put(bp.name, pkgs);
8477                }
8478                pkgs.add(pkg.packageName);
8479            }
8480
8481            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8482            switch (level) {
8483                case PermissionInfo.PROTECTION_NORMAL: {
8484                    // For all apps normal permissions are install time ones.
8485                    grant = GRANT_INSTALL;
8486                } break;
8487
8488                case PermissionInfo.PROTECTION_DANGEROUS: {
8489                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8490                        // For legacy apps dangerous permissions are install time ones.
8491                        grant = GRANT_INSTALL_LEGACY;
8492                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8493                        // For legacy apps that became modern, install becomes runtime.
8494                        grant = GRANT_UPGRADE;
8495                    } else if (mPromoteSystemApps
8496                            && isSystemApp(ps)
8497                            && mExistingSystemPackages.contains(ps.name)) {
8498                        // For legacy system apps, install becomes runtime.
8499                        // We cannot check hasInstallPermission() for system apps since those
8500                        // permissions were granted implicitly and not persisted pre-M.
8501                        grant = GRANT_UPGRADE;
8502                    } else {
8503                        // For modern apps keep runtime permissions unchanged.
8504                        grant = GRANT_RUNTIME;
8505                    }
8506                } break;
8507
8508                case PermissionInfo.PROTECTION_SIGNATURE: {
8509                    // For all apps signature permissions are install time ones.
8510                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8511                    if (allowedSig) {
8512                        grant = GRANT_INSTALL;
8513                    }
8514                } break;
8515            }
8516
8517            if (DEBUG_INSTALL) {
8518                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8519            }
8520
8521            if (grant != GRANT_DENIED) {
8522                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8523                    // If this is an existing, non-system package, then
8524                    // we can't add any new permissions to it.
8525                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8526                        // Except...  if this is a permission that was added
8527                        // to the platform (note: need to only do this when
8528                        // updating the platform).
8529                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8530                            grant = GRANT_DENIED;
8531                        }
8532                    }
8533                }
8534
8535                switch (grant) {
8536                    case GRANT_INSTALL: {
8537                        // Revoke this as runtime permission to handle the case of
8538                        // a runtime permission being downgraded to an install one.
8539                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8540                            if (origPermissions.getRuntimePermissionState(
8541                                    bp.name, userId) != null) {
8542                                // Revoke the runtime permission and clear the flags.
8543                                origPermissions.revokeRuntimePermission(bp, userId);
8544                                origPermissions.updatePermissionFlags(bp, userId,
8545                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8546                                // If we revoked a permission permission, we have to write.
8547                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8548                                        changedRuntimePermissionUserIds, userId);
8549                            }
8550                        }
8551                        // Grant an install permission.
8552                        if (permissionsState.grantInstallPermission(bp) !=
8553                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8554                            changedInstallPermission = true;
8555                        }
8556                    } break;
8557
8558                    case GRANT_INSTALL_LEGACY: {
8559                        // Grant an install permission.
8560                        if (permissionsState.grantInstallPermission(bp) !=
8561                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8562                            changedInstallPermission = true;
8563                        }
8564                    } break;
8565
8566                    case GRANT_RUNTIME: {
8567                        // Grant previously granted runtime permissions.
8568                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8569                            PermissionState permissionState = origPermissions
8570                                    .getRuntimePermissionState(bp.name, userId);
8571                            final int flags = permissionState != null
8572                                    ? permissionState.getFlags() : 0;
8573                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8574                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8575                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8576                                    // If we cannot put the permission as it was, we have to write.
8577                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8578                                            changedRuntimePermissionUserIds, userId);
8579                                }
8580                            }
8581                            // Propagate the permission flags.
8582                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8583                        }
8584                    } break;
8585
8586                    case GRANT_UPGRADE: {
8587                        // Grant runtime permissions for a previously held install permission.
8588                        PermissionState permissionState = origPermissions
8589                                .getInstallPermissionState(bp.name);
8590                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8591
8592                        if (origPermissions.revokeInstallPermission(bp)
8593                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8594                            // We will be transferring the permission flags, so clear them.
8595                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8596                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8597                            changedInstallPermission = true;
8598                        }
8599
8600                        // If the permission is not to be promoted to runtime we ignore it and
8601                        // also its other flags as they are not applicable to install permissions.
8602                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8603                            for (int userId : currentUserIds) {
8604                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8605                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8606                                    // Transfer the permission flags.
8607                                    permissionsState.updatePermissionFlags(bp, userId,
8608                                            flags, flags);
8609                                    // If we granted the permission, we have to write.
8610                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8611                                            changedRuntimePermissionUserIds, userId);
8612                                }
8613                            }
8614                        }
8615                    } break;
8616
8617                    default: {
8618                        if (packageOfInterest == null
8619                                || packageOfInterest.equals(pkg.packageName)) {
8620                            Slog.w(TAG, "Not granting permission " + perm
8621                                    + " to package " + pkg.packageName
8622                                    + " because it was previously installed without");
8623                        }
8624                    } break;
8625                }
8626            } else {
8627                if (permissionsState.revokeInstallPermission(bp) !=
8628                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8629                    // Also drop the permission flags.
8630                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8631                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8632                    changedInstallPermission = true;
8633                    Slog.i(TAG, "Un-granting permission " + perm
8634                            + " from package " + pkg.packageName
8635                            + " (protectionLevel=" + bp.protectionLevel
8636                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8637                            + ")");
8638                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8639                    // Don't print warning for app op permissions, since it is fine for them
8640                    // not to be granted, there is a UI for the user to decide.
8641                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8642                        Slog.w(TAG, "Not granting permission " + perm
8643                                + " to package " + pkg.packageName
8644                                + " (protectionLevel=" + bp.protectionLevel
8645                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8646                                + ")");
8647                    }
8648                }
8649            }
8650        }
8651
8652        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8653                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8654            // This is the first that we have heard about this package, so the
8655            // permissions we have now selected are fixed until explicitly
8656            // changed.
8657            ps.installPermissionsFixed = true;
8658        }
8659
8660        // Persist the runtime permissions state for users with changes.
8661        for (int userId : changedRuntimePermissionUserIds) {
8662            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8663        }
8664
8665        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8666    }
8667
8668    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8669        boolean allowed = false;
8670        final int NP = PackageParser.NEW_PERMISSIONS.length;
8671        for (int ip=0; ip<NP; ip++) {
8672            final PackageParser.NewPermissionInfo npi
8673                    = PackageParser.NEW_PERMISSIONS[ip];
8674            if (npi.name.equals(perm)
8675                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8676                allowed = true;
8677                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8678                        + pkg.packageName);
8679                break;
8680            }
8681        }
8682        return allowed;
8683    }
8684
8685    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8686            BasePermission bp, PermissionsState origPermissions) {
8687        boolean allowed;
8688        allowed = (compareSignatures(
8689                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8690                        == PackageManager.SIGNATURE_MATCH)
8691                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8692                        == PackageManager.SIGNATURE_MATCH);
8693        if (!allowed && (bp.protectionLevel
8694                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8695            if (isSystemApp(pkg)) {
8696                // For updated system applications, a system permission
8697                // is granted only if it had been defined by the original application.
8698                if (pkg.isUpdatedSystemApp()) {
8699                    final PackageSetting sysPs = mSettings
8700                            .getDisabledSystemPkgLPr(pkg.packageName);
8701                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8702                        // If the original was granted this permission, we take
8703                        // that grant decision as read and propagate it to the
8704                        // update.
8705                        if (sysPs.isPrivileged()) {
8706                            allowed = true;
8707                        }
8708                    } else {
8709                        // The system apk may have been updated with an older
8710                        // version of the one on the data partition, but which
8711                        // granted a new system permission that it didn't have
8712                        // before.  In this case we do want to allow the app to
8713                        // now get the new permission if the ancestral apk is
8714                        // privileged to get it.
8715                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8716                            for (int j=0;
8717                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8718                                if (perm.equals(
8719                                        sysPs.pkg.requestedPermissions.get(j))) {
8720                                    allowed = true;
8721                                    break;
8722                                }
8723                            }
8724                        }
8725                    }
8726                } else {
8727                    allowed = isPrivilegedApp(pkg);
8728                }
8729            }
8730        }
8731        if (!allowed) {
8732            if (!allowed && (bp.protectionLevel
8733                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8734                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8735                // If this was a previously normal/dangerous permission that got moved
8736                // to a system permission as part of the runtime permission redesign, then
8737                // we still want to blindly grant it to old apps.
8738                allowed = true;
8739            }
8740            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8741                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8742                // If this permission is to be granted to the system installer and
8743                // this app is an installer, then it gets the permission.
8744                allowed = true;
8745            }
8746            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8747                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8748                // If this permission is to be granted to the system verifier and
8749                // this app is a verifier, then it gets the permission.
8750                allowed = true;
8751            }
8752            if (!allowed && (bp.protectionLevel
8753                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8754                    && isSystemApp(pkg)) {
8755                // Any pre-installed system app is allowed to get this permission.
8756                allowed = true;
8757            }
8758            if (!allowed && (bp.protectionLevel
8759                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8760                // For development permissions, a development permission
8761                // is granted only if it was already granted.
8762                allowed = origPermissions.hasInstallPermission(perm);
8763            }
8764        }
8765        return allowed;
8766    }
8767
8768    final class ActivityIntentResolver
8769            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8770        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8771                boolean defaultOnly, int userId) {
8772            if (!sUserManager.exists(userId)) return null;
8773            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8774            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8775        }
8776
8777        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8778                int userId) {
8779            if (!sUserManager.exists(userId)) return null;
8780            mFlags = flags;
8781            return super.queryIntent(intent, resolvedType,
8782                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8783        }
8784
8785        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8786                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8787            if (!sUserManager.exists(userId)) return null;
8788            if (packageActivities == null) {
8789                return null;
8790            }
8791            mFlags = flags;
8792            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8793            final int N = packageActivities.size();
8794            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8795                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8796
8797            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8798            for (int i = 0; i < N; ++i) {
8799                intentFilters = packageActivities.get(i).intents;
8800                if (intentFilters != null && intentFilters.size() > 0) {
8801                    PackageParser.ActivityIntentInfo[] array =
8802                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8803                    intentFilters.toArray(array);
8804                    listCut.add(array);
8805                }
8806            }
8807            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8808        }
8809
8810        public final void addActivity(PackageParser.Activity a, String type) {
8811            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8812            mActivities.put(a.getComponentName(), a);
8813            if (DEBUG_SHOW_INFO)
8814                Log.v(
8815                TAG, "  " + type + " " +
8816                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8817            if (DEBUG_SHOW_INFO)
8818                Log.v(TAG, "    Class=" + a.info.name);
8819            final int NI = a.intents.size();
8820            for (int j=0; j<NI; j++) {
8821                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8822                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8823                    intent.setPriority(0);
8824                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8825                            + a.className + " with priority > 0, forcing to 0");
8826                }
8827                if (DEBUG_SHOW_INFO) {
8828                    Log.v(TAG, "    IntentFilter:");
8829                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8830                }
8831                if (!intent.debugCheck()) {
8832                    Log.w(TAG, "==> For Activity " + a.info.name);
8833                }
8834                addFilter(intent);
8835            }
8836        }
8837
8838        public final void removeActivity(PackageParser.Activity a, String type) {
8839            mActivities.remove(a.getComponentName());
8840            if (DEBUG_SHOW_INFO) {
8841                Log.v(TAG, "  " + type + " "
8842                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8843                                : a.info.name) + ":");
8844                Log.v(TAG, "    Class=" + a.info.name);
8845            }
8846            final int NI = a.intents.size();
8847            for (int j=0; j<NI; j++) {
8848                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8849                if (DEBUG_SHOW_INFO) {
8850                    Log.v(TAG, "    IntentFilter:");
8851                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8852                }
8853                removeFilter(intent);
8854            }
8855        }
8856
8857        @Override
8858        protected boolean allowFilterResult(
8859                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8860            ActivityInfo filterAi = filter.activity.info;
8861            for (int i=dest.size()-1; i>=0; i--) {
8862                ActivityInfo destAi = dest.get(i).activityInfo;
8863                if (destAi.name == filterAi.name
8864                        && destAi.packageName == filterAi.packageName) {
8865                    return false;
8866                }
8867            }
8868            return true;
8869        }
8870
8871        @Override
8872        protected ActivityIntentInfo[] newArray(int size) {
8873            return new ActivityIntentInfo[size];
8874        }
8875
8876        @Override
8877        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8878            if (!sUserManager.exists(userId)) return true;
8879            PackageParser.Package p = filter.activity.owner;
8880            if (p != null) {
8881                PackageSetting ps = (PackageSetting)p.mExtras;
8882                if (ps != null) {
8883                    // System apps are never considered stopped for purposes of
8884                    // filtering, because there may be no way for the user to
8885                    // actually re-launch them.
8886                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8887                            && ps.getStopped(userId);
8888                }
8889            }
8890            return false;
8891        }
8892
8893        @Override
8894        protected boolean isPackageForFilter(String packageName,
8895                PackageParser.ActivityIntentInfo info) {
8896            return packageName.equals(info.activity.owner.packageName);
8897        }
8898
8899        @Override
8900        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8901                int match, int userId) {
8902            if (!sUserManager.exists(userId)) return null;
8903            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8904                return null;
8905            }
8906            final PackageParser.Activity activity = info.activity;
8907            if (mSafeMode && (activity.info.applicationInfo.flags
8908                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8909                return null;
8910            }
8911            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8912            if (ps == null) {
8913                return null;
8914            }
8915            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8916                    ps.readUserState(userId), userId);
8917            if (ai == null) {
8918                return null;
8919            }
8920            final ResolveInfo res = new ResolveInfo();
8921            res.activityInfo = ai;
8922            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8923                res.filter = info;
8924            }
8925            if (info != null) {
8926                res.handleAllWebDataURI = info.handleAllWebDataURI();
8927            }
8928            res.priority = info.getPriority();
8929            res.preferredOrder = activity.owner.mPreferredOrder;
8930            //System.out.println("Result: " + res.activityInfo.className +
8931            //                   " = " + res.priority);
8932            res.match = match;
8933            res.isDefault = info.hasDefault;
8934            res.labelRes = info.labelRes;
8935            res.nonLocalizedLabel = info.nonLocalizedLabel;
8936            if (userNeedsBadging(userId)) {
8937                res.noResourceId = true;
8938            } else {
8939                res.icon = info.icon;
8940            }
8941            res.iconResourceId = info.icon;
8942            res.system = res.activityInfo.applicationInfo.isSystemApp();
8943            return res;
8944        }
8945
8946        @Override
8947        protected void sortResults(List<ResolveInfo> results) {
8948            Collections.sort(results, mResolvePrioritySorter);
8949        }
8950
8951        @Override
8952        protected void dumpFilter(PrintWriter out, String prefix,
8953                PackageParser.ActivityIntentInfo filter) {
8954            out.print(prefix); out.print(
8955                    Integer.toHexString(System.identityHashCode(filter.activity)));
8956                    out.print(' ');
8957                    filter.activity.printComponentShortName(out);
8958                    out.print(" filter ");
8959                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8960        }
8961
8962        @Override
8963        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8964            return filter.activity;
8965        }
8966
8967        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8968            PackageParser.Activity activity = (PackageParser.Activity)label;
8969            out.print(prefix); out.print(
8970                    Integer.toHexString(System.identityHashCode(activity)));
8971                    out.print(' ');
8972                    activity.printComponentShortName(out);
8973            if (count > 1) {
8974                out.print(" ("); out.print(count); out.print(" filters)");
8975            }
8976            out.println();
8977        }
8978
8979//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8980//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8981//            final List<ResolveInfo> retList = Lists.newArrayList();
8982//            while (i.hasNext()) {
8983//                final ResolveInfo resolveInfo = i.next();
8984//                if (isEnabledLP(resolveInfo.activityInfo)) {
8985//                    retList.add(resolveInfo);
8986//                }
8987//            }
8988//            return retList;
8989//        }
8990
8991        // Keys are String (activity class name), values are Activity.
8992        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8993                = new ArrayMap<ComponentName, PackageParser.Activity>();
8994        private int mFlags;
8995    }
8996
8997    private final class ServiceIntentResolver
8998            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8999        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9000                boolean defaultOnly, int userId) {
9001            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9002            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9003        }
9004
9005        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9006                int userId) {
9007            if (!sUserManager.exists(userId)) return null;
9008            mFlags = flags;
9009            return super.queryIntent(intent, resolvedType,
9010                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9011        }
9012
9013        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9014                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9015            if (!sUserManager.exists(userId)) return null;
9016            if (packageServices == null) {
9017                return null;
9018            }
9019            mFlags = flags;
9020            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9021            final int N = packageServices.size();
9022            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9023                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9024
9025            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9026            for (int i = 0; i < N; ++i) {
9027                intentFilters = packageServices.get(i).intents;
9028                if (intentFilters != null && intentFilters.size() > 0) {
9029                    PackageParser.ServiceIntentInfo[] array =
9030                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9031                    intentFilters.toArray(array);
9032                    listCut.add(array);
9033                }
9034            }
9035            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9036        }
9037
9038        public final void addService(PackageParser.Service s) {
9039            mServices.put(s.getComponentName(), s);
9040            if (DEBUG_SHOW_INFO) {
9041                Log.v(TAG, "  "
9042                        + (s.info.nonLocalizedLabel != null
9043                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9044                Log.v(TAG, "    Class=" + s.info.name);
9045            }
9046            final int NI = s.intents.size();
9047            int j;
9048            for (j=0; j<NI; j++) {
9049                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9050                if (DEBUG_SHOW_INFO) {
9051                    Log.v(TAG, "    IntentFilter:");
9052                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9053                }
9054                if (!intent.debugCheck()) {
9055                    Log.w(TAG, "==> For Service " + s.info.name);
9056                }
9057                addFilter(intent);
9058            }
9059        }
9060
9061        public final void removeService(PackageParser.Service s) {
9062            mServices.remove(s.getComponentName());
9063            if (DEBUG_SHOW_INFO) {
9064                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9065                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9066                Log.v(TAG, "    Class=" + s.info.name);
9067            }
9068            final int NI = s.intents.size();
9069            int j;
9070            for (j=0; j<NI; j++) {
9071                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9072                if (DEBUG_SHOW_INFO) {
9073                    Log.v(TAG, "    IntentFilter:");
9074                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9075                }
9076                removeFilter(intent);
9077            }
9078        }
9079
9080        @Override
9081        protected boolean allowFilterResult(
9082                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9083            ServiceInfo filterSi = filter.service.info;
9084            for (int i=dest.size()-1; i>=0; i--) {
9085                ServiceInfo destAi = dest.get(i).serviceInfo;
9086                if (destAi.name == filterSi.name
9087                        && destAi.packageName == filterSi.packageName) {
9088                    return false;
9089                }
9090            }
9091            return true;
9092        }
9093
9094        @Override
9095        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9096            return new PackageParser.ServiceIntentInfo[size];
9097        }
9098
9099        @Override
9100        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9101            if (!sUserManager.exists(userId)) return true;
9102            PackageParser.Package p = filter.service.owner;
9103            if (p != null) {
9104                PackageSetting ps = (PackageSetting)p.mExtras;
9105                if (ps != null) {
9106                    // System apps are never considered stopped for purposes of
9107                    // filtering, because there may be no way for the user to
9108                    // actually re-launch them.
9109                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9110                            && ps.getStopped(userId);
9111                }
9112            }
9113            return false;
9114        }
9115
9116        @Override
9117        protected boolean isPackageForFilter(String packageName,
9118                PackageParser.ServiceIntentInfo info) {
9119            return packageName.equals(info.service.owner.packageName);
9120        }
9121
9122        @Override
9123        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9124                int match, int userId) {
9125            if (!sUserManager.exists(userId)) return null;
9126            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9127            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9128                return null;
9129            }
9130            final PackageParser.Service service = info.service;
9131            if (mSafeMode && (service.info.applicationInfo.flags
9132                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9133                return null;
9134            }
9135            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9136            if (ps == null) {
9137                return null;
9138            }
9139            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9140                    ps.readUserState(userId), userId);
9141            if (si == null) {
9142                return null;
9143            }
9144            final ResolveInfo res = new ResolveInfo();
9145            res.serviceInfo = si;
9146            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9147                res.filter = filter;
9148            }
9149            res.priority = info.getPriority();
9150            res.preferredOrder = service.owner.mPreferredOrder;
9151            res.match = match;
9152            res.isDefault = info.hasDefault;
9153            res.labelRes = info.labelRes;
9154            res.nonLocalizedLabel = info.nonLocalizedLabel;
9155            res.icon = info.icon;
9156            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9157            return res;
9158        }
9159
9160        @Override
9161        protected void sortResults(List<ResolveInfo> results) {
9162            Collections.sort(results, mResolvePrioritySorter);
9163        }
9164
9165        @Override
9166        protected void dumpFilter(PrintWriter out, String prefix,
9167                PackageParser.ServiceIntentInfo filter) {
9168            out.print(prefix); out.print(
9169                    Integer.toHexString(System.identityHashCode(filter.service)));
9170                    out.print(' ');
9171                    filter.service.printComponentShortName(out);
9172                    out.print(" filter ");
9173                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9174        }
9175
9176        @Override
9177        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9178            return filter.service;
9179        }
9180
9181        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9182            PackageParser.Service service = (PackageParser.Service)label;
9183            out.print(prefix); out.print(
9184                    Integer.toHexString(System.identityHashCode(service)));
9185                    out.print(' ');
9186                    service.printComponentShortName(out);
9187            if (count > 1) {
9188                out.print(" ("); out.print(count); out.print(" filters)");
9189            }
9190            out.println();
9191        }
9192
9193//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9194//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9195//            final List<ResolveInfo> retList = Lists.newArrayList();
9196//            while (i.hasNext()) {
9197//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9198//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9199//                    retList.add(resolveInfo);
9200//                }
9201//            }
9202//            return retList;
9203//        }
9204
9205        // Keys are String (activity class name), values are Activity.
9206        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9207                = new ArrayMap<ComponentName, PackageParser.Service>();
9208        private int mFlags;
9209    };
9210
9211    private final class ProviderIntentResolver
9212            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9213        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9214                boolean defaultOnly, int userId) {
9215            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9216            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9217        }
9218
9219        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9220                int userId) {
9221            if (!sUserManager.exists(userId))
9222                return null;
9223            mFlags = flags;
9224            return super.queryIntent(intent, resolvedType,
9225                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9226        }
9227
9228        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9229                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9230            if (!sUserManager.exists(userId))
9231                return null;
9232            if (packageProviders == null) {
9233                return null;
9234            }
9235            mFlags = flags;
9236            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9237            final int N = packageProviders.size();
9238            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9239                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9240
9241            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9242            for (int i = 0; i < N; ++i) {
9243                intentFilters = packageProviders.get(i).intents;
9244                if (intentFilters != null && intentFilters.size() > 0) {
9245                    PackageParser.ProviderIntentInfo[] array =
9246                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9247                    intentFilters.toArray(array);
9248                    listCut.add(array);
9249                }
9250            }
9251            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9252        }
9253
9254        public final void addProvider(PackageParser.Provider p) {
9255            if (mProviders.containsKey(p.getComponentName())) {
9256                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9257                return;
9258            }
9259
9260            mProviders.put(p.getComponentName(), p);
9261            if (DEBUG_SHOW_INFO) {
9262                Log.v(TAG, "  "
9263                        + (p.info.nonLocalizedLabel != null
9264                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9265                Log.v(TAG, "    Class=" + p.info.name);
9266            }
9267            final int NI = p.intents.size();
9268            int j;
9269            for (j = 0; j < NI; j++) {
9270                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9271                if (DEBUG_SHOW_INFO) {
9272                    Log.v(TAG, "    IntentFilter:");
9273                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9274                }
9275                if (!intent.debugCheck()) {
9276                    Log.w(TAG, "==> For Provider " + p.info.name);
9277                }
9278                addFilter(intent);
9279            }
9280        }
9281
9282        public final void removeProvider(PackageParser.Provider p) {
9283            mProviders.remove(p.getComponentName());
9284            if (DEBUG_SHOW_INFO) {
9285                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9286                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9287                Log.v(TAG, "    Class=" + p.info.name);
9288            }
9289            final int NI = p.intents.size();
9290            int j;
9291            for (j = 0; j < NI; j++) {
9292                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9293                if (DEBUG_SHOW_INFO) {
9294                    Log.v(TAG, "    IntentFilter:");
9295                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9296                }
9297                removeFilter(intent);
9298            }
9299        }
9300
9301        @Override
9302        protected boolean allowFilterResult(
9303                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9304            ProviderInfo filterPi = filter.provider.info;
9305            for (int i = dest.size() - 1; i >= 0; i--) {
9306                ProviderInfo destPi = dest.get(i).providerInfo;
9307                if (destPi.name == filterPi.name
9308                        && destPi.packageName == filterPi.packageName) {
9309                    return false;
9310                }
9311            }
9312            return true;
9313        }
9314
9315        @Override
9316        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9317            return new PackageParser.ProviderIntentInfo[size];
9318        }
9319
9320        @Override
9321        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9322            if (!sUserManager.exists(userId))
9323                return true;
9324            PackageParser.Package p = filter.provider.owner;
9325            if (p != null) {
9326                PackageSetting ps = (PackageSetting) p.mExtras;
9327                if (ps != null) {
9328                    // System apps are never considered stopped for purposes of
9329                    // filtering, because there may be no way for the user to
9330                    // actually re-launch them.
9331                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9332                            && ps.getStopped(userId);
9333                }
9334            }
9335            return false;
9336        }
9337
9338        @Override
9339        protected boolean isPackageForFilter(String packageName,
9340                PackageParser.ProviderIntentInfo info) {
9341            return packageName.equals(info.provider.owner.packageName);
9342        }
9343
9344        @Override
9345        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9346                int match, int userId) {
9347            if (!sUserManager.exists(userId))
9348                return null;
9349            final PackageParser.ProviderIntentInfo info = filter;
9350            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9351                return null;
9352            }
9353            final PackageParser.Provider provider = info.provider;
9354            if (mSafeMode && (provider.info.applicationInfo.flags
9355                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9356                return null;
9357            }
9358            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9359            if (ps == null) {
9360                return null;
9361            }
9362            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9363                    ps.readUserState(userId), userId);
9364            if (pi == null) {
9365                return null;
9366            }
9367            final ResolveInfo res = new ResolveInfo();
9368            res.providerInfo = pi;
9369            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9370                res.filter = filter;
9371            }
9372            res.priority = info.getPriority();
9373            res.preferredOrder = provider.owner.mPreferredOrder;
9374            res.match = match;
9375            res.isDefault = info.hasDefault;
9376            res.labelRes = info.labelRes;
9377            res.nonLocalizedLabel = info.nonLocalizedLabel;
9378            res.icon = info.icon;
9379            res.system = res.providerInfo.applicationInfo.isSystemApp();
9380            return res;
9381        }
9382
9383        @Override
9384        protected void sortResults(List<ResolveInfo> results) {
9385            Collections.sort(results, mResolvePrioritySorter);
9386        }
9387
9388        @Override
9389        protected void dumpFilter(PrintWriter out, String prefix,
9390                PackageParser.ProviderIntentInfo filter) {
9391            out.print(prefix);
9392            out.print(
9393                    Integer.toHexString(System.identityHashCode(filter.provider)));
9394            out.print(' ');
9395            filter.provider.printComponentShortName(out);
9396            out.print(" filter ");
9397            out.println(Integer.toHexString(System.identityHashCode(filter)));
9398        }
9399
9400        @Override
9401        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9402            return filter.provider;
9403        }
9404
9405        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9406            PackageParser.Provider provider = (PackageParser.Provider)label;
9407            out.print(prefix); out.print(
9408                    Integer.toHexString(System.identityHashCode(provider)));
9409                    out.print(' ');
9410                    provider.printComponentShortName(out);
9411            if (count > 1) {
9412                out.print(" ("); out.print(count); out.print(" filters)");
9413            }
9414            out.println();
9415        }
9416
9417        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9418                = new ArrayMap<ComponentName, PackageParser.Provider>();
9419        private int mFlags;
9420    };
9421
9422    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9423            new Comparator<ResolveInfo>() {
9424        public int compare(ResolveInfo r1, ResolveInfo r2) {
9425            int v1 = r1.priority;
9426            int v2 = r2.priority;
9427            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9428            if (v1 != v2) {
9429                return (v1 > v2) ? -1 : 1;
9430            }
9431            v1 = r1.preferredOrder;
9432            v2 = r2.preferredOrder;
9433            if (v1 != v2) {
9434                return (v1 > v2) ? -1 : 1;
9435            }
9436            if (r1.isDefault != r2.isDefault) {
9437                return r1.isDefault ? -1 : 1;
9438            }
9439            v1 = r1.match;
9440            v2 = r2.match;
9441            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9442            if (v1 != v2) {
9443                return (v1 > v2) ? -1 : 1;
9444            }
9445            if (r1.system != r2.system) {
9446                return r1.system ? -1 : 1;
9447            }
9448            return 0;
9449        }
9450    };
9451
9452    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9453            new Comparator<ProviderInfo>() {
9454        public int compare(ProviderInfo p1, ProviderInfo p2) {
9455            final int v1 = p1.initOrder;
9456            final int v2 = p2.initOrder;
9457            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9458        }
9459    };
9460
9461    final void sendPackageBroadcast(final String action, final String pkg,
9462            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9463            final int[] userIds) {
9464        mHandler.post(new Runnable() {
9465            @Override
9466            public void run() {
9467                try {
9468                    final IActivityManager am = ActivityManagerNative.getDefault();
9469                    if (am == null) return;
9470                    final int[] resolvedUserIds;
9471                    if (userIds == null) {
9472                        resolvedUserIds = am.getRunningUserIds();
9473                    } else {
9474                        resolvedUserIds = userIds;
9475                    }
9476                    for (int id : resolvedUserIds) {
9477                        final Intent intent = new Intent(action,
9478                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9479                        if (extras != null) {
9480                            intent.putExtras(extras);
9481                        }
9482                        if (targetPkg != null) {
9483                            intent.setPackage(targetPkg);
9484                        }
9485                        // Modify the UID when posting to other users
9486                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9487                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9488                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9489                            intent.putExtra(Intent.EXTRA_UID, uid);
9490                        }
9491                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9492                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9493                        if (DEBUG_BROADCASTS) {
9494                            RuntimeException here = new RuntimeException("here");
9495                            here.fillInStackTrace();
9496                            Slog.d(TAG, "Sending to user " + id + ": "
9497                                    + intent.toShortString(false, true, false, false)
9498                                    + " " + intent.getExtras(), here);
9499                        }
9500                        am.broadcastIntent(null, intent, null, finishedReceiver,
9501                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9502                                null, finishedReceiver != null, false, id);
9503                    }
9504                } catch (RemoteException ex) {
9505                }
9506            }
9507        });
9508    }
9509
9510    /**
9511     * Check if the external storage media is available. This is true if there
9512     * is a mounted external storage medium or if the external storage is
9513     * emulated.
9514     */
9515    private boolean isExternalMediaAvailable() {
9516        return mMediaMounted || Environment.isExternalStorageEmulated();
9517    }
9518
9519    @Override
9520    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9521        // writer
9522        synchronized (mPackages) {
9523            if (!isExternalMediaAvailable()) {
9524                // If the external storage is no longer mounted at this point,
9525                // the caller may not have been able to delete all of this
9526                // packages files and can not delete any more.  Bail.
9527                return null;
9528            }
9529            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9530            if (lastPackage != null) {
9531                pkgs.remove(lastPackage);
9532            }
9533            if (pkgs.size() > 0) {
9534                return pkgs.get(0);
9535            }
9536        }
9537        return null;
9538    }
9539
9540    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9541        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9542                userId, andCode ? 1 : 0, packageName);
9543        if (mSystemReady) {
9544            msg.sendToTarget();
9545        } else {
9546            if (mPostSystemReadyMessages == null) {
9547                mPostSystemReadyMessages = new ArrayList<>();
9548            }
9549            mPostSystemReadyMessages.add(msg);
9550        }
9551    }
9552
9553    void startCleaningPackages() {
9554        // reader
9555        synchronized (mPackages) {
9556            if (!isExternalMediaAvailable()) {
9557                return;
9558            }
9559            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9560                return;
9561            }
9562        }
9563        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9564        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9565        IActivityManager am = ActivityManagerNative.getDefault();
9566        if (am != null) {
9567            try {
9568                am.startService(null, intent, null, mContext.getOpPackageName(),
9569                        UserHandle.USER_OWNER);
9570            } catch (RemoteException e) {
9571            }
9572        }
9573    }
9574
9575    @Override
9576    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9577            int installFlags, String installerPackageName, VerificationParams verificationParams,
9578            String packageAbiOverride) {
9579        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9580                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9581    }
9582
9583    @Override
9584    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9585            int installFlags, String installerPackageName, VerificationParams verificationParams,
9586            String packageAbiOverride, int userId) {
9587        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9588
9589        final int callingUid = Binder.getCallingUid();
9590        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9591
9592        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9593            try {
9594                if (observer != null) {
9595                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9596                }
9597            } catch (RemoteException re) {
9598            }
9599            return;
9600        }
9601
9602        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9603            installFlags |= PackageManager.INSTALL_FROM_ADB;
9604
9605        } else {
9606            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9607            // about installerPackageName.
9608
9609            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9610            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9611        }
9612
9613        UserHandle user;
9614        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9615            user = UserHandle.ALL;
9616        } else {
9617            user = new UserHandle(userId);
9618        }
9619
9620        // Only system components can circumvent runtime permissions when installing.
9621        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9622                && mContext.checkCallingOrSelfPermission(Manifest.permission
9623                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9624            throw new SecurityException("You need the "
9625                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9626                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9627        }
9628
9629        verificationParams.setInstallerUid(callingUid);
9630
9631        final File originFile = new File(originPath);
9632        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9633
9634        final Message msg = mHandler.obtainMessage(INIT_COPY);
9635        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9636                null, verificationParams, user, packageAbiOverride, null);
9637        mHandler.sendMessage(msg);
9638    }
9639
9640    void installStage(String packageName, File stagedDir, String stagedCid,
9641            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9642            String installerPackageName, int installerUid, UserHandle user) {
9643        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9644                params.referrerUri, installerUid, null);
9645        verifParams.setInstallerUid(installerUid);
9646
9647        final OriginInfo origin;
9648        if (stagedDir != null) {
9649            origin = OriginInfo.fromStagedFile(stagedDir);
9650        } else {
9651            origin = OriginInfo.fromStagedContainer(stagedCid);
9652        }
9653
9654        final Message msg = mHandler.obtainMessage(INIT_COPY);
9655        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9656                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9657                params.grantedRuntimePermissions);
9658
9659        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9660                System.identityHashCode(msg.obj));
9661
9662        mHandler.sendMessage(msg);
9663    }
9664
9665    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9666        Bundle extras = new Bundle(1);
9667        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9668
9669        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9670                packageName, extras, null, null, new int[] {userId});
9671        try {
9672            IActivityManager am = ActivityManagerNative.getDefault();
9673            final boolean isSystem =
9674                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9675            if (isSystem && am.isUserRunning(userId, false)) {
9676                // The just-installed/enabled app is bundled on the system, so presumed
9677                // to be able to run automatically without needing an explicit launch.
9678                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9679                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9680                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9681                        .setPackage(packageName);
9682                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9683                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9684            }
9685        } catch (RemoteException e) {
9686            // shouldn't happen
9687            Slog.w(TAG, "Unable to bootstrap installed package", e);
9688        }
9689    }
9690
9691    @Override
9692    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9693            int userId) {
9694        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9695        PackageSetting pkgSetting;
9696        final int uid = Binder.getCallingUid();
9697        enforceCrossUserPermission(uid, userId, true, true,
9698                "setApplicationHiddenSetting for user " + userId);
9699
9700        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9701            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9702            return false;
9703        }
9704
9705        long callingId = Binder.clearCallingIdentity();
9706        try {
9707            boolean sendAdded = false;
9708            boolean sendRemoved = false;
9709            // writer
9710            synchronized (mPackages) {
9711                pkgSetting = mSettings.mPackages.get(packageName);
9712                if (pkgSetting == null) {
9713                    return false;
9714                }
9715                if (pkgSetting.getHidden(userId) != hidden) {
9716                    pkgSetting.setHidden(hidden, userId);
9717                    mSettings.writePackageRestrictionsLPr(userId);
9718                    if (hidden) {
9719                        sendRemoved = true;
9720                    } else {
9721                        sendAdded = true;
9722                    }
9723                }
9724            }
9725            if (sendAdded) {
9726                sendPackageAddedForUser(packageName, pkgSetting, userId);
9727                return true;
9728            }
9729            if (sendRemoved) {
9730                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9731                        "hiding pkg");
9732                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9733                return true;
9734            }
9735        } finally {
9736            Binder.restoreCallingIdentity(callingId);
9737        }
9738        return false;
9739    }
9740
9741    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9742            int userId) {
9743        final PackageRemovedInfo info = new PackageRemovedInfo();
9744        info.removedPackage = packageName;
9745        info.removedUsers = new int[] {userId};
9746        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9747        info.sendBroadcast(false, false, false);
9748    }
9749
9750    /**
9751     * Returns true if application is not found or there was an error. Otherwise it returns
9752     * the hidden state of the package for the given user.
9753     */
9754    @Override
9755    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9756        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9757        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9758                false, "getApplicationHidden for user " + userId);
9759        PackageSetting pkgSetting;
9760        long callingId = Binder.clearCallingIdentity();
9761        try {
9762            // writer
9763            synchronized (mPackages) {
9764                pkgSetting = mSettings.mPackages.get(packageName);
9765                if (pkgSetting == null) {
9766                    return true;
9767                }
9768                return pkgSetting.getHidden(userId);
9769            }
9770        } finally {
9771            Binder.restoreCallingIdentity(callingId);
9772        }
9773    }
9774
9775    /**
9776     * @hide
9777     */
9778    @Override
9779    public int installExistingPackageAsUser(String packageName, int userId) {
9780        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9781                null);
9782        PackageSetting pkgSetting;
9783        final int uid = Binder.getCallingUid();
9784        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9785                + userId);
9786        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9787            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9788        }
9789
9790        long callingId = Binder.clearCallingIdentity();
9791        try {
9792            boolean sendAdded = false;
9793
9794            // writer
9795            synchronized (mPackages) {
9796                pkgSetting = mSettings.mPackages.get(packageName);
9797                if (pkgSetting == null) {
9798                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9799                }
9800                if (!pkgSetting.getInstalled(userId)) {
9801                    pkgSetting.setInstalled(true, userId);
9802                    pkgSetting.setHidden(false, userId);
9803                    mSettings.writePackageRestrictionsLPr(userId);
9804                    sendAdded = true;
9805                }
9806            }
9807
9808            if (sendAdded) {
9809                sendPackageAddedForUser(packageName, pkgSetting, userId);
9810            }
9811        } finally {
9812            Binder.restoreCallingIdentity(callingId);
9813        }
9814
9815        return PackageManager.INSTALL_SUCCEEDED;
9816    }
9817
9818    boolean isUserRestricted(int userId, String restrictionKey) {
9819        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9820        if (restrictions.getBoolean(restrictionKey, false)) {
9821            Log.w(TAG, "User is restricted: " + restrictionKey);
9822            return true;
9823        }
9824        return false;
9825    }
9826
9827    @Override
9828    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9829        mContext.enforceCallingOrSelfPermission(
9830                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9831                "Only package verification agents can verify applications");
9832
9833        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9834        final PackageVerificationResponse response = new PackageVerificationResponse(
9835                verificationCode, Binder.getCallingUid());
9836        msg.arg1 = id;
9837        msg.obj = response;
9838        mHandler.sendMessage(msg);
9839    }
9840
9841    @Override
9842    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9843            long millisecondsToDelay) {
9844        mContext.enforceCallingOrSelfPermission(
9845                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9846                "Only package verification agents can extend verification timeouts");
9847
9848        final PackageVerificationState state = mPendingVerification.get(id);
9849        final PackageVerificationResponse response = new PackageVerificationResponse(
9850                verificationCodeAtTimeout, Binder.getCallingUid());
9851
9852        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9853            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9854        }
9855        if (millisecondsToDelay < 0) {
9856            millisecondsToDelay = 0;
9857        }
9858        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9859                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9860            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9861        }
9862
9863        if ((state != null) && !state.timeoutExtended()) {
9864            state.extendTimeout();
9865
9866            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9867            msg.arg1 = id;
9868            msg.obj = response;
9869            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9870        }
9871    }
9872
9873    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9874            int verificationCode, UserHandle user) {
9875        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9876        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9877        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9878        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9879        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9880
9881        mContext.sendBroadcastAsUser(intent, user,
9882                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9883    }
9884
9885    private ComponentName matchComponentForVerifier(String packageName,
9886            List<ResolveInfo> receivers) {
9887        ActivityInfo targetReceiver = null;
9888
9889        final int NR = receivers.size();
9890        for (int i = 0; i < NR; i++) {
9891            final ResolveInfo info = receivers.get(i);
9892            if (info.activityInfo == null) {
9893                continue;
9894            }
9895
9896            if (packageName.equals(info.activityInfo.packageName)) {
9897                targetReceiver = info.activityInfo;
9898                break;
9899            }
9900        }
9901
9902        if (targetReceiver == null) {
9903            return null;
9904        }
9905
9906        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9907    }
9908
9909    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9910            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9911        if (pkgInfo.verifiers.length == 0) {
9912            return null;
9913        }
9914
9915        final int N = pkgInfo.verifiers.length;
9916        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9917        for (int i = 0; i < N; i++) {
9918            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9919
9920            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9921                    receivers);
9922            if (comp == null) {
9923                continue;
9924            }
9925
9926            final int verifierUid = getUidForVerifier(verifierInfo);
9927            if (verifierUid == -1) {
9928                continue;
9929            }
9930
9931            if (DEBUG_VERIFY) {
9932                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9933                        + " with the correct signature");
9934            }
9935            sufficientVerifiers.add(comp);
9936            verificationState.addSufficientVerifier(verifierUid);
9937        }
9938
9939        return sufficientVerifiers;
9940    }
9941
9942    private int getUidForVerifier(VerifierInfo verifierInfo) {
9943        synchronized (mPackages) {
9944            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9945            if (pkg == null) {
9946                return -1;
9947            } else if (pkg.mSignatures.length != 1) {
9948                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9949                        + " has more than one signature; ignoring");
9950                return -1;
9951            }
9952
9953            /*
9954             * If the public key of the package's signature does not match
9955             * our expected public key, then this is a different package and
9956             * we should skip.
9957             */
9958
9959            final byte[] expectedPublicKey;
9960            try {
9961                final Signature verifierSig = pkg.mSignatures[0];
9962                final PublicKey publicKey = verifierSig.getPublicKey();
9963                expectedPublicKey = publicKey.getEncoded();
9964            } catch (CertificateException e) {
9965                return -1;
9966            }
9967
9968            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9969
9970            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9971                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9972                        + " does not have the expected public key; ignoring");
9973                return -1;
9974            }
9975
9976            return pkg.applicationInfo.uid;
9977        }
9978    }
9979
9980    @Override
9981    public void finishPackageInstall(int token) {
9982        enforceSystemOrRoot("Only the system is allowed to finish installs");
9983
9984        if (DEBUG_INSTALL) {
9985            Slog.v(TAG, "BM finishing package install for " + token);
9986        }
9987
9988        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9989        mHandler.sendMessage(msg);
9990    }
9991
9992    /**
9993     * Get the verification agent timeout.
9994     *
9995     * @return verification timeout in milliseconds
9996     */
9997    private long getVerificationTimeout() {
9998        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9999                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10000                DEFAULT_VERIFICATION_TIMEOUT);
10001    }
10002
10003    /**
10004     * Get the default verification agent response code.
10005     *
10006     * @return default verification response code
10007     */
10008    private int getDefaultVerificationResponse() {
10009        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10010                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10011                DEFAULT_VERIFICATION_RESPONSE);
10012    }
10013
10014    /**
10015     * Check whether or not package verification has been enabled.
10016     *
10017     * @return true if verification should be performed
10018     */
10019    private boolean isVerificationEnabled(int userId, int installFlags) {
10020        if (!DEFAULT_VERIFY_ENABLE) {
10021            return false;
10022        }
10023
10024        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10025
10026        // Check if installing from ADB
10027        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10028            // Do not run verification in a test harness environment
10029            if (ActivityManager.isRunningInTestHarness()) {
10030                return false;
10031            }
10032            if (ensureVerifyAppsEnabled) {
10033                return true;
10034            }
10035            // Check if the developer does not want package verification for ADB installs
10036            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10037                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10038                return false;
10039            }
10040        }
10041
10042        if (ensureVerifyAppsEnabled) {
10043            return true;
10044        }
10045
10046        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10047                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10048    }
10049
10050    @Override
10051    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10052            throws RemoteException {
10053        mContext.enforceCallingOrSelfPermission(
10054                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10055                "Only intentfilter verification agents can verify applications");
10056
10057        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10058        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10059                Binder.getCallingUid(), verificationCode, failedDomains);
10060        msg.arg1 = id;
10061        msg.obj = response;
10062        mHandler.sendMessage(msg);
10063    }
10064
10065    @Override
10066    public int getIntentVerificationStatus(String packageName, int userId) {
10067        synchronized (mPackages) {
10068            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10069        }
10070    }
10071
10072    @Override
10073    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10074        mContext.enforceCallingOrSelfPermission(
10075                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10076
10077        boolean result = false;
10078        synchronized (mPackages) {
10079            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10080        }
10081        if (result) {
10082            scheduleWritePackageRestrictionsLocked(userId);
10083        }
10084        return result;
10085    }
10086
10087    @Override
10088    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10089        synchronized (mPackages) {
10090            return mSettings.getIntentFilterVerificationsLPr(packageName);
10091        }
10092    }
10093
10094    @Override
10095    public List<IntentFilter> getAllIntentFilters(String packageName) {
10096        if (TextUtils.isEmpty(packageName)) {
10097            return Collections.<IntentFilter>emptyList();
10098        }
10099        synchronized (mPackages) {
10100            PackageParser.Package pkg = mPackages.get(packageName);
10101            if (pkg == null || pkg.activities == null) {
10102                return Collections.<IntentFilter>emptyList();
10103            }
10104            final int count = pkg.activities.size();
10105            ArrayList<IntentFilter> result = new ArrayList<>();
10106            for (int n=0; n<count; n++) {
10107                PackageParser.Activity activity = pkg.activities.get(n);
10108                if (activity.intents != null || activity.intents.size() > 0) {
10109                    result.addAll(activity.intents);
10110                }
10111            }
10112            return result;
10113        }
10114    }
10115
10116    @Override
10117    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10118        mContext.enforceCallingOrSelfPermission(
10119                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10120
10121        synchronized (mPackages) {
10122            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10123            if (packageName != null) {
10124                result |= updateIntentVerificationStatus(packageName,
10125                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10126                        userId);
10127                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10128                        packageName, userId);
10129            }
10130            return result;
10131        }
10132    }
10133
10134    @Override
10135    public String getDefaultBrowserPackageName(int userId) {
10136        synchronized (mPackages) {
10137            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10138        }
10139    }
10140
10141    /**
10142     * Get the "allow unknown sources" setting.
10143     *
10144     * @return the current "allow unknown sources" setting
10145     */
10146    private int getUnknownSourcesSettings() {
10147        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10148                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10149                -1);
10150    }
10151
10152    @Override
10153    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10154        final int uid = Binder.getCallingUid();
10155        // writer
10156        synchronized (mPackages) {
10157            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10158            if (targetPackageSetting == null) {
10159                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10160            }
10161
10162            PackageSetting installerPackageSetting;
10163            if (installerPackageName != null) {
10164                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10165                if (installerPackageSetting == null) {
10166                    throw new IllegalArgumentException("Unknown installer package: "
10167                            + installerPackageName);
10168                }
10169            } else {
10170                installerPackageSetting = null;
10171            }
10172
10173            Signature[] callerSignature;
10174            Object obj = mSettings.getUserIdLPr(uid);
10175            if (obj != null) {
10176                if (obj instanceof SharedUserSetting) {
10177                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10178                } else if (obj instanceof PackageSetting) {
10179                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10180                } else {
10181                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10182                }
10183            } else {
10184                throw new SecurityException("Unknown calling uid " + uid);
10185            }
10186
10187            // Verify: can't set installerPackageName to a package that is
10188            // not signed with the same cert as the caller.
10189            if (installerPackageSetting != null) {
10190                if (compareSignatures(callerSignature,
10191                        installerPackageSetting.signatures.mSignatures)
10192                        != PackageManager.SIGNATURE_MATCH) {
10193                    throw new SecurityException(
10194                            "Caller does not have same cert as new installer package "
10195                            + installerPackageName);
10196                }
10197            }
10198
10199            // Verify: if target already has an installer package, it must
10200            // be signed with the same cert as the caller.
10201            if (targetPackageSetting.installerPackageName != null) {
10202                PackageSetting setting = mSettings.mPackages.get(
10203                        targetPackageSetting.installerPackageName);
10204                // If the currently set package isn't valid, then it's always
10205                // okay to change it.
10206                if (setting != null) {
10207                    if (compareSignatures(callerSignature,
10208                            setting.signatures.mSignatures)
10209                            != PackageManager.SIGNATURE_MATCH) {
10210                        throw new SecurityException(
10211                                "Caller does not have same cert as old installer package "
10212                                + targetPackageSetting.installerPackageName);
10213                    }
10214                }
10215            }
10216
10217            // Okay!
10218            targetPackageSetting.installerPackageName = installerPackageName;
10219            scheduleWriteSettingsLocked();
10220        }
10221    }
10222
10223    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10224        // Queue up an async operation since the package installation may take a little while.
10225        mHandler.post(new Runnable() {
10226            public void run() {
10227                mHandler.removeCallbacks(this);
10228                 // Result object to be returned
10229                PackageInstalledInfo res = new PackageInstalledInfo();
10230                res.returnCode = currentStatus;
10231                res.uid = -1;
10232                res.pkg = null;
10233                res.removedInfo = new PackageRemovedInfo();
10234                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10235                    args.doPreInstall(res.returnCode);
10236                    synchronized (mInstallLock) {
10237                        installPackageTracedLI(args, res);
10238                    }
10239                    args.doPostInstall(res.returnCode, res.uid);
10240                }
10241
10242                // A restore should be performed at this point if (a) the install
10243                // succeeded, (b) the operation is not an update, and (c) the new
10244                // package has not opted out of backup participation.
10245                final boolean update = res.removedInfo.removedPackage != null;
10246                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10247                boolean doRestore = !update
10248                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10249
10250                // Set up the post-install work request bookkeeping.  This will be used
10251                // and cleaned up by the post-install event handling regardless of whether
10252                // there's a restore pass performed.  Token values are >= 1.
10253                int token;
10254                if (mNextInstallToken < 0) mNextInstallToken = 1;
10255                token = mNextInstallToken++;
10256
10257                PostInstallData data = new PostInstallData(args, res);
10258                mRunningInstalls.put(token, data);
10259                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10260
10261                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10262                    // Pass responsibility to the Backup Manager.  It will perform a
10263                    // restore if appropriate, then pass responsibility back to the
10264                    // Package Manager to run the post-install observer callbacks
10265                    // and broadcasts.
10266                    IBackupManager bm = IBackupManager.Stub.asInterface(
10267                            ServiceManager.getService(Context.BACKUP_SERVICE));
10268                    if (bm != null) {
10269                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10270                                + " to BM for possible restore");
10271                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10272                        try {
10273                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10274                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10275                            } else {
10276                                doRestore = false;
10277                            }
10278                        } catch (RemoteException e) {
10279                            // can't happen; the backup manager is local
10280                        } catch (Exception e) {
10281                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10282                            doRestore = false;
10283                        } finally {
10284                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10285                        }
10286                    } else {
10287                        Slog.e(TAG, "Backup Manager not found!");
10288                        doRestore = false;
10289                    }
10290                }
10291
10292                if (!doRestore) {
10293                    // No restore possible, or the Backup Manager was mysteriously not
10294                    // available -- just fire the post-install work request directly.
10295                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10296
10297                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10298
10299                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10300                    mHandler.sendMessage(msg);
10301                }
10302            }
10303        });
10304    }
10305
10306    private abstract class HandlerParams {
10307        private static final int MAX_RETRIES = 4;
10308
10309        /**
10310         * Number of times startCopy() has been attempted and had a non-fatal
10311         * error.
10312         */
10313        private int mRetries = 0;
10314
10315        /** User handle for the user requesting the information or installation. */
10316        private final UserHandle mUser;
10317
10318        HandlerParams(UserHandle user) {
10319            mUser = user;
10320        }
10321
10322        UserHandle getUser() {
10323            return mUser;
10324        }
10325
10326        final boolean startCopy() {
10327            boolean res;
10328            try {
10329                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10330
10331                if (++mRetries > MAX_RETRIES) {
10332                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10333                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10334                    handleServiceError();
10335                    return false;
10336                } else {
10337                    handleStartCopy();
10338                    res = true;
10339                }
10340            } catch (RemoteException e) {
10341                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10342                mHandler.sendEmptyMessage(MCS_RECONNECT);
10343                res = false;
10344            }
10345            handleReturnCode();
10346            return res;
10347        }
10348
10349        final void serviceError() {
10350            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10351            handleServiceError();
10352            handleReturnCode();
10353        }
10354
10355        abstract void handleStartCopy() throws RemoteException;
10356        abstract void handleServiceError();
10357        abstract void handleReturnCode();
10358    }
10359
10360    class MeasureParams extends HandlerParams {
10361        private final PackageStats mStats;
10362        private boolean mSuccess;
10363
10364        private final IPackageStatsObserver mObserver;
10365
10366        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10367            super(new UserHandle(stats.userHandle));
10368            mObserver = observer;
10369            mStats = stats;
10370        }
10371
10372        @Override
10373        public String toString() {
10374            return "MeasureParams{"
10375                + Integer.toHexString(System.identityHashCode(this))
10376                + " " + mStats.packageName + "}";
10377        }
10378
10379        @Override
10380        void handleStartCopy() throws RemoteException {
10381            synchronized (mInstallLock) {
10382                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10383            }
10384
10385            if (mSuccess) {
10386                final boolean mounted;
10387                if (Environment.isExternalStorageEmulated()) {
10388                    mounted = true;
10389                } else {
10390                    final String status = Environment.getExternalStorageState();
10391                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10392                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10393                }
10394
10395                if (mounted) {
10396                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10397
10398                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10399                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10400
10401                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10402                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10403
10404                    // Always subtract cache size, since it's a subdirectory
10405                    mStats.externalDataSize -= mStats.externalCacheSize;
10406
10407                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10408                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10409
10410                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10411                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10412                }
10413            }
10414        }
10415
10416        @Override
10417        void handleReturnCode() {
10418            if (mObserver != null) {
10419                try {
10420                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10421                } catch (RemoteException e) {
10422                    Slog.i(TAG, "Observer no longer exists.");
10423                }
10424            }
10425        }
10426
10427        @Override
10428        void handleServiceError() {
10429            Slog.e(TAG, "Could not measure application " + mStats.packageName
10430                            + " external storage");
10431        }
10432    }
10433
10434    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10435            throws RemoteException {
10436        long result = 0;
10437        for (File path : paths) {
10438            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10439        }
10440        return result;
10441    }
10442
10443    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10444        for (File path : paths) {
10445            try {
10446                mcs.clearDirectory(path.getAbsolutePath());
10447            } catch (RemoteException e) {
10448            }
10449        }
10450    }
10451
10452    static class OriginInfo {
10453        /**
10454         * Location where install is coming from, before it has been
10455         * copied/renamed into place. This could be a single monolithic APK
10456         * file, or a cluster directory. This location may be untrusted.
10457         */
10458        final File file;
10459        final String cid;
10460
10461        /**
10462         * Flag indicating that {@link #file} or {@link #cid} has already been
10463         * staged, meaning downstream users don't need to defensively copy the
10464         * contents.
10465         */
10466        final boolean staged;
10467
10468        /**
10469         * Flag indicating that {@link #file} or {@link #cid} is an already
10470         * installed app that is being moved.
10471         */
10472        final boolean existing;
10473
10474        final String resolvedPath;
10475        final File resolvedFile;
10476
10477        static OriginInfo fromNothing() {
10478            return new OriginInfo(null, null, false, false);
10479        }
10480
10481        static OriginInfo fromUntrustedFile(File file) {
10482            return new OriginInfo(file, null, false, false);
10483        }
10484
10485        static OriginInfo fromExistingFile(File file) {
10486            return new OriginInfo(file, null, false, true);
10487        }
10488
10489        static OriginInfo fromStagedFile(File file) {
10490            return new OriginInfo(file, null, true, false);
10491        }
10492
10493        static OriginInfo fromStagedContainer(String cid) {
10494            return new OriginInfo(null, cid, true, false);
10495        }
10496
10497        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10498            this.file = file;
10499            this.cid = cid;
10500            this.staged = staged;
10501            this.existing = existing;
10502
10503            if (cid != null) {
10504                resolvedPath = PackageHelper.getSdDir(cid);
10505                resolvedFile = new File(resolvedPath);
10506            } else if (file != null) {
10507                resolvedPath = file.getAbsolutePath();
10508                resolvedFile = file;
10509            } else {
10510                resolvedPath = null;
10511                resolvedFile = null;
10512            }
10513        }
10514    }
10515
10516    class MoveInfo {
10517        final int moveId;
10518        final String fromUuid;
10519        final String toUuid;
10520        final String packageName;
10521        final String dataAppName;
10522        final int appId;
10523        final String seinfo;
10524
10525        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10526                String dataAppName, int appId, String seinfo) {
10527            this.moveId = moveId;
10528            this.fromUuid = fromUuid;
10529            this.toUuid = toUuid;
10530            this.packageName = packageName;
10531            this.dataAppName = dataAppName;
10532            this.appId = appId;
10533            this.seinfo = seinfo;
10534        }
10535    }
10536
10537    class InstallParams extends HandlerParams {
10538        final OriginInfo origin;
10539        final MoveInfo move;
10540        final IPackageInstallObserver2 observer;
10541        int installFlags;
10542        final String installerPackageName;
10543        final String volumeUuid;
10544        final VerificationParams verificationParams;
10545        private InstallArgs mArgs;
10546        private int mRet;
10547        final String packageAbiOverride;
10548        final String[] grantedRuntimePermissions;
10549
10550
10551        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10552                int installFlags, String installerPackageName, String volumeUuid,
10553                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10554                String[] grantedPermissions) {
10555            super(user);
10556            this.origin = origin;
10557            this.move = move;
10558            this.observer = observer;
10559            this.installFlags = installFlags;
10560            this.installerPackageName = installerPackageName;
10561            this.volumeUuid = volumeUuid;
10562            this.verificationParams = verificationParams;
10563            this.packageAbiOverride = packageAbiOverride;
10564            this.grantedRuntimePermissions = grantedPermissions;
10565        }
10566
10567        @Override
10568        public String toString() {
10569            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10570                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10571        }
10572
10573        public ManifestDigest getManifestDigest() {
10574            if (verificationParams == null) {
10575                return null;
10576            }
10577            return verificationParams.getManifestDigest();
10578        }
10579
10580        private int installLocationPolicy(PackageInfoLite pkgLite) {
10581            String packageName = pkgLite.packageName;
10582            int installLocation = pkgLite.installLocation;
10583            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10584            // reader
10585            synchronized (mPackages) {
10586                PackageParser.Package pkg = mPackages.get(packageName);
10587                if (pkg != null) {
10588                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10589                        // Check for downgrading.
10590                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10591                            try {
10592                                checkDowngrade(pkg, pkgLite);
10593                            } catch (PackageManagerException e) {
10594                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10595                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10596                            }
10597                        }
10598                        // Check for updated system application.
10599                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10600                            if (onSd) {
10601                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10602                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10603                            }
10604                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10605                        } else {
10606                            if (onSd) {
10607                                // Install flag overrides everything.
10608                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10609                            }
10610                            // If current upgrade specifies particular preference
10611                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10612                                // Application explicitly specified internal.
10613                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10614                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10615                                // App explictly prefers external. Let policy decide
10616                            } else {
10617                                // Prefer previous location
10618                                if (isExternal(pkg)) {
10619                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10620                                }
10621                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10622                            }
10623                        }
10624                    } else {
10625                        // Invalid install. Return error code
10626                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10627                    }
10628                }
10629            }
10630            // All the special cases have been taken care of.
10631            // Return result based on recommended install location.
10632            if (onSd) {
10633                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10634            }
10635            return pkgLite.recommendedInstallLocation;
10636        }
10637
10638        /*
10639         * Invoke remote method to get package information and install
10640         * location values. Override install location based on default
10641         * policy if needed and then create install arguments based
10642         * on the install location.
10643         */
10644        public void handleStartCopy() throws RemoteException {
10645            int ret = PackageManager.INSTALL_SUCCEEDED;
10646
10647            // If we're already staged, we've firmly committed to an install location
10648            if (origin.staged) {
10649                if (origin.file != null) {
10650                    installFlags |= PackageManager.INSTALL_INTERNAL;
10651                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10652                } else if (origin.cid != null) {
10653                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10654                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10655                } else {
10656                    throw new IllegalStateException("Invalid stage location");
10657                }
10658            }
10659
10660            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10661            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10662            PackageInfoLite pkgLite = null;
10663
10664            if (onInt && onSd) {
10665                // Check if both bits are set.
10666                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10667                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10668            } else {
10669                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10670                        packageAbiOverride);
10671
10672                /*
10673                 * If we have too little free space, try to free cache
10674                 * before giving up.
10675                 */
10676                if (!origin.staged && pkgLite.recommendedInstallLocation
10677                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10678                    // TODO: focus freeing disk space on the target device
10679                    final StorageManager storage = StorageManager.from(mContext);
10680                    final long lowThreshold = storage.getStorageLowBytes(
10681                            Environment.getDataDirectory());
10682
10683                    final long sizeBytes = mContainerService.calculateInstalledSize(
10684                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10685
10686                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10687                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10688                                installFlags, packageAbiOverride);
10689                    }
10690
10691                    /*
10692                     * The cache free must have deleted the file we
10693                     * downloaded to install.
10694                     *
10695                     * TODO: fix the "freeCache" call to not delete
10696                     *       the file we care about.
10697                     */
10698                    if (pkgLite.recommendedInstallLocation
10699                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10700                        pkgLite.recommendedInstallLocation
10701                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10702                    }
10703                }
10704            }
10705
10706            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10707                int loc = pkgLite.recommendedInstallLocation;
10708                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10709                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10710                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10711                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10712                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10713                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10714                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10715                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10716                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10717                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10718                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10719                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10720                } else {
10721                    // Override with defaults if needed.
10722                    loc = installLocationPolicy(pkgLite);
10723                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10724                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10725                    } else if (!onSd && !onInt) {
10726                        // Override install location with flags
10727                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10728                            // Set the flag to install on external media.
10729                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10730                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10731                        } else {
10732                            // Make sure the flag for installing on external
10733                            // media is unset
10734                            installFlags |= PackageManager.INSTALL_INTERNAL;
10735                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10736                        }
10737                    }
10738                }
10739            }
10740
10741            final InstallArgs args = createInstallArgs(this);
10742            mArgs = args;
10743
10744            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10745                 /*
10746                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10747                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10748                 */
10749                int userIdentifier = getUser().getIdentifier();
10750                if (userIdentifier == UserHandle.USER_ALL
10751                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10752                    userIdentifier = UserHandle.USER_OWNER;
10753                }
10754
10755                /*
10756                 * Determine if we have any installed package verifiers. If we
10757                 * do, then we'll defer to them to verify the packages.
10758                 */
10759                final int requiredUid = mRequiredVerifierPackage == null ? -1
10760                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10761                if (!origin.existing && requiredUid != -1
10762                        && isVerificationEnabled(userIdentifier, installFlags)) {
10763                    final Intent verification = new Intent(
10764                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10765                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10766                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10767                            PACKAGE_MIME_TYPE);
10768                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10769
10770                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10771                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10772                            0 /* TODO: Which userId? */);
10773
10774                    if (DEBUG_VERIFY) {
10775                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10776                                + verification.toString() + " with " + pkgLite.verifiers.length
10777                                + " optional verifiers");
10778                    }
10779
10780                    final int verificationId = mPendingVerificationToken++;
10781
10782                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10783
10784                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10785                            installerPackageName);
10786
10787                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10788                            installFlags);
10789
10790                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10791                            pkgLite.packageName);
10792
10793                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10794                            pkgLite.versionCode);
10795
10796                    if (verificationParams != null) {
10797                        if (verificationParams.getVerificationURI() != null) {
10798                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10799                                 verificationParams.getVerificationURI());
10800                        }
10801                        if (verificationParams.getOriginatingURI() != null) {
10802                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10803                                  verificationParams.getOriginatingURI());
10804                        }
10805                        if (verificationParams.getReferrer() != null) {
10806                            verification.putExtra(Intent.EXTRA_REFERRER,
10807                                  verificationParams.getReferrer());
10808                        }
10809                        if (verificationParams.getOriginatingUid() >= 0) {
10810                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10811                                  verificationParams.getOriginatingUid());
10812                        }
10813                        if (verificationParams.getInstallerUid() >= 0) {
10814                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10815                                  verificationParams.getInstallerUid());
10816                        }
10817                    }
10818
10819                    final PackageVerificationState verificationState = new PackageVerificationState(
10820                            requiredUid, args);
10821
10822                    mPendingVerification.append(verificationId, verificationState);
10823
10824                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10825                            receivers, verificationState);
10826
10827                    // Apps installed for "all" users use the device owner to verify the app
10828                    UserHandle verifierUser = getUser();
10829                    if (verifierUser == UserHandle.ALL) {
10830                        verifierUser = UserHandle.OWNER;
10831                    }
10832
10833                    /*
10834                     * If any sufficient verifiers were listed in the package
10835                     * manifest, attempt to ask them.
10836                     */
10837                    if (sufficientVerifiers != null) {
10838                        final int N = sufficientVerifiers.size();
10839                        if (N == 0) {
10840                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10841                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10842                        } else {
10843                            for (int i = 0; i < N; i++) {
10844                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10845
10846                                final Intent sufficientIntent = new Intent(verification);
10847                                sufficientIntent.setComponent(verifierComponent);
10848                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10849                            }
10850                        }
10851                    }
10852
10853                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10854                            mRequiredVerifierPackage, receivers);
10855                    if (ret == PackageManager.INSTALL_SUCCEEDED
10856                            && mRequiredVerifierPackage != null) {
10857                        Trace.asyncTraceBegin(
10858                                TRACE_TAG_PACKAGE_MANAGER, "pendingVerification", verificationId);
10859                        /*
10860                         * Send the intent to the required verification agent,
10861                         * but only start the verification timeout after the
10862                         * target BroadcastReceivers have run.
10863                         */
10864                        verification.setComponent(requiredVerifierComponent);
10865                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10866                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10867                                new BroadcastReceiver() {
10868                                    @Override
10869                                    public void onReceive(Context context, Intent intent) {
10870                                        final Message msg = mHandler
10871                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10872                                        msg.arg1 = verificationId;
10873                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10874                                    }
10875                                }, null, 0, null, null);
10876
10877                        /*
10878                         * We don't want the copy to proceed until verification
10879                         * succeeds, so null out this field.
10880                         */
10881                        mArgs = null;
10882                    }
10883                } else {
10884                    /*
10885                     * No package verification is enabled, so immediately start
10886                     * the remote call to initiate copy using temporary file.
10887                     */
10888                    ret = args.copyApk(mContainerService, true);
10889                }
10890            }
10891
10892            mRet = ret;
10893        }
10894
10895        @Override
10896        void handleReturnCode() {
10897            // If mArgs is null, then MCS couldn't be reached. When it
10898            // reconnects, it will try again to install. At that point, this
10899            // will succeed.
10900            if (mArgs != null) {
10901                processPendingInstall(mArgs, mRet);
10902            }
10903        }
10904
10905        @Override
10906        void handleServiceError() {
10907            mArgs = createInstallArgs(this);
10908            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10909        }
10910
10911        public boolean isForwardLocked() {
10912            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10913        }
10914    }
10915
10916    /**
10917     * Used during creation of InstallArgs
10918     *
10919     * @param installFlags package installation flags
10920     * @return true if should be installed on external storage
10921     */
10922    private static boolean installOnExternalAsec(int installFlags) {
10923        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10924            return false;
10925        }
10926        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10927            return true;
10928        }
10929        return false;
10930    }
10931
10932    /**
10933     * Used during creation of InstallArgs
10934     *
10935     * @param installFlags package installation flags
10936     * @return true if should be installed as forward locked
10937     */
10938    private static boolean installForwardLocked(int installFlags) {
10939        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10940    }
10941
10942    private InstallArgs createInstallArgs(InstallParams params) {
10943        if (params.move != null) {
10944            return new MoveInstallArgs(params);
10945        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10946            return new AsecInstallArgs(params);
10947        } else {
10948            return new FileInstallArgs(params);
10949        }
10950    }
10951
10952    /**
10953     * Create args that describe an existing installed package. Typically used
10954     * when cleaning up old installs, or used as a move source.
10955     */
10956    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10957            String resourcePath, String[] instructionSets) {
10958        final boolean isInAsec;
10959        if (installOnExternalAsec(installFlags)) {
10960            /* Apps on SD card are always in ASEC containers. */
10961            isInAsec = true;
10962        } else if (installForwardLocked(installFlags)
10963                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10964            /*
10965             * Forward-locked apps are only in ASEC containers if they're the
10966             * new style
10967             */
10968            isInAsec = true;
10969        } else {
10970            isInAsec = false;
10971        }
10972
10973        if (isInAsec) {
10974            return new AsecInstallArgs(codePath, instructionSets,
10975                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10976        } else {
10977            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10978        }
10979    }
10980
10981    static abstract class InstallArgs {
10982        /** @see InstallParams#origin */
10983        final OriginInfo origin;
10984        /** @see InstallParams#move */
10985        final MoveInfo move;
10986
10987        final IPackageInstallObserver2 observer;
10988        // Always refers to PackageManager flags only
10989        final int installFlags;
10990        final String installerPackageName;
10991        final String volumeUuid;
10992        final ManifestDigest manifestDigest;
10993        final UserHandle user;
10994        final String abiOverride;
10995        final String[] installGrantPermissions;
10996
10997        // The list of instruction sets supported by this app. This is currently
10998        // only used during the rmdex() phase to clean up resources. We can get rid of this
10999        // if we move dex files under the common app path.
11000        /* nullable */ String[] instructionSets;
11001
11002        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11003                int installFlags, String installerPackageName, String volumeUuid,
11004                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11005                String abiOverride, String[] installGrantPermissions) {
11006            this.origin = origin;
11007            this.move = move;
11008            this.installFlags = installFlags;
11009            this.observer = observer;
11010            this.installerPackageName = installerPackageName;
11011            this.volumeUuid = volumeUuid;
11012            this.manifestDigest = manifestDigest;
11013            this.user = user;
11014            this.instructionSets = instructionSets;
11015            this.abiOverride = abiOverride;
11016            this.installGrantPermissions = installGrantPermissions;
11017        }
11018
11019        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11020        abstract int doPreInstall(int status);
11021
11022        /**
11023         * Rename package into final resting place. All paths on the given
11024         * scanned package should be updated to reflect the rename.
11025         */
11026        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11027        abstract int doPostInstall(int status, int uid);
11028
11029        /** @see PackageSettingBase#codePathString */
11030        abstract String getCodePath();
11031        /** @see PackageSettingBase#resourcePathString */
11032        abstract String getResourcePath();
11033
11034        // Need installer lock especially for dex file removal.
11035        abstract void cleanUpResourcesLI();
11036        abstract boolean doPostDeleteLI(boolean delete);
11037
11038        /**
11039         * Called before the source arguments are copied. This is used mostly
11040         * for MoveParams when it needs to read the source file to put it in the
11041         * destination.
11042         */
11043        int doPreCopy() {
11044            return PackageManager.INSTALL_SUCCEEDED;
11045        }
11046
11047        /**
11048         * Called after the source arguments are copied. This is used mostly for
11049         * MoveParams when it needs to read the source file to put it in the
11050         * destination.
11051         *
11052         * @return
11053         */
11054        int doPostCopy(int uid) {
11055            return PackageManager.INSTALL_SUCCEEDED;
11056        }
11057
11058        protected boolean isFwdLocked() {
11059            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11060        }
11061
11062        protected boolean isExternalAsec() {
11063            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11064        }
11065
11066        UserHandle getUser() {
11067            return user;
11068        }
11069    }
11070
11071    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11072        if (!allCodePaths.isEmpty()) {
11073            if (instructionSets == null) {
11074                throw new IllegalStateException("instructionSet == null");
11075            }
11076            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11077            for (String codePath : allCodePaths) {
11078                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11079                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11080                    if (retCode < 0) {
11081                        Slog.w(TAG, "Couldn't remove dex file for package: "
11082                                + " at location " + codePath + ", retcode=" + retCode);
11083                        // we don't consider this to be a failure of the core package deletion
11084                    }
11085                }
11086            }
11087        }
11088    }
11089
11090    /**
11091     * Logic to handle installation of non-ASEC applications, including copying
11092     * and renaming logic.
11093     */
11094    class FileInstallArgs extends InstallArgs {
11095        private File codeFile;
11096        private File resourceFile;
11097
11098        // Example topology:
11099        // /data/app/com.example/base.apk
11100        // /data/app/com.example/split_foo.apk
11101        // /data/app/com.example/lib/arm/libfoo.so
11102        // /data/app/com.example/lib/arm64/libfoo.so
11103        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11104
11105        /** New install */
11106        FileInstallArgs(InstallParams params) {
11107            super(params.origin, params.move, params.observer, params.installFlags,
11108                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11109                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11110                    params.grantedRuntimePermissions);
11111            if (isFwdLocked()) {
11112                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11113            }
11114        }
11115
11116        /** Existing install */
11117        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11118            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11119                    null, null);
11120            this.codeFile = (codePath != null) ? new File(codePath) : null;
11121            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11122        }
11123
11124        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11125            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11126            try {
11127                return doCopyApk(imcs, temp);
11128            } finally {
11129                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11130            }
11131        }
11132
11133        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11134            if (origin.staged) {
11135                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11136                codeFile = origin.file;
11137                resourceFile = origin.file;
11138                return PackageManager.INSTALL_SUCCEEDED;
11139            }
11140
11141            try {
11142                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11143                codeFile = tempDir;
11144                resourceFile = tempDir;
11145            } catch (IOException e) {
11146                Slog.w(TAG, "Failed to create copy file: " + e);
11147                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11148            }
11149
11150            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11151                @Override
11152                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11153                    if (!FileUtils.isValidExtFilename(name)) {
11154                        throw new IllegalArgumentException("Invalid filename: " + name);
11155                    }
11156                    try {
11157                        final File file = new File(codeFile, name);
11158                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11159                                O_RDWR | O_CREAT, 0644);
11160                        Os.chmod(file.getAbsolutePath(), 0644);
11161                        return new ParcelFileDescriptor(fd);
11162                    } catch (ErrnoException e) {
11163                        throw new RemoteException("Failed to open: " + e.getMessage());
11164                    }
11165                }
11166            };
11167
11168            int ret = PackageManager.INSTALL_SUCCEEDED;
11169            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11170            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11171                Slog.e(TAG, "Failed to copy package");
11172                return ret;
11173            }
11174
11175            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11176            NativeLibraryHelper.Handle handle = null;
11177            try {
11178                handle = NativeLibraryHelper.Handle.create(codeFile);
11179                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11180                        abiOverride);
11181            } catch (IOException e) {
11182                Slog.e(TAG, "Copying native libraries failed", e);
11183                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11184            } finally {
11185                IoUtils.closeQuietly(handle);
11186            }
11187
11188            return ret;
11189        }
11190
11191        int doPreInstall(int status) {
11192            if (status != PackageManager.INSTALL_SUCCEEDED) {
11193                cleanUp();
11194            }
11195            return status;
11196        }
11197
11198        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11199            if (status != PackageManager.INSTALL_SUCCEEDED) {
11200                cleanUp();
11201                return false;
11202            }
11203
11204            final File targetDir = codeFile.getParentFile();
11205            final File beforeCodeFile = codeFile;
11206            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11207
11208            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11209            try {
11210                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11211            } catch (ErrnoException e) {
11212                Slog.w(TAG, "Failed to rename", e);
11213                return false;
11214            }
11215
11216            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11217                Slog.w(TAG, "Failed to restorecon");
11218                return false;
11219            }
11220
11221            // Reflect the rename internally
11222            codeFile = afterCodeFile;
11223            resourceFile = afterCodeFile;
11224
11225            // Reflect the rename in scanned details
11226            pkg.codePath = afterCodeFile.getAbsolutePath();
11227            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11228                    pkg.baseCodePath);
11229            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11230                    pkg.splitCodePaths);
11231
11232            // Reflect the rename in app info
11233            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11234            pkg.applicationInfo.setCodePath(pkg.codePath);
11235            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11236            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11237            pkg.applicationInfo.setResourcePath(pkg.codePath);
11238            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11239            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11240
11241            return true;
11242        }
11243
11244        int doPostInstall(int status, int uid) {
11245            if (status != PackageManager.INSTALL_SUCCEEDED) {
11246                cleanUp();
11247            }
11248            return status;
11249        }
11250
11251        @Override
11252        String getCodePath() {
11253            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11254        }
11255
11256        @Override
11257        String getResourcePath() {
11258            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11259        }
11260
11261        private boolean cleanUp() {
11262            if (codeFile == null || !codeFile.exists()) {
11263                return false;
11264            }
11265
11266            if (codeFile.isDirectory()) {
11267                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11268            } else {
11269                codeFile.delete();
11270            }
11271
11272            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11273                resourceFile.delete();
11274            }
11275
11276            return true;
11277        }
11278
11279        void cleanUpResourcesLI() {
11280            // Try enumerating all code paths before deleting
11281            List<String> allCodePaths = Collections.EMPTY_LIST;
11282            if (codeFile != null && codeFile.exists()) {
11283                try {
11284                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11285                    allCodePaths = pkg.getAllCodePaths();
11286                } catch (PackageParserException e) {
11287                    // Ignored; we tried our best
11288                }
11289            }
11290
11291            cleanUp();
11292            removeDexFiles(allCodePaths, instructionSets);
11293        }
11294
11295        boolean doPostDeleteLI(boolean delete) {
11296            // XXX err, shouldn't we respect the delete flag?
11297            cleanUpResourcesLI();
11298            return true;
11299        }
11300    }
11301
11302    private boolean isAsecExternal(String cid) {
11303        final String asecPath = PackageHelper.getSdFilesystem(cid);
11304        return !asecPath.startsWith(mAsecInternalPath);
11305    }
11306
11307    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11308            PackageManagerException {
11309        if (copyRet < 0) {
11310            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11311                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11312                throw new PackageManagerException(copyRet, message);
11313            }
11314        }
11315    }
11316
11317    /**
11318     * Extract the MountService "container ID" from the full code path of an
11319     * .apk.
11320     */
11321    static String cidFromCodePath(String fullCodePath) {
11322        int eidx = fullCodePath.lastIndexOf("/");
11323        String subStr1 = fullCodePath.substring(0, eidx);
11324        int sidx = subStr1.lastIndexOf("/");
11325        return subStr1.substring(sidx+1, eidx);
11326    }
11327
11328    /**
11329     * Logic to handle installation of ASEC applications, including copying and
11330     * renaming logic.
11331     */
11332    class AsecInstallArgs extends InstallArgs {
11333        static final String RES_FILE_NAME = "pkg.apk";
11334        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11335
11336        String cid;
11337        String packagePath;
11338        String resourcePath;
11339
11340        /** New install */
11341        AsecInstallArgs(InstallParams params) {
11342            super(params.origin, params.move, params.observer, params.installFlags,
11343                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11344                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11345                    params.grantedRuntimePermissions);
11346        }
11347
11348        /** Existing install */
11349        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11350                        boolean isExternal, boolean isForwardLocked) {
11351            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11352                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11353                    instructionSets, null, null);
11354            // Hackily pretend we're still looking at a full code path
11355            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11356                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11357            }
11358
11359            // Extract cid from fullCodePath
11360            int eidx = fullCodePath.lastIndexOf("/");
11361            String subStr1 = fullCodePath.substring(0, eidx);
11362            int sidx = subStr1.lastIndexOf("/");
11363            cid = subStr1.substring(sidx+1, eidx);
11364            setMountPath(subStr1);
11365        }
11366
11367        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11368            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11369                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11370                    instructionSets, null, null);
11371            this.cid = cid;
11372            setMountPath(PackageHelper.getSdDir(cid));
11373        }
11374
11375        void createCopyFile() {
11376            cid = mInstallerService.allocateExternalStageCidLegacy();
11377        }
11378
11379        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11380            if (origin.staged) {
11381                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11382                cid = origin.cid;
11383                setMountPath(PackageHelper.getSdDir(cid));
11384                return PackageManager.INSTALL_SUCCEEDED;
11385            }
11386
11387            if (temp) {
11388                createCopyFile();
11389            } else {
11390                /*
11391                 * Pre-emptively destroy the container since it's destroyed if
11392                 * copying fails due to it existing anyway.
11393                 */
11394                PackageHelper.destroySdDir(cid);
11395            }
11396
11397            final String newMountPath = imcs.copyPackageToContainer(
11398                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11399                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11400
11401            if (newMountPath != null) {
11402                setMountPath(newMountPath);
11403                return PackageManager.INSTALL_SUCCEEDED;
11404            } else {
11405                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11406            }
11407        }
11408
11409        @Override
11410        String getCodePath() {
11411            return packagePath;
11412        }
11413
11414        @Override
11415        String getResourcePath() {
11416            return resourcePath;
11417        }
11418
11419        int doPreInstall(int status) {
11420            if (status != PackageManager.INSTALL_SUCCEEDED) {
11421                // Destroy container
11422                PackageHelper.destroySdDir(cid);
11423            } else {
11424                boolean mounted = PackageHelper.isContainerMounted(cid);
11425                if (!mounted) {
11426                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11427                            Process.SYSTEM_UID);
11428                    if (newMountPath != null) {
11429                        setMountPath(newMountPath);
11430                    } else {
11431                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11432                    }
11433                }
11434            }
11435            return status;
11436        }
11437
11438        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11439            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11440            String newMountPath = null;
11441            if (PackageHelper.isContainerMounted(cid)) {
11442                // Unmount the container
11443                if (!PackageHelper.unMountSdDir(cid)) {
11444                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11445                    return false;
11446                }
11447            }
11448            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11449                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11450                        " which might be stale. Will try to clean up.");
11451                // Clean up the stale container and proceed to recreate.
11452                if (!PackageHelper.destroySdDir(newCacheId)) {
11453                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11454                    return false;
11455                }
11456                // Successfully cleaned up stale container. Try to rename again.
11457                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11458                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11459                            + " inspite of cleaning it up.");
11460                    return false;
11461                }
11462            }
11463            if (!PackageHelper.isContainerMounted(newCacheId)) {
11464                Slog.w(TAG, "Mounting container " + newCacheId);
11465                newMountPath = PackageHelper.mountSdDir(newCacheId,
11466                        getEncryptKey(), Process.SYSTEM_UID);
11467            } else {
11468                newMountPath = PackageHelper.getSdDir(newCacheId);
11469            }
11470            if (newMountPath == null) {
11471                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11472                return false;
11473            }
11474            Log.i(TAG, "Succesfully renamed " + cid +
11475                    " to " + newCacheId +
11476                    " at new path: " + newMountPath);
11477            cid = newCacheId;
11478
11479            final File beforeCodeFile = new File(packagePath);
11480            setMountPath(newMountPath);
11481            final File afterCodeFile = new File(packagePath);
11482
11483            // Reflect the rename in scanned details
11484            pkg.codePath = afterCodeFile.getAbsolutePath();
11485            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11486                    pkg.baseCodePath);
11487            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11488                    pkg.splitCodePaths);
11489
11490            // Reflect the rename in app info
11491            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11492            pkg.applicationInfo.setCodePath(pkg.codePath);
11493            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11494            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11495            pkg.applicationInfo.setResourcePath(pkg.codePath);
11496            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11497            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11498
11499            return true;
11500        }
11501
11502        private void setMountPath(String mountPath) {
11503            final File mountFile = new File(mountPath);
11504
11505            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11506            if (monolithicFile.exists()) {
11507                packagePath = monolithicFile.getAbsolutePath();
11508                if (isFwdLocked()) {
11509                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11510                } else {
11511                    resourcePath = packagePath;
11512                }
11513            } else {
11514                packagePath = mountFile.getAbsolutePath();
11515                resourcePath = packagePath;
11516            }
11517        }
11518
11519        int doPostInstall(int status, int uid) {
11520            if (status != PackageManager.INSTALL_SUCCEEDED) {
11521                cleanUp();
11522            } else {
11523                final int groupOwner;
11524                final String protectedFile;
11525                if (isFwdLocked()) {
11526                    groupOwner = UserHandle.getSharedAppGid(uid);
11527                    protectedFile = RES_FILE_NAME;
11528                } else {
11529                    groupOwner = -1;
11530                    protectedFile = null;
11531                }
11532
11533                if (uid < Process.FIRST_APPLICATION_UID
11534                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11535                    Slog.e(TAG, "Failed to finalize " + cid);
11536                    PackageHelper.destroySdDir(cid);
11537                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11538                }
11539
11540                boolean mounted = PackageHelper.isContainerMounted(cid);
11541                if (!mounted) {
11542                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11543                }
11544            }
11545            return status;
11546        }
11547
11548        private void cleanUp() {
11549            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11550
11551            // Destroy secure container
11552            PackageHelper.destroySdDir(cid);
11553        }
11554
11555        private List<String> getAllCodePaths() {
11556            final File codeFile = new File(getCodePath());
11557            if (codeFile != null && codeFile.exists()) {
11558                try {
11559                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11560                    return pkg.getAllCodePaths();
11561                } catch (PackageParserException e) {
11562                    // Ignored; we tried our best
11563                }
11564            }
11565            return Collections.EMPTY_LIST;
11566        }
11567
11568        void cleanUpResourcesLI() {
11569            // Enumerate all code paths before deleting
11570            cleanUpResourcesLI(getAllCodePaths());
11571        }
11572
11573        private void cleanUpResourcesLI(List<String> allCodePaths) {
11574            cleanUp();
11575            removeDexFiles(allCodePaths, instructionSets);
11576        }
11577
11578        String getPackageName() {
11579            return getAsecPackageName(cid);
11580        }
11581
11582        boolean doPostDeleteLI(boolean delete) {
11583            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11584            final List<String> allCodePaths = getAllCodePaths();
11585            boolean mounted = PackageHelper.isContainerMounted(cid);
11586            if (mounted) {
11587                // Unmount first
11588                if (PackageHelper.unMountSdDir(cid)) {
11589                    mounted = false;
11590                }
11591            }
11592            if (!mounted && delete) {
11593                cleanUpResourcesLI(allCodePaths);
11594            }
11595            return !mounted;
11596        }
11597
11598        @Override
11599        int doPreCopy() {
11600            if (isFwdLocked()) {
11601                if (!PackageHelper.fixSdPermissions(cid,
11602                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11603                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11604                }
11605            }
11606
11607            return PackageManager.INSTALL_SUCCEEDED;
11608        }
11609
11610        @Override
11611        int doPostCopy(int uid) {
11612            if (isFwdLocked()) {
11613                if (uid < Process.FIRST_APPLICATION_UID
11614                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11615                                RES_FILE_NAME)) {
11616                    Slog.e(TAG, "Failed to finalize " + cid);
11617                    PackageHelper.destroySdDir(cid);
11618                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11619                }
11620            }
11621
11622            return PackageManager.INSTALL_SUCCEEDED;
11623        }
11624    }
11625
11626    /**
11627     * Logic to handle movement of existing installed applications.
11628     */
11629    class MoveInstallArgs extends InstallArgs {
11630        private File codeFile;
11631        private File resourceFile;
11632
11633        /** New install */
11634        MoveInstallArgs(InstallParams params) {
11635            super(params.origin, params.move, params.observer, params.installFlags,
11636                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11637                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11638                    params.grantedRuntimePermissions);
11639        }
11640
11641        int copyApk(IMediaContainerService imcs, boolean temp) {
11642            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11643                    + move.fromUuid + " to " + move.toUuid);
11644            synchronized (mInstaller) {
11645                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11646                        move.dataAppName, move.appId, move.seinfo) != 0) {
11647                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11648                }
11649            }
11650
11651            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11652            resourceFile = codeFile;
11653            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11654
11655            return PackageManager.INSTALL_SUCCEEDED;
11656        }
11657
11658        int doPreInstall(int status) {
11659            if (status != PackageManager.INSTALL_SUCCEEDED) {
11660                cleanUp(move.toUuid);
11661            }
11662            return status;
11663        }
11664
11665        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11666            if (status != PackageManager.INSTALL_SUCCEEDED) {
11667                cleanUp(move.toUuid);
11668                return false;
11669            }
11670
11671            // Reflect the move in app info
11672            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11673            pkg.applicationInfo.setCodePath(pkg.codePath);
11674            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11675            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11676            pkg.applicationInfo.setResourcePath(pkg.codePath);
11677            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11678            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11679
11680            return true;
11681        }
11682
11683        int doPostInstall(int status, int uid) {
11684            if (status == PackageManager.INSTALL_SUCCEEDED) {
11685                cleanUp(move.fromUuid);
11686            } else {
11687                cleanUp(move.toUuid);
11688            }
11689            return status;
11690        }
11691
11692        @Override
11693        String getCodePath() {
11694            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11695        }
11696
11697        @Override
11698        String getResourcePath() {
11699            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11700        }
11701
11702        private boolean cleanUp(String volumeUuid) {
11703            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11704                    move.dataAppName);
11705            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11706            synchronized (mInstallLock) {
11707                // Clean up both app data and code
11708                removeDataDirsLI(volumeUuid, move.packageName);
11709                if (codeFile.isDirectory()) {
11710                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11711                } else {
11712                    codeFile.delete();
11713                }
11714            }
11715            return true;
11716        }
11717
11718        void cleanUpResourcesLI() {
11719            throw new UnsupportedOperationException();
11720        }
11721
11722        boolean doPostDeleteLI(boolean delete) {
11723            throw new UnsupportedOperationException();
11724        }
11725    }
11726
11727    static String getAsecPackageName(String packageCid) {
11728        int idx = packageCid.lastIndexOf("-");
11729        if (idx == -1) {
11730            return packageCid;
11731        }
11732        return packageCid.substring(0, idx);
11733    }
11734
11735    // Utility method used to create code paths based on package name and available index.
11736    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11737        String idxStr = "";
11738        int idx = 1;
11739        // Fall back to default value of idx=1 if prefix is not
11740        // part of oldCodePath
11741        if (oldCodePath != null) {
11742            String subStr = oldCodePath;
11743            // Drop the suffix right away
11744            if (suffix != null && subStr.endsWith(suffix)) {
11745                subStr = subStr.substring(0, subStr.length() - suffix.length());
11746            }
11747            // If oldCodePath already contains prefix find out the
11748            // ending index to either increment or decrement.
11749            int sidx = subStr.lastIndexOf(prefix);
11750            if (sidx != -1) {
11751                subStr = subStr.substring(sidx + prefix.length());
11752                if (subStr != null) {
11753                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11754                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11755                    }
11756                    try {
11757                        idx = Integer.parseInt(subStr);
11758                        if (idx <= 1) {
11759                            idx++;
11760                        } else {
11761                            idx--;
11762                        }
11763                    } catch(NumberFormatException e) {
11764                    }
11765                }
11766            }
11767        }
11768        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11769        return prefix + idxStr;
11770    }
11771
11772    private File getNextCodePath(File targetDir, String packageName) {
11773        int suffix = 1;
11774        File result;
11775        do {
11776            result = new File(targetDir, packageName + "-" + suffix);
11777            suffix++;
11778        } while (result.exists());
11779        return result;
11780    }
11781
11782    // Utility method that returns the relative package path with respect
11783    // to the installation directory. Like say for /data/data/com.test-1.apk
11784    // string com.test-1 is returned.
11785    static String deriveCodePathName(String codePath) {
11786        if (codePath == null) {
11787            return null;
11788        }
11789        final File codeFile = new File(codePath);
11790        final String name = codeFile.getName();
11791        if (codeFile.isDirectory()) {
11792            return name;
11793        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11794            final int lastDot = name.lastIndexOf('.');
11795            return name.substring(0, lastDot);
11796        } else {
11797            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11798            return null;
11799        }
11800    }
11801
11802    class PackageInstalledInfo {
11803        String name;
11804        int uid;
11805        // The set of users that originally had this package installed.
11806        int[] origUsers;
11807        // The set of users that now have this package installed.
11808        int[] newUsers;
11809        PackageParser.Package pkg;
11810        int returnCode;
11811        String returnMsg;
11812        PackageRemovedInfo removedInfo;
11813
11814        public void setError(int code, String msg) {
11815            returnCode = code;
11816            returnMsg = msg;
11817            Slog.w(TAG, msg);
11818        }
11819
11820        public void setError(String msg, PackageParserException e) {
11821            returnCode = e.error;
11822            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11823            Slog.w(TAG, msg, e);
11824        }
11825
11826        public void setError(String msg, PackageManagerException e) {
11827            returnCode = e.error;
11828            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11829            Slog.w(TAG, msg, e);
11830        }
11831
11832        // In some error cases we want to convey more info back to the observer
11833        String origPackage;
11834        String origPermission;
11835    }
11836
11837    /*
11838     * Install a non-existing package.
11839     */
11840    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11841            UserHandle user, String installerPackageName, String volumeUuid,
11842            PackageInstalledInfo res) {
11843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11844
11845        // Remember this for later, in case we need to rollback this install
11846        String pkgName = pkg.packageName;
11847
11848        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11849        final boolean dataDirExists = Environment
11850                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11851
11852        synchronized(mPackages) {
11853            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11854                // A package with the same name is already installed, though
11855                // it has been renamed to an older name.  The package we
11856                // are trying to install should be installed as an update to
11857                // the existing one, but that has not been requested, so bail.
11858                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11859                        + " without first uninstalling package running as "
11860                        + mSettings.mRenamedPackages.get(pkgName));
11861                return;
11862            }
11863            if (mPackages.containsKey(pkgName)) {
11864                // Don't allow installation over an existing package with the same name.
11865                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11866                        + " without first uninstalling.");
11867                return;
11868            }
11869        }
11870
11871        try {
11872            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11873                    System.currentTimeMillis(), user);
11874
11875            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11876            // delete the partially installed application. the data directory will have to be
11877            // restored if it was already existing
11878            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11879                // remove package from internal structures.  Note that we want deletePackageX to
11880                // delete the package data and cache directories that it created in
11881                // scanPackageLocked, unless those directories existed before we even tried to
11882                // install.
11883                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11884                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11885                                res.removedInfo, true);
11886            }
11887
11888        } catch (PackageManagerException e) {
11889            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11890        }
11891
11892        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11893    }
11894
11895    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11896        // Can't rotate keys during boot or if sharedUser.
11897        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11898                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11899            return false;
11900        }
11901        // app is using upgradeKeySets; make sure all are valid
11902        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11903        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11904        for (int i = 0; i < upgradeKeySets.length; i++) {
11905            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11906                Slog.wtf(TAG, "Package "
11907                         + (oldPs.name != null ? oldPs.name : "<null>")
11908                         + " contains upgrade-key-set reference to unknown key-set: "
11909                         + upgradeKeySets[i]
11910                         + " reverting to signatures check.");
11911                return false;
11912            }
11913        }
11914        return true;
11915    }
11916
11917    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11918        // Upgrade keysets are being used.  Determine if new package has a superset of the
11919        // required keys.
11920        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11921        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11922        for (int i = 0; i < upgradeKeySets.length; i++) {
11923            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11924            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11925                return true;
11926            }
11927        }
11928        return false;
11929    }
11930
11931    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11932            UserHandle user, String installerPackageName, String volumeUuid,
11933            PackageInstalledInfo res) {
11934        final PackageParser.Package oldPackage;
11935        final String pkgName = pkg.packageName;
11936        final int[] allUsers;
11937        final boolean[] perUserInstalled;
11938
11939        // First find the old package info and check signatures
11940        synchronized(mPackages) {
11941            oldPackage = mPackages.get(pkgName);
11942            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11943            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11944            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11945                if(!checkUpgradeKeySetLP(ps, pkg)) {
11946                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11947                            "New package not signed by keys specified by upgrade-keysets: "
11948                            + pkgName);
11949                    return;
11950                }
11951            } else {
11952                // default to original signature matching
11953                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11954                    != PackageManager.SIGNATURE_MATCH) {
11955                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11956                            "New package has a different signature: " + pkgName);
11957                    return;
11958                }
11959            }
11960
11961            // In case of rollback, remember per-user/profile install state
11962            allUsers = sUserManager.getUserIds();
11963            perUserInstalled = new boolean[allUsers.length];
11964            for (int i = 0; i < allUsers.length; i++) {
11965                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11966            }
11967        }
11968
11969        boolean sysPkg = (isSystemApp(oldPackage));
11970        if (sysPkg) {
11971            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11972                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11973        } else {
11974            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11975                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11976        }
11977    }
11978
11979    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11980            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11981            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11982            String volumeUuid, PackageInstalledInfo res) {
11983        String pkgName = deletedPackage.packageName;
11984        boolean deletedPkg = true;
11985        boolean updatedSettings = false;
11986
11987        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11988                + deletedPackage);
11989        long origUpdateTime;
11990        if (pkg.mExtras != null) {
11991            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11992        } else {
11993            origUpdateTime = 0;
11994        }
11995
11996        // First delete the existing package while retaining the data directory
11997        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11998                res.removedInfo, true)) {
11999            // If the existing package wasn't successfully deleted
12000            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12001            deletedPkg = false;
12002        } else {
12003            // Successfully deleted the old package; proceed with replace.
12004
12005            // If deleted package lived in a container, give users a chance to
12006            // relinquish resources before killing.
12007            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12008                if (DEBUG_INSTALL) {
12009                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12010                }
12011                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12012                final ArrayList<String> pkgList = new ArrayList<String>(1);
12013                pkgList.add(deletedPackage.applicationInfo.packageName);
12014                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12015            }
12016
12017            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12018            try {
12019                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12020                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12021                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12022                        perUserInstalled, res, user);
12023                updatedSettings = true;
12024            } catch (PackageManagerException e) {
12025                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12026            }
12027        }
12028
12029        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12030            // remove package from internal structures.  Note that we want deletePackageX to
12031            // delete the package data and cache directories that it created in
12032            // scanPackageLocked, unless those directories existed before we even tried to
12033            // install.
12034            if(updatedSettings) {
12035                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12036                deletePackageLI(
12037                        pkgName, null, true, allUsers, perUserInstalled,
12038                        PackageManager.DELETE_KEEP_DATA,
12039                                res.removedInfo, true);
12040            }
12041            // Since we failed to install the new package we need to restore the old
12042            // package that we deleted.
12043            if (deletedPkg) {
12044                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12045                File restoreFile = new File(deletedPackage.codePath);
12046                // Parse old package
12047                boolean oldExternal = isExternal(deletedPackage);
12048                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12049                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12050                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12051                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12052                try {
12053                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
12054                } catch (PackageManagerException e) {
12055                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12056                            + e.getMessage());
12057                    return;
12058                }
12059                // Restore of old package succeeded. Update permissions.
12060                // writer
12061                synchronized (mPackages) {
12062                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12063                            UPDATE_PERMISSIONS_ALL);
12064                    // can downgrade to reader
12065                    mSettings.writeLPr();
12066                }
12067                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12068            }
12069        }
12070    }
12071
12072    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12073            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12074            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12075            String volumeUuid, PackageInstalledInfo res) {
12076        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12077                + ", old=" + deletedPackage);
12078        boolean disabledSystem = false;
12079        boolean updatedSettings = false;
12080        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12081        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12082                != 0) {
12083            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12084        }
12085        String packageName = deletedPackage.packageName;
12086        if (packageName == null) {
12087            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12088                    "Attempt to delete null packageName.");
12089            return;
12090        }
12091        PackageParser.Package oldPkg;
12092        PackageSetting oldPkgSetting;
12093        // reader
12094        synchronized (mPackages) {
12095            oldPkg = mPackages.get(packageName);
12096            oldPkgSetting = mSettings.mPackages.get(packageName);
12097            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12098                    (oldPkgSetting == null)) {
12099                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12100                        "Couldn't find package:" + packageName + " information");
12101                return;
12102            }
12103        }
12104
12105        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12106
12107        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12108        res.removedInfo.removedPackage = packageName;
12109        // Remove existing system package
12110        removePackageLI(oldPkgSetting, true);
12111        // writer
12112        synchronized (mPackages) {
12113            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12114            if (!disabledSystem && deletedPackage != null) {
12115                // We didn't need to disable the .apk as a current system package,
12116                // which means we are replacing another update that is already
12117                // installed.  We need to make sure to delete the older one's .apk.
12118                res.removedInfo.args = createInstallArgsForExisting(0,
12119                        deletedPackage.applicationInfo.getCodePath(),
12120                        deletedPackage.applicationInfo.getResourcePath(),
12121                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12122            } else {
12123                res.removedInfo.args = null;
12124            }
12125        }
12126
12127        // Successfully disabled the old package. Now proceed with re-installation
12128        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12129
12130        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12131        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12132
12133        PackageParser.Package newPackage = null;
12134        try {
12135            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12136            if (newPackage.mExtras != null) {
12137                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12138                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12139                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12140
12141                // is the update attempting to change shared user? that isn't going to work...
12142                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12143                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12144                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12145                            + " to " + newPkgSetting.sharedUser);
12146                    updatedSettings = true;
12147                }
12148            }
12149
12150            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12151                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12152                        perUserInstalled, res, user);
12153                updatedSettings = true;
12154            }
12155
12156        } catch (PackageManagerException e) {
12157            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12158        }
12159
12160        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12161            // Re installation failed. Restore old information
12162            // Remove new pkg information
12163            if (newPackage != null) {
12164                removeInstalledPackageLI(newPackage, true);
12165            }
12166            // Add back the old system package
12167            try {
12168                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12169            } catch (PackageManagerException e) {
12170                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12171            }
12172            // Restore the old system information in Settings
12173            synchronized (mPackages) {
12174                if (disabledSystem) {
12175                    mSettings.enableSystemPackageLPw(packageName);
12176                }
12177                if (updatedSettings) {
12178                    mSettings.setInstallerPackageName(packageName,
12179                            oldPkgSetting.installerPackageName);
12180                }
12181                mSettings.writeLPr();
12182            }
12183        }
12184    }
12185
12186    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12187            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12188            UserHandle user) {
12189        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12190
12191        String pkgName = newPackage.packageName;
12192        synchronized (mPackages) {
12193            //write settings. the installStatus will be incomplete at this stage.
12194            //note that the new package setting would have already been
12195            //added to mPackages. It hasn't been persisted yet.
12196            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12197            mSettings.writeLPr();
12198        }
12199
12200        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12201        synchronized (mPackages) {
12202            updatePermissionsLPw(newPackage.packageName, newPackage,
12203                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12204                            ? UPDATE_PERMISSIONS_ALL : 0));
12205            // For system-bundled packages, we assume that installing an upgraded version
12206            // of the package implies that the user actually wants to run that new code,
12207            // so we enable the package.
12208            PackageSetting ps = mSettings.mPackages.get(pkgName);
12209            if (ps != null) {
12210                if (isSystemApp(newPackage)) {
12211                    // NB: implicit assumption that system package upgrades apply to all users
12212                    if (DEBUG_INSTALL) {
12213                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12214                    }
12215                    if (res.origUsers != null) {
12216                        for (int userHandle : res.origUsers) {
12217                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12218                                    userHandle, installerPackageName);
12219                        }
12220                    }
12221                    // Also convey the prior install/uninstall state
12222                    if (allUsers != null && perUserInstalled != null) {
12223                        for (int i = 0; i < allUsers.length; i++) {
12224                            if (DEBUG_INSTALL) {
12225                                Slog.d(TAG, "    user " + allUsers[i]
12226                                        + " => " + perUserInstalled[i]);
12227                            }
12228                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12229                        }
12230                        // these install state changes will be persisted in the
12231                        // upcoming call to mSettings.writeLPr().
12232                    }
12233                }
12234                // It's implied that when a user requests installation, they want the app to be
12235                // installed and enabled.
12236                int userId = user.getIdentifier();
12237                if (userId != UserHandle.USER_ALL) {
12238                    ps.setInstalled(true, userId);
12239                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12240                }
12241            }
12242            res.name = pkgName;
12243            res.uid = newPackage.applicationInfo.uid;
12244            res.pkg = newPackage;
12245            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12246            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12247            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12248            //to update install status
12249            mSettings.writeLPr();
12250        }
12251
12252        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12253    }
12254
12255    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12256        try {
12257            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12258            installPackageLI(args, res);
12259        } finally {
12260            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12261        }
12262    }
12263
12264    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12265        final int installFlags = args.installFlags;
12266        final String installerPackageName = args.installerPackageName;
12267        final String volumeUuid = args.volumeUuid;
12268        final File tmpPackageFile = new File(args.getCodePath());
12269        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12270        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12271                || (args.volumeUuid != null));
12272        boolean replace = false;
12273        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12274        if (args.move != null) {
12275            // moving a complete application; perfom an initial scan on the new install location
12276            scanFlags |= SCAN_INITIAL;
12277        }
12278        // Result object to be returned
12279        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12280
12281        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12282
12283        // Retrieve PackageSettings and parse package
12284        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12285                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12286                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12287        PackageParser pp = new PackageParser();
12288        pp.setSeparateProcesses(mSeparateProcesses);
12289        pp.setDisplayMetrics(mMetrics);
12290
12291        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12292        final PackageParser.Package pkg;
12293        try {
12294            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12295        } catch (PackageParserException e) {
12296            res.setError("Failed parse during installPackageLI", e);
12297            return;
12298        } finally {
12299            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12300        }
12301
12302        // Mark that we have an install time CPU ABI override.
12303        pkg.cpuAbiOverride = args.abiOverride;
12304
12305        String pkgName = res.name = pkg.packageName;
12306        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12307            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12308                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12309                return;
12310            }
12311        }
12312
12313        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12314        try {
12315            pp.collectCertificates(pkg, parseFlags);
12316            pp.collectManifestDigest(pkg);
12317        } catch (PackageParserException e) {
12318            res.setError("Failed collect during installPackageLI", e);
12319            return;
12320        } finally {
12321            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12322        }
12323
12324        /* If the installer passed in a manifest digest, compare it now. */
12325        if (args.manifestDigest != null) {
12326            if (DEBUG_INSTALL) {
12327                final String parsedManifest = pkg.manifestDigest == null ? "null"
12328                        : pkg.manifestDigest.toString();
12329                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12330                        + parsedManifest);
12331            }
12332
12333            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12334                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12335                return;
12336            }
12337        } else if (DEBUG_INSTALL) {
12338            final String parsedManifest = pkg.manifestDigest == null
12339                    ? "null" : pkg.manifestDigest.toString();
12340            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12341        }
12342
12343        // Get rid of all references to package scan path via parser.
12344        pp = null;
12345        String oldCodePath = null;
12346        boolean systemApp = false;
12347        synchronized (mPackages) {
12348            // Check if installing already existing package
12349            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12350                String oldName = mSettings.mRenamedPackages.get(pkgName);
12351                if (pkg.mOriginalPackages != null
12352                        && pkg.mOriginalPackages.contains(oldName)
12353                        && mPackages.containsKey(oldName)) {
12354                    // This package is derived from an original package,
12355                    // and this device has been updating from that original
12356                    // name.  We must continue using the original name, so
12357                    // rename the new package here.
12358                    pkg.setPackageName(oldName);
12359                    pkgName = pkg.packageName;
12360                    replace = true;
12361                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12362                            + oldName + " pkgName=" + pkgName);
12363                } else if (mPackages.containsKey(pkgName)) {
12364                    // This package, under its official name, already exists
12365                    // on the device; we should replace it.
12366                    replace = true;
12367                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12368                }
12369
12370                // Prevent apps opting out from runtime permissions
12371                if (replace) {
12372                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12373                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12374                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12375                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12376                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12377                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12378                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12379                                        + " doesn't support runtime permissions but the old"
12380                                        + " target SDK " + oldTargetSdk + " does.");
12381                        return;
12382                    }
12383                }
12384            }
12385
12386            PackageSetting ps = mSettings.mPackages.get(pkgName);
12387            if (ps != null) {
12388                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12389
12390                // Quick sanity check that we're signed correctly if updating;
12391                // we'll check this again later when scanning, but we want to
12392                // bail early here before tripping over redefined permissions.
12393                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12394                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12395                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12396                                + pkg.packageName + " upgrade keys do not match the "
12397                                + "previously installed version");
12398                        return;
12399                    }
12400                } else {
12401                    try {
12402                        verifySignaturesLP(ps, pkg);
12403                    } catch (PackageManagerException e) {
12404                        res.setError(e.error, e.getMessage());
12405                        return;
12406                    }
12407                }
12408
12409                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12410                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12411                    systemApp = (ps.pkg.applicationInfo.flags &
12412                            ApplicationInfo.FLAG_SYSTEM) != 0;
12413                }
12414                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12415            }
12416
12417            // Check whether the newly-scanned package wants to define an already-defined perm
12418            int N = pkg.permissions.size();
12419            for (int i = N-1; i >= 0; i--) {
12420                PackageParser.Permission perm = pkg.permissions.get(i);
12421                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12422                if (bp != null) {
12423                    // If the defining package is signed with our cert, it's okay.  This
12424                    // also includes the "updating the same package" case, of course.
12425                    // "updating same package" could also involve key-rotation.
12426                    final boolean sigsOk;
12427                    if (bp.sourcePackage.equals(pkg.packageName)
12428                            && (bp.packageSetting instanceof PackageSetting)
12429                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12430                                    scanFlags))) {
12431                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12432                    } else {
12433                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12434                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12435                    }
12436                    if (!sigsOk) {
12437                        // If the owning package is the system itself, we log but allow
12438                        // install to proceed; we fail the install on all other permission
12439                        // redefinitions.
12440                        if (!bp.sourcePackage.equals("android")) {
12441                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12442                                    + pkg.packageName + " attempting to redeclare permission "
12443                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12444                            res.origPermission = perm.info.name;
12445                            res.origPackage = bp.sourcePackage;
12446                            return;
12447                        } else {
12448                            Slog.w(TAG, "Package " + pkg.packageName
12449                                    + " attempting to redeclare system permission "
12450                                    + perm.info.name + "; ignoring new declaration");
12451                            pkg.permissions.remove(i);
12452                        }
12453                    }
12454                }
12455            }
12456
12457        }
12458
12459        if (systemApp && onExternal) {
12460            // Disable updates to system apps on sdcard
12461            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12462                    "Cannot install updates to system apps on sdcard");
12463            return;
12464        }
12465
12466        if (args.move != null) {
12467            // We did an in-place move, so dex is ready to roll
12468            scanFlags |= SCAN_NO_DEX;
12469            scanFlags |= SCAN_MOVE;
12470
12471            synchronized (mPackages) {
12472                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12473                if (ps == null) {
12474                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12475                            "Missing settings for moved package " + pkgName);
12476                }
12477
12478                // We moved the entire application as-is, so bring over the
12479                // previously derived ABI information.
12480                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12481                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12482            }
12483
12484        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12485            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12486            scanFlags |= SCAN_NO_DEX;
12487
12488            try {
12489                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12490                        true /* extract libs */);
12491            } catch (PackageManagerException pme) {
12492                Slog.e(TAG, "Error deriving application ABI", pme);
12493                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12494                return;
12495            }
12496
12497            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12498            int result = mPackageDexOptimizer
12499                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12500                            false /* defer */, false /* inclDependencies */);
12501            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12502                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12503                return;
12504            }
12505        }
12506
12507        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12508            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12509            return;
12510        }
12511
12512        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12513
12514        if (replace) {
12515            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12516                    installerPackageName, volumeUuid, res);
12517        } else {
12518            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12519                    args.user, installerPackageName, volumeUuid, res);
12520        }
12521        synchronized (mPackages) {
12522            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12523            if (ps != null) {
12524                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12525            }
12526        }
12527    }
12528
12529    private void startIntentFilterVerifications(int userId, boolean replacing,
12530            PackageParser.Package pkg) {
12531        if (mIntentFilterVerifierComponent == null) {
12532            Slog.w(TAG, "No IntentFilter verification will not be done as "
12533                    + "there is no IntentFilterVerifier available!");
12534            return;
12535        }
12536
12537        final int verifierUid = getPackageUid(
12538                mIntentFilterVerifierComponent.getPackageName(),
12539                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12540
12541        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12542        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12543        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12544        mHandler.sendMessage(msg);
12545    }
12546
12547    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12548            PackageParser.Package pkg) {
12549        int size = pkg.activities.size();
12550        if (size == 0) {
12551            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12552                    "No activity, so no need to verify any IntentFilter!");
12553            return;
12554        }
12555
12556        final boolean hasDomainURLs = hasDomainURLs(pkg);
12557        if (!hasDomainURLs) {
12558            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12559                    "No domain URLs, so no need to verify any IntentFilter!");
12560            return;
12561        }
12562
12563        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12564                + " if any IntentFilter from the " + size
12565                + " Activities needs verification ...");
12566
12567        int count = 0;
12568        final String packageName = pkg.packageName;
12569
12570        synchronized (mPackages) {
12571            // If this is a new install and we see that we've already run verification for this
12572            // package, we have nothing to do: it means the state was restored from backup.
12573            if (!replacing) {
12574                IntentFilterVerificationInfo ivi =
12575                        mSettings.getIntentFilterVerificationLPr(packageName);
12576                if (ivi != null) {
12577                    if (DEBUG_DOMAIN_VERIFICATION) {
12578                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12579                                + ivi.getStatusString());
12580                    }
12581                    return;
12582                }
12583            }
12584
12585            // If any filters need to be verified, then all need to be.
12586            boolean needToVerify = false;
12587            for (PackageParser.Activity a : pkg.activities) {
12588                for (ActivityIntentInfo filter : a.intents) {
12589                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12590                        if (DEBUG_DOMAIN_VERIFICATION) {
12591                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12592                        }
12593                        needToVerify = true;
12594                        break;
12595                    }
12596                }
12597            }
12598
12599            if (needToVerify) {
12600                final int verificationId = mIntentFilterVerificationToken++;
12601                for (PackageParser.Activity a : pkg.activities) {
12602                    for (ActivityIntentInfo filter : a.intents) {
12603                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12604                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12605                                    "Verification needed for IntentFilter:" + filter.toString());
12606                            mIntentFilterVerifier.addOneIntentFilterVerification(
12607                                    verifierUid, userId, verificationId, filter, packageName);
12608                            count++;
12609                        }
12610                    }
12611                }
12612            }
12613        }
12614
12615        if (count > 0) {
12616            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12617                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12618                    +  " for userId:" + userId);
12619            mIntentFilterVerifier.startVerifications(userId);
12620        } else {
12621            if (DEBUG_DOMAIN_VERIFICATION) {
12622                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12623            }
12624        }
12625    }
12626
12627    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12628        final ComponentName cn  = filter.activity.getComponentName();
12629        final String packageName = cn.getPackageName();
12630
12631        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12632                packageName);
12633        if (ivi == null) {
12634            return true;
12635        }
12636        int status = ivi.getStatus();
12637        switch (status) {
12638            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12639            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12640                return true;
12641
12642            default:
12643                // Nothing to do
12644                return false;
12645        }
12646    }
12647
12648    private static boolean isMultiArch(PackageSetting ps) {
12649        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12650    }
12651
12652    private static boolean isMultiArch(ApplicationInfo info) {
12653        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12654    }
12655
12656    private static boolean isExternal(PackageParser.Package pkg) {
12657        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12658    }
12659
12660    private static boolean isExternal(PackageSetting ps) {
12661        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12662    }
12663
12664    private static boolean isExternal(ApplicationInfo info) {
12665        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12666    }
12667
12668    private static boolean isSystemApp(PackageParser.Package pkg) {
12669        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12670    }
12671
12672    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12673        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12674    }
12675
12676    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12677        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12678    }
12679
12680    private static boolean isSystemApp(PackageSetting ps) {
12681        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12682    }
12683
12684    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12685        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12686    }
12687
12688    private int packageFlagsToInstallFlags(PackageSetting ps) {
12689        int installFlags = 0;
12690        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12691            // This existing package was an external ASEC install when we have
12692            // the external flag without a UUID
12693            installFlags |= PackageManager.INSTALL_EXTERNAL;
12694        }
12695        if (ps.isForwardLocked()) {
12696            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12697        }
12698        return installFlags;
12699    }
12700
12701    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12702        if (isExternal(pkg)) {
12703            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12704                return mSettings.getExternalVersion();
12705            } else {
12706                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12707            }
12708        } else {
12709            return mSettings.getInternalVersion();
12710        }
12711    }
12712
12713    private void deleteTempPackageFiles() {
12714        final FilenameFilter filter = new FilenameFilter() {
12715            public boolean accept(File dir, String name) {
12716                return name.startsWith("vmdl") && name.endsWith(".tmp");
12717            }
12718        };
12719        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12720            file.delete();
12721        }
12722    }
12723
12724    @Override
12725    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12726            int flags) {
12727        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12728                flags);
12729    }
12730
12731    @Override
12732    public void deletePackage(final String packageName,
12733            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12734        mContext.enforceCallingOrSelfPermission(
12735                android.Manifest.permission.DELETE_PACKAGES, null);
12736        Preconditions.checkNotNull(packageName);
12737        Preconditions.checkNotNull(observer);
12738        final int uid = Binder.getCallingUid();
12739        if (UserHandle.getUserId(uid) != userId) {
12740            mContext.enforceCallingPermission(
12741                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12742                    "deletePackage for user " + userId);
12743        }
12744        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12745            try {
12746                observer.onPackageDeleted(packageName,
12747                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12748            } catch (RemoteException re) {
12749            }
12750            return;
12751        }
12752
12753        boolean uninstallBlocked = false;
12754        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12755            int[] users = sUserManager.getUserIds();
12756            for (int i = 0; i < users.length; ++i) {
12757                if (getBlockUninstallForUser(packageName, users[i])) {
12758                    uninstallBlocked = true;
12759                    break;
12760                }
12761            }
12762        } else {
12763            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12764        }
12765        if (uninstallBlocked) {
12766            try {
12767                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12768                        null);
12769            } catch (RemoteException re) {
12770            }
12771            return;
12772        }
12773
12774        if (DEBUG_REMOVE) {
12775            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12776        }
12777        // Queue up an async operation since the package deletion may take a little while.
12778        mHandler.post(new Runnable() {
12779            public void run() {
12780                mHandler.removeCallbacks(this);
12781                final int returnCode = deletePackageX(packageName, userId, flags);
12782                if (observer != null) {
12783                    try {
12784                        observer.onPackageDeleted(packageName, returnCode, null);
12785                    } catch (RemoteException e) {
12786                        Log.i(TAG, "Observer no longer exists.");
12787                    } //end catch
12788                } //end if
12789            } //end run
12790        });
12791    }
12792
12793    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12794        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12795                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12796        try {
12797            if (dpm != null) {
12798                if (dpm.isDeviceOwner(packageName)) {
12799                    return true;
12800                }
12801                int[] users;
12802                if (userId == UserHandle.USER_ALL) {
12803                    users = sUserManager.getUserIds();
12804                } else {
12805                    users = new int[]{userId};
12806                }
12807                for (int i = 0; i < users.length; ++i) {
12808                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12809                        return true;
12810                    }
12811                }
12812            }
12813        } catch (RemoteException e) {
12814        }
12815        return false;
12816    }
12817
12818    /**
12819     *  This method is an internal method that could be get invoked either
12820     *  to delete an installed package or to clean up a failed installation.
12821     *  After deleting an installed package, a broadcast is sent to notify any
12822     *  listeners that the package has been installed. For cleaning up a failed
12823     *  installation, the broadcast is not necessary since the package's
12824     *  installation wouldn't have sent the initial broadcast either
12825     *  The key steps in deleting a package are
12826     *  deleting the package information in internal structures like mPackages,
12827     *  deleting the packages base directories through installd
12828     *  updating mSettings to reflect current status
12829     *  persisting settings for later use
12830     *  sending a broadcast if necessary
12831     */
12832    private int deletePackageX(String packageName, int userId, int flags) {
12833        final PackageRemovedInfo info = new PackageRemovedInfo();
12834        final boolean res;
12835
12836        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12837                ? UserHandle.ALL : new UserHandle(userId);
12838
12839        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12840            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12841            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12842        }
12843
12844        boolean removedForAllUsers = false;
12845        boolean systemUpdate = false;
12846
12847        // for the uninstall-updates case and restricted profiles, remember the per-
12848        // userhandle installed state
12849        int[] allUsers;
12850        boolean[] perUserInstalled;
12851        synchronized (mPackages) {
12852            PackageSetting ps = mSettings.mPackages.get(packageName);
12853            allUsers = sUserManager.getUserIds();
12854            perUserInstalled = new boolean[allUsers.length];
12855            for (int i = 0; i < allUsers.length; i++) {
12856                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12857            }
12858        }
12859
12860        synchronized (mInstallLock) {
12861            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12862            res = deletePackageLI(packageName, removeForUser,
12863                    true, allUsers, perUserInstalled,
12864                    flags | REMOVE_CHATTY, info, true);
12865            systemUpdate = info.isRemovedPackageSystemUpdate;
12866            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12867                removedForAllUsers = true;
12868            }
12869            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12870                    + " removedForAllUsers=" + removedForAllUsers);
12871        }
12872
12873        if (res) {
12874            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12875
12876            // If the removed package was a system update, the old system package
12877            // was re-enabled; we need to broadcast this information
12878            if (systemUpdate) {
12879                Bundle extras = new Bundle(1);
12880                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12881                        ? info.removedAppId : info.uid);
12882                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12883
12884                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12885                        extras, null, null, null);
12886                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12887                        extras, null, null, null);
12888                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12889                        null, packageName, null, null);
12890            }
12891        }
12892        // Force a gc here.
12893        Runtime.getRuntime().gc();
12894        // Delete the resources here after sending the broadcast to let
12895        // other processes clean up before deleting resources.
12896        if (info.args != null) {
12897            synchronized (mInstallLock) {
12898                info.args.doPostDeleteLI(true);
12899            }
12900        }
12901
12902        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12903    }
12904
12905    class PackageRemovedInfo {
12906        String removedPackage;
12907        int uid = -1;
12908        int removedAppId = -1;
12909        int[] removedUsers = null;
12910        boolean isRemovedPackageSystemUpdate = false;
12911        // Clean up resources deleted packages.
12912        InstallArgs args = null;
12913
12914        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12915            Bundle extras = new Bundle(1);
12916            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12917            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12918            if (replacing) {
12919                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12920            }
12921            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12922            if (removedPackage != null) {
12923                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12924                        extras, null, null, removedUsers);
12925                if (fullRemove && !replacing) {
12926                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12927                            extras, null, null, removedUsers);
12928                }
12929            }
12930            if (removedAppId >= 0) {
12931                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12932                        removedUsers);
12933            }
12934        }
12935    }
12936
12937    /*
12938     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12939     * flag is not set, the data directory is removed as well.
12940     * make sure this flag is set for partially installed apps. If not its meaningless to
12941     * delete a partially installed application.
12942     */
12943    private void removePackageDataLI(PackageSetting ps,
12944            int[] allUserHandles, boolean[] perUserInstalled,
12945            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12946        String packageName = ps.name;
12947        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12948        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12949        // Retrieve object to delete permissions for shared user later on
12950        final PackageSetting deletedPs;
12951        // reader
12952        synchronized (mPackages) {
12953            deletedPs = mSettings.mPackages.get(packageName);
12954            if (outInfo != null) {
12955                outInfo.removedPackage = packageName;
12956                outInfo.removedUsers = deletedPs != null
12957                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12958                        : null;
12959            }
12960        }
12961        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12962            removeDataDirsLI(ps.volumeUuid, packageName);
12963            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12964        }
12965        // writer
12966        synchronized (mPackages) {
12967            if (deletedPs != null) {
12968                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12969                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12970                    clearDefaultBrowserIfNeeded(packageName);
12971                    if (outInfo != null) {
12972                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12973                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12974                    }
12975                    updatePermissionsLPw(deletedPs.name, null, 0);
12976                    if (deletedPs.sharedUser != null) {
12977                        // Remove permissions associated with package. Since runtime
12978                        // permissions are per user we have to kill the removed package
12979                        // or packages running under the shared user of the removed
12980                        // package if revoking the permissions requested only by the removed
12981                        // package is successful and this causes a change in gids.
12982                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12983                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12984                                    userId);
12985                            if (userIdToKill == UserHandle.USER_ALL
12986                                    || userIdToKill >= UserHandle.USER_OWNER) {
12987                                // If gids changed for this user, kill all affected packages.
12988                                mHandler.post(new Runnable() {
12989                                    @Override
12990                                    public void run() {
12991                                        // This has to happen with no lock held.
12992                                        killApplication(deletedPs.name, deletedPs.appId,
12993                                                KILL_APP_REASON_GIDS_CHANGED);
12994                                    }
12995                                });
12996                                break;
12997                            }
12998                        }
12999                    }
13000                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13001                }
13002                // make sure to preserve per-user disabled state if this removal was just
13003                // a downgrade of a system app to the factory package
13004                if (allUserHandles != null && perUserInstalled != null) {
13005                    if (DEBUG_REMOVE) {
13006                        Slog.d(TAG, "Propagating install state across downgrade");
13007                    }
13008                    for (int i = 0; i < allUserHandles.length; i++) {
13009                        if (DEBUG_REMOVE) {
13010                            Slog.d(TAG, "    user " + allUserHandles[i]
13011                                    + " => " + perUserInstalled[i]);
13012                        }
13013                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13014                    }
13015                }
13016            }
13017            // can downgrade to reader
13018            if (writeSettings) {
13019                // Save settings now
13020                mSettings.writeLPr();
13021            }
13022        }
13023        if (outInfo != null) {
13024            // A user ID was deleted here. Go through all users and remove it
13025            // from KeyStore.
13026            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13027        }
13028    }
13029
13030    static boolean locationIsPrivileged(File path) {
13031        try {
13032            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13033                    .getCanonicalPath();
13034            return path.getCanonicalPath().startsWith(privilegedAppDir);
13035        } catch (IOException e) {
13036            Slog.e(TAG, "Unable to access code path " + path);
13037        }
13038        return false;
13039    }
13040
13041    /*
13042     * Tries to delete system package.
13043     */
13044    private boolean deleteSystemPackageLI(PackageSetting newPs,
13045            int[] allUserHandles, boolean[] perUserInstalled,
13046            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13047        final boolean applyUserRestrictions
13048                = (allUserHandles != null) && (perUserInstalled != null);
13049        PackageSetting disabledPs = null;
13050        // Confirm if the system package has been updated
13051        // An updated system app can be deleted. This will also have to restore
13052        // the system pkg from system partition
13053        // reader
13054        synchronized (mPackages) {
13055            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13056        }
13057        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13058                + " disabledPs=" + disabledPs);
13059        if (disabledPs == null) {
13060            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13061            return false;
13062        } else if (DEBUG_REMOVE) {
13063            Slog.d(TAG, "Deleting system pkg from data partition");
13064        }
13065        if (DEBUG_REMOVE) {
13066            if (applyUserRestrictions) {
13067                Slog.d(TAG, "Remembering install states:");
13068                for (int i = 0; i < allUserHandles.length; i++) {
13069                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13070                }
13071            }
13072        }
13073        // Delete the updated package
13074        outInfo.isRemovedPackageSystemUpdate = true;
13075        if (disabledPs.versionCode < newPs.versionCode) {
13076            // Delete data for downgrades
13077            flags &= ~PackageManager.DELETE_KEEP_DATA;
13078        } else {
13079            // Preserve data by setting flag
13080            flags |= PackageManager.DELETE_KEEP_DATA;
13081        }
13082        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13083                allUserHandles, perUserInstalled, outInfo, writeSettings);
13084        if (!ret) {
13085            return false;
13086        }
13087        // writer
13088        synchronized (mPackages) {
13089            // Reinstate the old system package
13090            mSettings.enableSystemPackageLPw(newPs.name);
13091            // Remove any native libraries from the upgraded package.
13092            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13093        }
13094        // Install the system package
13095        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13096        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13097        if (locationIsPrivileged(disabledPs.codePath)) {
13098            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13099        }
13100
13101        final PackageParser.Package newPkg;
13102        try {
13103            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13104        } catch (PackageManagerException e) {
13105            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13106            return false;
13107        }
13108
13109        // writer
13110        synchronized (mPackages) {
13111            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13112
13113            // Propagate the permissions state as we do not want to drop on the floor
13114            // runtime permissions. The update permissions method below will take
13115            // care of removing obsolete permissions and grant install permissions.
13116            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13117            updatePermissionsLPw(newPkg.packageName, newPkg,
13118                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13119
13120            if (applyUserRestrictions) {
13121                if (DEBUG_REMOVE) {
13122                    Slog.d(TAG, "Propagating install state across reinstall");
13123                }
13124                for (int i = 0; i < allUserHandles.length; i++) {
13125                    if (DEBUG_REMOVE) {
13126                        Slog.d(TAG, "    user " + allUserHandles[i]
13127                                + " => " + perUserInstalled[i]);
13128                    }
13129                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13130
13131                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13132                }
13133                // Regardless of writeSettings we need to ensure that this restriction
13134                // state propagation is persisted
13135                mSettings.writeAllUsersPackageRestrictionsLPr();
13136            }
13137            // can downgrade to reader here
13138            if (writeSettings) {
13139                mSettings.writeLPr();
13140            }
13141        }
13142        return true;
13143    }
13144
13145    private boolean deleteInstalledPackageLI(PackageSetting ps,
13146            boolean deleteCodeAndResources, int flags,
13147            int[] allUserHandles, boolean[] perUserInstalled,
13148            PackageRemovedInfo outInfo, boolean writeSettings) {
13149        if (outInfo != null) {
13150            outInfo.uid = ps.appId;
13151        }
13152
13153        // Delete package data from internal structures and also remove data if flag is set
13154        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13155
13156        // Delete application code and resources
13157        if (deleteCodeAndResources && (outInfo != null)) {
13158            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13159                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13160            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13161        }
13162        return true;
13163    }
13164
13165    @Override
13166    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13167            int userId) {
13168        mContext.enforceCallingOrSelfPermission(
13169                android.Manifest.permission.DELETE_PACKAGES, null);
13170        synchronized (mPackages) {
13171            PackageSetting ps = mSettings.mPackages.get(packageName);
13172            if (ps == null) {
13173                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13174                return false;
13175            }
13176            if (!ps.getInstalled(userId)) {
13177                // Can't block uninstall for an app that is not installed or enabled.
13178                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13179                return false;
13180            }
13181            ps.setBlockUninstall(blockUninstall, userId);
13182            mSettings.writePackageRestrictionsLPr(userId);
13183        }
13184        return true;
13185    }
13186
13187    @Override
13188    public boolean getBlockUninstallForUser(String packageName, int userId) {
13189        synchronized (mPackages) {
13190            PackageSetting ps = mSettings.mPackages.get(packageName);
13191            if (ps == null) {
13192                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13193                return false;
13194            }
13195            return ps.getBlockUninstall(userId);
13196        }
13197    }
13198
13199    /*
13200     * This method handles package deletion in general
13201     */
13202    private boolean deletePackageLI(String packageName, UserHandle user,
13203            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13204            int flags, PackageRemovedInfo outInfo,
13205            boolean writeSettings) {
13206        if (packageName == null) {
13207            Slog.w(TAG, "Attempt to delete null packageName.");
13208            return false;
13209        }
13210        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13211        PackageSetting ps;
13212        boolean dataOnly = false;
13213        int removeUser = -1;
13214        int appId = -1;
13215        synchronized (mPackages) {
13216            ps = mSettings.mPackages.get(packageName);
13217            if (ps == null) {
13218                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13219                return false;
13220            }
13221            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13222                    && user.getIdentifier() != UserHandle.USER_ALL) {
13223                // The caller is asking that the package only be deleted for a single
13224                // user.  To do this, we just mark its uninstalled state and delete
13225                // its data.  If this is a system app, we only allow this to happen if
13226                // they have set the special DELETE_SYSTEM_APP which requests different
13227                // semantics than normal for uninstalling system apps.
13228                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13229                final int userId = user.getIdentifier();
13230                ps.setUserState(userId,
13231                        COMPONENT_ENABLED_STATE_DEFAULT,
13232                        false, //installed
13233                        true,  //stopped
13234                        true,  //notLaunched
13235                        false, //hidden
13236                        null, null, null,
13237                        false, // blockUninstall
13238                        ps.readUserState(userId).domainVerificationStatus, 0);
13239                if (!isSystemApp(ps)) {
13240                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13241                        // Other user still have this package installed, so all
13242                        // we need to do is clear this user's data and save that
13243                        // it is uninstalled.
13244                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13245                        removeUser = user.getIdentifier();
13246                        appId = ps.appId;
13247                        scheduleWritePackageRestrictionsLocked(removeUser);
13248                    } else {
13249                        // We need to set it back to 'installed' so the uninstall
13250                        // broadcasts will be sent correctly.
13251                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13252                        ps.setInstalled(true, user.getIdentifier());
13253                    }
13254                } else {
13255                    // This is a system app, so we assume that the
13256                    // other users still have this package installed, so all
13257                    // we need to do is clear this user's data and save that
13258                    // it is uninstalled.
13259                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13260                    removeUser = user.getIdentifier();
13261                    appId = ps.appId;
13262                    scheduleWritePackageRestrictionsLocked(removeUser);
13263                }
13264            }
13265        }
13266
13267        if (removeUser >= 0) {
13268            // From above, we determined that we are deleting this only
13269            // for a single user.  Continue the work here.
13270            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13271            if (outInfo != null) {
13272                outInfo.removedPackage = packageName;
13273                outInfo.removedAppId = appId;
13274                outInfo.removedUsers = new int[] {removeUser};
13275            }
13276            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13277            removeKeystoreDataIfNeeded(removeUser, appId);
13278            schedulePackageCleaning(packageName, removeUser, false);
13279            synchronized (mPackages) {
13280                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13281                    scheduleWritePackageRestrictionsLocked(removeUser);
13282                }
13283                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13284            }
13285            return true;
13286        }
13287
13288        if (dataOnly) {
13289            // Delete application data first
13290            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13291            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13292            return true;
13293        }
13294
13295        boolean ret = false;
13296        if (isSystemApp(ps)) {
13297            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13298            // When an updated system application is deleted we delete the existing resources as well and
13299            // fall back to existing code in system partition
13300            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13301                    flags, outInfo, writeSettings);
13302        } else {
13303            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13304            // Kill application pre-emptively especially for apps on sd.
13305            killApplication(packageName, ps.appId, "uninstall pkg");
13306            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13307                    allUserHandles, perUserInstalled,
13308                    outInfo, writeSettings);
13309        }
13310
13311        return ret;
13312    }
13313
13314    private final class ClearStorageConnection implements ServiceConnection {
13315        IMediaContainerService mContainerService;
13316
13317        @Override
13318        public void onServiceConnected(ComponentName name, IBinder service) {
13319            synchronized (this) {
13320                mContainerService = IMediaContainerService.Stub.asInterface(service);
13321                notifyAll();
13322            }
13323        }
13324
13325        @Override
13326        public void onServiceDisconnected(ComponentName name) {
13327        }
13328    }
13329
13330    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13331        final boolean mounted;
13332        if (Environment.isExternalStorageEmulated()) {
13333            mounted = true;
13334        } else {
13335            final String status = Environment.getExternalStorageState();
13336
13337            mounted = status.equals(Environment.MEDIA_MOUNTED)
13338                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13339        }
13340
13341        if (!mounted) {
13342            return;
13343        }
13344
13345        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13346        int[] users;
13347        if (userId == UserHandle.USER_ALL) {
13348            users = sUserManager.getUserIds();
13349        } else {
13350            users = new int[] { userId };
13351        }
13352        final ClearStorageConnection conn = new ClearStorageConnection();
13353        if (mContext.bindServiceAsUser(
13354                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13355            try {
13356                for (int curUser : users) {
13357                    long timeout = SystemClock.uptimeMillis() + 5000;
13358                    synchronized (conn) {
13359                        long now = SystemClock.uptimeMillis();
13360                        while (conn.mContainerService == null && now < timeout) {
13361                            try {
13362                                conn.wait(timeout - now);
13363                            } catch (InterruptedException e) {
13364                            }
13365                        }
13366                    }
13367                    if (conn.mContainerService == null) {
13368                        return;
13369                    }
13370
13371                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13372                    clearDirectory(conn.mContainerService,
13373                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13374                    if (allData) {
13375                        clearDirectory(conn.mContainerService,
13376                                userEnv.buildExternalStorageAppDataDirs(packageName));
13377                        clearDirectory(conn.mContainerService,
13378                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13379                    }
13380                }
13381            } finally {
13382                mContext.unbindService(conn);
13383            }
13384        }
13385    }
13386
13387    @Override
13388    public void clearApplicationUserData(final String packageName,
13389            final IPackageDataObserver observer, final int userId) {
13390        mContext.enforceCallingOrSelfPermission(
13391                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13392        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13393        // Queue up an async operation since the package deletion may take a little while.
13394        mHandler.post(new Runnable() {
13395            public void run() {
13396                mHandler.removeCallbacks(this);
13397                final boolean succeeded;
13398                synchronized (mInstallLock) {
13399                    succeeded = clearApplicationUserDataLI(packageName, userId);
13400                }
13401                clearExternalStorageDataSync(packageName, userId, true);
13402                if (succeeded) {
13403                    // invoke DeviceStorageMonitor's update method to clear any notifications
13404                    DeviceStorageMonitorInternal
13405                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13406                    if (dsm != null) {
13407                        dsm.checkMemory();
13408                    }
13409                }
13410                if(observer != null) {
13411                    try {
13412                        observer.onRemoveCompleted(packageName, succeeded);
13413                    } catch (RemoteException e) {
13414                        Log.i(TAG, "Observer no longer exists.");
13415                    }
13416                } //end if observer
13417            } //end run
13418        });
13419    }
13420
13421    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13422        if (packageName == null) {
13423            Slog.w(TAG, "Attempt to delete null packageName.");
13424            return false;
13425        }
13426
13427        // Try finding details about the requested package
13428        PackageParser.Package pkg;
13429        synchronized (mPackages) {
13430            pkg = mPackages.get(packageName);
13431            if (pkg == null) {
13432                final PackageSetting ps = mSettings.mPackages.get(packageName);
13433                if (ps != null) {
13434                    pkg = ps.pkg;
13435                }
13436            }
13437
13438            if (pkg == null) {
13439                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13440                return false;
13441            }
13442
13443            PackageSetting ps = (PackageSetting) pkg.mExtras;
13444            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13445        }
13446
13447        // Always delete data directories for package, even if we found no other
13448        // record of app. This helps users recover from UID mismatches without
13449        // resorting to a full data wipe.
13450        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13451        if (retCode < 0) {
13452            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13453            return false;
13454        }
13455
13456        final int appId = pkg.applicationInfo.uid;
13457        removeKeystoreDataIfNeeded(userId, appId);
13458
13459        // Create a native library symlink only if we have native libraries
13460        // and if the native libraries are 32 bit libraries. We do not provide
13461        // this symlink for 64 bit libraries.
13462        if (pkg.applicationInfo.primaryCpuAbi != null &&
13463                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13464            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13465            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13466                    nativeLibPath, userId) < 0) {
13467                Slog.w(TAG, "Failed linking native library dir");
13468                return false;
13469            }
13470        }
13471
13472        return true;
13473    }
13474
13475    /**
13476     * Reverts user permission state changes (permissions and flags) in
13477     * all packages for a given user.
13478     *
13479     * @param userId The device user for which to do a reset.
13480     */
13481    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13482        final int packageCount = mPackages.size();
13483        for (int i = 0; i < packageCount; i++) {
13484            PackageParser.Package pkg = mPackages.valueAt(i);
13485            PackageSetting ps = (PackageSetting) pkg.mExtras;
13486            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13487        }
13488    }
13489
13490    /**
13491     * Reverts user permission state changes (permissions and flags).
13492     *
13493     * @param ps The package for which to reset.
13494     * @param userId The device user for which to do a reset.
13495     */
13496    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13497            final PackageSetting ps, final int userId) {
13498        if (ps.pkg == null) {
13499            return;
13500        }
13501
13502        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13503                | FLAG_PERMISSION_USER_FIXED
13504                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13505
13506        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13507                | FLAG_PERMISSION_POLICY_FIXED;
13508
13509        boolean writeInstallPermissions = false;
13510        boolean writeRuntimePermissions = false;
13511
13512        final int permissionCount = ps.pkg.requestedPermissions.size();
13513        for (int i = 0; i < permissionCount; i++) {
13514            String permission = ps.pkg.requestedPermissions.get(i);
13515
13516            BasePermission bp = mSettings.mPermissions.get(permission);
13517            if (bp == null) {
13518                continue;
13519            }
13520
13521            // If shared user we just reset the state to which only this app contributed.
13522            if (ps.sharedUser != null) {
13523                boolean used = false;
13524                final int packageCount = ps.sharedUser.packages.size();
13525                for (int j = 0; j < packageCount; j++) {
13526                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13527                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13528                            && pkg.pkg.requestedPermissions.contains(permission)) {
13529                        used = true;
13530                        break;
13531                    }
13532                }
13533                if (used) {
13534                    continue;
13535                }
13536            }
13537
13538            PermissionsState permissionsState = ps.getPermissionsState();
13539
13540            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13541
13542            // Always clear the user settable flags.
13543            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13544                    bp.name) != null;
13545            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13546                if (hasInstallState) {
13547                    writeInstallPermissions = true;
13548                } else {
13549                    writeRuntimePermissions = true;
13550                }
13551            }
13552
13553            // Below is only runtime permission handling.
13554            if (!bp.isRuntime()) {
13555                continue;
13556            }
13557
13558            // Never clobber system or policy.
13559            if ((oldFlags & policyOrSystemFlags) != 0) {
13560                continue;
13561            }
13562
13563            // If this permission was granted by default, make sure it is.
13564            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13565                if (permissionsState.grantRuntimePermission(bp, userId)
13566                        != PERMISSION_OPERATION_FAILURE) {
13567                    writeRuntimePermissions = true;
13568                }
13569            } else {
13570                // Otherwise, reset the permission.
13571                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13572                switch (revokeResult) {
13573                    case PERMISSION_OPERATION_SUCCESS: {
13574                        writeRuntimePermissions = true;
13575                    } break;
13576
13577                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13578                        writeRuntimePermissions = true;
13579                        final int appId = ps.appId;
13580                        mHandler.post(new Runnable() {
13581                            @Override
13582                            public void run() {
13583                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13584                            }
13585                        });
13586                    } break;
13587                }
13588            }
13589        }
13590
13591        // Synchronously write as we are taking permissions away.
13592        if (writeRuntimePermissions) {
13593            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13594        }
13595
13596        // Synchronously write as we are taking permissions away.
13597        if (writeInstallPermissions) {
13598            mSettings.writeLPr();
13599        }
13600    }
13601
13602    /**
13603     * Remove entries from the keystore daemon. Will only remove it if the
13604     * {@code appId} is valid.
13605     */
13606    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13607        if (appId < 0) {
13608            return;
13609        }
13610
13611        final KeyStore keyStore = KeyStore.getInstance();
13612        if (keyStore != null) {
13613            if (userId == UserHandle.USER_ALL) {
13614                for (final int individual : sUserManager.getUserIds()) {
13615                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13616                }
13617            } else {
13618                keyStore.clearUid(UserHandle.getUid(userId, appId));
13619            }
13620        } else {
13621            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13622        }
13623    }
13624
13625    @Override
13626    public void deleteApplicationCacheFiles(final String packageName,
13627            final IPackageDataObserver observer) {
13628        mContext.enforceCallingOrSelfPermission(
13629                android.Manifest.permission.DELETE_CACHE_FILES, null);
13630        // Queue up an async operation since the package deletion may take a little while.
13631        final int userId = UserHandle.getCallingUserId();
13632        mHandler.post(new Runnable() {
13633            public void run() {
13634                mHandler.removeCallbacks(this);
13635                final boolean succeded;
13636                synchronized (mInstallLock) {
13637                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13638                }
13639                clearExternalStorageDataSync(packageName, userId, false);
13640                if (observer != null) {
13641                    try {
13642                        observer.onRemoveCompleted(packageName, succeded);
13643                    } catch (RemoteException e) {
13644                        Log.i(TAG, "Observer no longer exists.");
13645                    }
13646                } //end if observer
13647            } //end run
13648        });
13649    }
13650
13651    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13652        if (packageName == null) {
13653            Slog.w(TAG, "Attempt to delete null packageName.");
13654            return false;
13655        }
13656        PackageParser.Package p;
13657        synchronized (mPackages) {
13658            p = mPackages.get(packageName);
13659        }
13660        if (p == null) {
13661            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13662            return false;
13663        }
13664        final ApplicationInfo applicationInfo = p.applicationInfo;
13665        if (applicationInfo == null) {
13666            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13667            return false;
13668        }
13669        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13670        if (retCode < 0) {
13671            Slog.w(TAG, "Couldn't remove cache files for package: "
13672                       + packageName + " u" + userId);
13673            return false;
13674        }
13675        return true;
13676    }
13677
13678    @Override
13679    public void getPackageSizeInfo(final String packageName, int userHandle,
13680            final IPackageStatsObserver observer) {
13681        mContext.enforceCallingOrSelfPermission(
13682                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13683        if (packageName == null) {
13684            throw new IllegalArgumentException("Attempt to get size of null packageName");
13685        }
13686
13687        PackageStats stats = new PackageStats(packageName, userHandle);
13688
13689        /*
13690         * Queue up an async operation since the package measurement may take a
13691         * little while.
13692         */
13693        Message msg = mHandler.obtainMessage(INIT_COPY);
13694        msg.obj = new MeasureParams(stats, observer);
13695        mHandler.sendMessage(msg);
13696    }
13697
13698    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13699            PackageStats pStats) {
13700        if (packageName == null) {
13701            Slog.w(TAG, "Attempt to get size of null packageName.");
13702            return false;
13703        }
13704        PackageParser.Package p;
13705        boolean dataOnly = false;
13706        String libDirRoot = null;
13707        String asecPath = null;
13708        PackageSetting ps = null;
13709        synchronized (mPackages) {
13710            p = mPackages.get(packageName);
13711            ps = mSettings.mPackages.get(packageName);
13712            if(p == null) {
13713                dataOnly = true;
13714                if((ps == null) || (ps.pkg == null)) {
13715                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13716                    return false;
13717                }
13718                p = ps.pkg;
13719            }
13720            if (ps != null) {
13721                libDirRoot = ps.legacyNativeLibraryPathString;
13722            }
13723            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13724                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13725                if (secureContainerId != null) {
13726                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13727                }
13728            }
13729        }
13730        String publicSrcDir = null;
13731        if(!dataOnly) {
13732            final ApplicationInfo applicationInfo = p.applicationInfo;
13733            if (applicationInfo == null) {
13734                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13735                return false;
13736            }
13737            if (p.isForwardLocked()) {
13738                publicSrcDir = applicationInfo.getBaseResourcePath();
13739            }
13740        }
13741        // TODO: extend to measure size of split APKs
13742        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13743        // not just the first level.
13744        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13745        // just the primary.
13746        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13747        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13748                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13749        if (res < 0) {
13750            return false;
13751        }
13752
13753        // Fix-up for forward-locked applications in ASEC containers.
13754        if (!isExternal(p)) {
13755            pStats.codeSize += pStats.externalCodeSize;
13756            pStats.externalCodeSize = 0L;
13757        }
13758
13759        return true;
13760    }
13761
13762
13763    @Override
13764    public void addPackageToPreferred(String packageName) {
13765        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13766    }
13767
13768    @Override
13769    public void removePackageFromPreferred(String packageName) {
13770        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13771    }
13772
13773    @Override
13774    public List<PackageInfo> getPreferredPackages(int flags) {
13775        return new ArrayList<PackageInfo>();
13776    }
13777
13778    private int getUidTargetSdkVersionLockedLPr(int uid) {
13779        Object obj = mSettings.getUserIdLPr(uid);
13780        if (obj instanceof SharedUserSetting) {
13781            final SharedUserSetting sus = (SharedUserSetting) obj;
13782            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13783            final Iterator<PackageSetting> it = sus.packages.iterator();
13784            while (it.hasNext()) {
13785                final PackageSetting ps = it.next();
13786                if (ps.pkg != null) {
13787                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13788                    if (v < vers) vers = v;
13789                }
13790            }
13791            return vers;
13792        } else if (obj instanceof PackageSetting) {
13793            final PackageSetting ps = (PackageSetting) obj;
13794            if (ps.pkg != null) {
13795                return ps.pkg.applicationInfo.targetSdkVersion;
13796            }
13797        }
13798        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13799    }
13800
13801    @Override
13802    public void addPreferredActivity(IntentFilter filter, int match,
13803            ComponentName[] set, ComponentName activity, int userId) {
13804        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13805                "Adding preferred");
13806    }
13807
13808    private void addPreferredActivityInternal(IntentFilter filter, int match,
13809            ComponentName[] set, ComponentName activity, boolean always, int userId,
13810            String opname) {
13811        // writer
13812        int callingUid = Binder.getCallingUid();
13813        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13814        if (filter.countActions() == 0) {
13815            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13816            return;
13817        }
13818        synchronized (mPackages) {
13819            if (mContext.checkCallingOrSelfPermission(
13820                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13821                    != PackageManager.PERMISSION_GRANTED) {
13822                if (getUidTargetSdkVersionLockedLPr(callingUid)
13823                        < Build.VERSION_CODES.FROYO) {
13824                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13825                            + callingUid);
13826                    return;
13827                }
13828                mContext.enforceCallingOrSelfPermission(
13829                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13830            }
13831
13832            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13833            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13834                    + userId + ":");
13835            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13836            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13837            scheduleWritePackageRestrictionsLocked(userId);
13838        }
13839    }
13840
13841    @Override
13842    public void replacePreferredActivity(IntentFilter filter, int match,
13843            ComponentName[] set, ComponentName activity, int userId) {
13844        if (filter.countActions() != 1) {
13845            throw new IllegalArgumentException(
13846                    "replacePreferredActivity expects filter to have only 1 action.");
13847        }
13848        if (filter.countDataAuthorities() != 0
13849                || filter.countDataPaths() != 0
13850                || filter.countDataSchemes() > 1
13851                || filter.countDataTypes() != 0) {
13852            throw new IllegalArgumentException(
13853                    "replacePreferredActivity expects filter to have no data authorities, " +
13854                    "paths, or types; and at most one scheme.");
13855        }
13856
13857        final int callingUid = Binder.getCallingUid();
13858        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13859        synchronized (mPackages) {
13860            if (mContext.checkCallingOrSelfPermission(
13861                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13862                    != PackageManager.PERMISSION_GRANTED) {
13863                if (getUidTargetSdkVersionLockedLPr(callingUid)
13864                        < Build.VERSION_CODES.FROYO) {
13865                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13866                            + Binder.getCallingUid());
13867                    return;
13868                }
13869                mContext.enforceCallingOrSelfPermission(
13870                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13871            }
13872
13873            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13874            if (pir != null) {
13875                // Get all of the existing entries that exactly match this filter.
13876                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13877                if (existing != null && existing.size() == 1) {
13878                    PreferredActivity cur = existing.get(0);
13879                    if (DEBUG_PREFERRED) {
13880                        Slog.i(TAG, "Checking replace of preferred:");
13881                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13882                        if (!cur.mPref.mAlways) {
13883                            Slog.i(TAG, "  -- CUR; not mAlways!");
13884                        } else {
13885                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13886                            Slog.i(TAG, "  -- CUR: mSet="
13887                                    + Arrays.toString(cur.mPref.mSetComponents));
13888                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13889                            Slog.i(TAG, "  -- NEW: mMatch="
13890                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13891                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13892                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13893                        }
13894                    }
13895                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13896                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13897                            && cur.mPref.sameSet(set)) {
13898                        // Setting the preferred activity to what it happens to be already
13899                        if (DEBUG_PREFERRED) {
13900                            Slog.i(TAG, "Replacing with same preferred activity "
13901                                    + cur.mPref.mShortComponent + " for user "
13902                                    + userId + ":");
13903                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13904                        }
13905                        return;
13906                    }
13907                }
13908
13909                if (existing != null) {
13910                    if (DEBUG_PREFERRED) {
13911                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13912                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13913                    }
13914                    for (int i = 0; i < existing.size(); i++) {
13915                        PreferredActivity pa = existing.get(i);
13916                        if (DEBUG_PREFERRED) {
13917                            Slog.i(TAG, "Removing existing preferred activity "
13918                                    + pa.mPref.mComponent + ":");
13919                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13920                        }
13921                        pir.removeFilter(pa);
13922                    }
13923                }
13924            }
13925            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13926                    "Replacing preferred");
13927        }
13928    }
13929
13930    @Override
13931    public void clearPackagePreferredActivities(String packageName) {
13932        final int uid = Binder.getCallingUid();
13933        // writer
13934        synchronized (mPackages) {
13935            PackageParser.Package pkg = mPackages.get(packageName);
13936            if (pkg == null || pkg.applicationInfo.uid != uid) {
13937                if (mContext.checkCallingOrSelfPermission(
13938                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13939                        != PackageManager.PERMISSION_GRANTED) {
13940                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13941                            < Build.VERSION_CODES.FROYO) {
13942                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13943                                + Binder.getCallingUid());
13944                        return;
13945                    }
13946                    mContext.enforceCallingOrSelfPermission(
13947                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13948                }
13949            }
13950
13951            int user = UserHandle.getCallingUserId();
13952            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13953                scheduleWritePackageRestrictionsLocked(user);
13954            }
13955        }
13956    }
13957
13958    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13959    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13960        ArrayList<PreferredActivity> removed = null;
13961        boolean changed = false;
13962        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13963            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13964            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13965            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13966                continue;
13967            }
13968            Iterator<PreferredActivity> it = pir.filterIterator();
13969            while (it.hasNext()) {
13970                PreferredActivity pa = it.next();
13971                // Mark entry for removal only if it matches the package name
13972                // and the entry is of type "always".
13973                if (packageName == null ||
13974                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13975                                && pa.mPref.mAlways)) {
13976                    if (removed == null) {
13977                        removed = new ArrayList<PreferredActivity>();
13978                    }
13979                    removed.add(pa);
13980                }
13981            }
13982            if (removed != null) {
13983                for (int j=0; j<removed.size(); j++) {
13984                    PreferredActivity pa = removed.get(j);
13985                    pir.removeFilter(pa);
13986                }
13987                changed = true;
13988            }
13989        }
13990        return changed;
13991    }
13992
13993    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13994    private void clearIntentFilterVerificationsLPw(int userId) {
13995        final int packageCount = mPackages.size();
13996        for (int i = 0; i < packageCount; i++) {
13997            PackageParser.Package pkg = mPackages.valueAt(i);
13998            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13999        }
14000    }
14001
14002    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14003    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14004        if (userId == UserHandle.USER_ALL) {
14005            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14006                    sUserManager.getUserIds())) {
14007                for (int oneUserId : sUserManager.getUserIds()) {
14008                    scheduleWritePackageRestrictionsLocked(oneUserId);
14009                }
14010            }
14011        } else {
14012            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14013                scheduleWritePackageRestrictionsLocked(userId);
14014            }
14015        }
14016    }
14017
14018    void clearDefaultBrowserIfNeeded(String packageName) {
14019        for (int oneUserId : sUserManager.getUserIds()) {
14020            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14021            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14022            if (packageName.equals(defaultBrowserPackageName)) {
14023                setDefaultBrowserPackageName(null, oneUserId);
14024            }
14025        }
14026    }
14027
14028    @Override
14029    public void resetApplicationPreferences(int userId) {
14030        mContext.enforceCallingOrSelfPermission(
14031                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14032        // writer
14033        synchronized (mPackages) {
14034            final long identity = Binder.clearCallingIdentity();
14035            try {
14036                clearPackagePreferredActivitiesLPw(null, userId);
14037                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14038                // TODO: We have to reset the default SMS and Phone. This requires
14039                // significant refactoring to keep all default apps in the package
14040                // manager (cleaner but more work) or have the services provide
14041                // callbacks to the package manager to request a default app reset.
14042                applyFactoryDefaultBrowserLPw(userId);
14043                clearIntentFilterVerificationsLPw(userId);
14044                primeDomainVerificationsLPw(userId);
14045                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14046                scheduleWritePackageRestrictionsLocked(userId);
14047            } finally {
14048                Binder.restoreCallingIdentity(identity);
14049            }
14050        }
14051    }
14052
14053    @Override
14054    public int getPreferredActivities(List<IntentFilter> outFilters,
14055            List<ComponentName> outActivities, String packageName) {
14056
14057        int num = 0;
14058        final int userId = UserHandle.getCallingUserId();
14059        // reader
14060        synchronized (mPackages) {
14061            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14062            if (pir != null) {
14063                final Iterator<PreferredActivity> it = pir.filterIterator();
14064                while (it.hasNext()) {
14065                    final PreferredActivity pa = it.next();
14066                    if (packageName == null
14067                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14068                                    && pa.mPref.mAlways)) {
14069                        if (outFilters != null) {
14070                            outFilters.add(new IntentFilter(pa));
14071                        }
14072                        if (outActivities != null) {
14073                            outActivities.add(pa.mPref.mComponent);
14074                        }
14075                    }
14076                }
14077            }
14078        }
14079
14080        return num;
14081    }
14082
14083    @Override
14084    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14085            int userId) {
14086        int callingUid = Binder.getCallingUid();
14087        if (callingUid != Process.SYSTEM_UID) {
14088            throw new SecurityException(
14089                    "addPersistentPreferredActivity can only be run by the system");
14090        }
14091        if (filter.countActions() == 0) {
14092            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14093            return;
14094        }
14095        synchronized (mPackages) {
14096            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14097                    " :");
14098            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14099            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14100                    new PersistentPreferredActivity(filter, activity));
14101            scheduleWritePackageRestrictionsLocked(userId);
14102        }
14103    }
14104
14105    @Override
14106    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14107        int callingUid = Binder.getCallingUid();
14108        if (callingUid != Process.SYSTEM_UID) {
14109            throw new SecurityException(
14110                    "clearPackagePersistentPreferredActivities can only be run by the system");
14111        }
14112        ArrayList<PersistentPreferredActivity> removed = null;
14113        boolean changed = false;
14114        synchronized (mPackages) {
14115            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14116                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14117                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14118                        .valueAt(i);
14119                if (userId != thisUserId) {
14120                    continue;
14121                }
14122                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14123                while (it.hasNext()) {
14124                    PersistentPreferredActivity ppa = it.next();
14125                    // Mark entry for removal only if it matches the package name.
14126                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14127                        if (removed == null) {
14128                            removed = new ArrayList<PersistentPreferredActivity>();
14129                        }
14130                        removed.add(ppa);
14131                    }
14132                }
14133                if (removed != null) {
14134                    for (int j=0; j<removed.size(); j++) {
14135                        PersistentPreferredActivity ppa = removed.get(j);
14136                        ppir.removeFilter(ppa);
14137                    }
14138                    changed = true;
14139                }
14140            }
14141
14142            if (changed) {
14143                scheduleWritePackageRestrictionsLocked(userId);
14144            }
14145        }
14146    }
14147
14148    /**
14149     * Common machinery for picking apart a restored XML blob and passing
14150     * it to a caller-supplied functor to be applied to the running system.
14151     */
14152    private void restoreFromXml(XmlPullParser parser, int userId,
14153            String expectedStartTag, BlobXmlRestorer functor)
14154            throws IOException, XmlPullParserException {
14155        int type;
14156        while ((type = parser.next()) != XmlPullParser.START_TAG
14157                && type != XmlPullParser.END_DOCUMENT) {
14158        }
14159        if (type != XmlPullParser.START_TAG) {
14160            // oops didn't find a start tag?!
14161            if (DEBUG_BACKUP) {
14162                Slog.e(TAG, "Didn't find start tag during restore");
14163            }
14164            return;
14165        }
14166
14167        // this is supposed to be TAG_PREFERRED_BACKUP
14168        if (!expectedStartTag.equals(parser.getName())) {
14169            if (DEBUG_BACKUP) {
14170                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14171            }
14172            return;
14173        }
14174
14175        // skip interfering stuff, then we're aligned with the backing implementation
14176        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14177        functor.apply(parser, userId);
14178    }
14179
14180    private interface BlobXmlRestorer {
14181        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14182    }
14183
14184    /**
14185     * Non-Binder method, support for the backup/restore mechanism: write the
14186     * full set of preferred activities in its canonical XML format.  Returns the
14187     * XML output as a byte array, or null if there is none.
14188     */
14189    @Override
14190    public byte[] getPreferredActivityBackup(int userId) {
14191        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14192            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14193        }
14194
14195        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14196        try {
14197            final XmlSerializer serializer = new FastXmlSerializer();
14198            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14199            serializer.startDocument(null, true);
14200            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14201
14202            synchronized (mPackages) {
14203                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14204            }
14205
14206            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14207            serializer.endDocument();
14208            serializer.flush();
14209        } catch (Exception e) {
14210            if (DEBUG_BACKUP) {
14211                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14212            }
14213            return null;
14214        }
14215
14216        return dataStream.toByteArray();
14217    }
14218
14219    @Override
14220    public void restorePreferredActivities(byte[] backup, int userId) {
14221        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14222            throw new SecurityException("Only the system may call restorePreferredActivities()");
14223        }
14224
14225        try {
14226            final XmlPullParser parser = Xml.newPullParser();
14227            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14228            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14229                    new BlobXmlRestorer() {
14230                        @Override
14231                        public void apply(XmlPullParser parser, int userId)
14232                                throws XmlPullParserException, IOException {
14233                            synchronized (mPackages) {
14234                                mSettings.readPreferredActivitiesLPw(parser, userId);
14235                            }
14236                        }
14237                    } );
14238        } catch (Exception e) {
14239            if (DEBUG_BACKUP) {
14240                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14241            }
14242        }
14243    }
14244
14245    /**
14246     * Non-Binder method, support for the backup/restore mechanism: write the
14247     * default browser (etc) settings in its canonical XML format.  Returns the default
14248     * browser XML representation as a byte array, or null if there is none.
14249     */
14250    @Override
14251    public byte[] getDefaultAppsBackup(int userId) {
14252        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14253            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14254        }
14255
14256        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14257        try {
14258            final XmlSerializer serializer = new FastXmlSerializer();
14259            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14260            serializer.startDocument(null, true);
14261            serializer.startTag(null, TAG_DEFAULT_APPS);
14262
14263            synchronized (mPackages) {
14264                mSettings.writeDefaultAppsLPr(serializer, userId);
14265            }
14266
14267            serializer.endTag(null, TAG_DEFAULT_APPS);
14268            serializer.endDocument();
14269            serializer.flush();
14270        } catch (Exception e) {
14271            if (DEBUG_BACKUP) {
14272                Slog.e(TAG, "Unable to write default apps for backup", e);
14273            }
14274            return null;
14275        }
14276
14277        return dataStream.toByteArray();
14278    }
14279
14280    @Override
14281    public void restoreDefaultApps(byte[] backup, int userId) {
14282        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14283            throw new SecurityException("Only the system may call restoreDefaultApps()");
14284        }
14285
14286        try {
14287            final XmlPullParser parser = Xml.newPullParser();
14288            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14289            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14290                    new BlobXmlRestorer() {
14291                        @Override
14292                        public void apply(XmlPullParser parser, int userId)
14293                                throws XmlPullParserException, IOException {
14294                            synchronized (mPackages) {
14295                                mSettings.readDefaultAppsLPw(parser, userId);
14296                            }
14297                        }
14298                    } );
14299        } catch (Exception e) {
14300            if (DEBUG_BACKUP) {
14301                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14302            }
14303        }
14304    }
14305
14306    @Override
14307    public byte[] getIntentFilterVerificationBackup(int userId) {
14308        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14309            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14310        }
14311
14312        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14313        try {
14314            final XmlSerializer serializer = new FastXmlSerializer();
14315            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14316            serializer.startDocument(null, true);
14317            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14318
14319            synchronized (mPackages) {
14320                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14321            }
14322
14323            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14324            serializer.endDocument();
14325            serializer.flush();
14326        } catch (Exception e) {
14327            if (DEBUG_BACKUP) {
14328                Slog.e(TAG, "Unable to write default apps for backup", e);
14329            }
14330            return null;
14331        }
14332
14333        return dataStream.toByteArray();
14334    }
14335
14336    @Override
14337    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14338        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14339            throw new SecurityException("Only the system may call restorePreferredActivities()");
14340        }
14341
14342        try {
14343            final XmlPullParser parser = Xml.newPullParser();
14344            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14345            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14346                    new BlobXmlRestorer() {
14347                        @Override
14348                        public void apply(XmlPullParser parser, int userId)
14349                                throws XmlPullParserException, IOException {
14350                            synchronized (mPackages) {
14351                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14352                                mSettings.writeLPr();
14353                            }
14354                        }
14355                    } );
14356        } catch (Exception e) {
14357            if (DEBUG_BACKUP) {
14358                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14359            }
14360        }
14361    }
14362
14363    @Override
14364    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14365            int sourceUserId, int targetUserId, int flags) {
14366        mContext.enforceCallingOrSelfPermission(
14367                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14368        int callingUid = Binder.getCallingUid();
14369        enforceOwnerRights(ownerPackage, callingUid);
14370        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14371        if (intentFilter.countActions() == 0) {
14372            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14373            return;
14374        }
14375        synchronized (mPackages) {
14376            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14377                    ownerPackage, targetUserId, flags);
14378            CrossProfileIntentResolver resolver =
14379                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14380            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14381            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14382            if (existing != null) {
14383                int size = existing.size();
14384                for (int i = 0; i < size; i++) {
14385                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14386                        return;
14387                    }
14388                }
14389            }
14390            resolver.addFilter(newFilter);
14391            scheduleWritePackageRestrictionsLocked(sourceUserId);
14392        }
14393    }
14394
14395    @Override
14396    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14397        mContext.enforceCallingOrSelfPermission(
14398                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14399        int callingUid = Binder.getCallingUid();
14400        enforceOwnerRights(ownerPackage, callingUid);
14401        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14402        synchronized (mPackages) {
14403            CrossProfileIntentResolver resolver =
14404                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14405            ArraySet<CrossProfileIntentFilter> set =
14406                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14407            for (CrossProfileIntentFilter filter : set) {
14408                if (filter.getOwnerPackage().equals(ownerPackage)) {
14409                    resolver.removeFilter(filter);
14410                }
14411            }
14412            scheduleWritePackageRestrictionsLocked(sourceUserId);
14413        }
14414    }
14415
14416    // Enforcing that callingUid is owning pkg on userId
14417    private void enforceOwnerRights(String pkg, int callingUid) {
14418        // The system owns everything.
14419        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14420            return;
14421        }
14422        int callingUserId = UserHandle.getUserId(callingUid);
14423        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14424        if (pi == null) {
14425            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14426                    + callingUserId);
14427        }
14428        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14429            throw new SecurityException("Calling uid " + callingUid
14430                    + " does not own package " + pkg);
14431        }
14432    }
14433
14434    @Override
14435    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14436        Intent intent = new Intent(Intent.ACTION_MAIN);
14437        intent.addCategory(Intent.CATEGORY_HOME);
14438
14439        final int callingUserId = UserHandle.getCallingUserId();
14440        List<ResolveInfo> list = queryIntentActivities(intent, null,
14441                PackageManager.GET_META_DATA, callingUserId);
14442        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14443                true, false, false, callingUserId);
14444
14445        allHomeCandidates.clear();
14446        if (list != null) {
14447            for (ResolveInfo ri : list) {
14448                allHomeCandidates.add(ri);
14449            }
14450        }
14451        return (preferred == null || preferred.activityInfo == null)
14452                ? null
14453                : new ComponentName(preferred.activityInfo.packageName,
14454                        preferred.activityInfo.name);
14455    }
14456
14457    @Override
14458    public void setApplicationEnabledSetting(String appPackageName,
14459            int newState, int flags, int userId, String callingPackage) {
14460        if (!sUserManager.exists(userId)) return;
14461        if (callingPackage == null) {
14462            callingPackage = Integer.toString(Binder.getCallingUid());
14463        }
14464        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14465    }
14466
14467    @Override
14468    public void setComponentEnabledSetting(ComponentName componentName,
14469            int newState, int flags, int userId) {
14470        if (!sUserManager.exists(userId)) return;
14471        setEnabledSetting(componentName.getPackageName(),
14472                componentName.getClassName(), newState, flags, userId, null);
14473    }
14474
14475    private void setEnabledSetting(final String packageName, String className, int newState,
14476            final int flags, int userId, String callingPackage) {
14477        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14478              || newState == COMPONENT_ENABLED_STATE_ENABLED
14479              || newState == COMPONENT_ENABLED_STATE_DISABLED
14480              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14481              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14482            throw new IllegalArgumentException("Invalid new component state: "
14483                    + newState);
14484        }
14485        PackageSetting pkgSetting;
14486        final int uid = Binder.getCallingUid();
14487        final int permission = mContext.checkCallingOrSelfPermission(
14488                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14489        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14490        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14491        boolean sendNow = false;
14492        boolean isApp = (className == null);
14493        String componentName = isApp ? packageName : className;
14494        int packageUid = -1;
14495        ArrayList<String> components;
14496
14497        // writer
14498        synchronized (mPackages) {
14499            pkgSetting = mSettings.mPackages.get(packageName);
14500            if (pkgSetting == null) {
14501                if (className == null) {
14502                    throw new IllegalArgumentException(
14503                            "Unknown package: " + packageName);
14504                }
14505                throw new IllegalArgumentException(
14506                        "Unknown component: " + packageName
14507                        + "/" + className);
14508            }
14509            // Allow root and verify that userId is not being specified by a different user
14510            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14511                throw new SecurityException(
14512                        "Permission Denial: attempt to change component state from pid="
14513                        + Binder.getCallingPid()
14514                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14515            }
14516            if (className == null) {
14517                // We're dealing with an application/package level state change
14518                if (pkgSetting.getEnabled(userId) == newState) {
14519                    // Nothing to do
14520                    return;
14521                }
14522                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14523                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14524                    // Don't care about who enables an app.
14525                    callingPackage = null;
14526                }
14527                pkgSetting.setEnabled(newState, userId, callingPackage);
14528                // pkgSetting.pkg.mSetEnabled = newState;
14529            } else {
14530                // We're dealing with a component level state change
14531                // First, verify that this is a valid class name.
14532                PackageParser.Package pkg = pkgSetting.pkg;
14533                if (pkg == null || !pkg.hasComponentClassName(className)) {
14534                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14535                        throw new IllegalArgumentException("Component class " + className
14536                                + " does not exist in " + packageName);
14537                    } else {
14538                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14539                                + className + " does not exist in " + packageName);
14540                    }
14541                }
14542                switch (newState) {
14543                case COMPONENT_ENABLED_STATE_ENABLED:
14544                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14545                        return;
14546                    }
14547                    break;
14548                case COMPONENT_ENABLED_STATE_DISABLED:
14549                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14550                        return;
14551                    }
14552                    break;
14553                case COMPONENT_ENABLED_STATE_DEFAULT:
14554                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14555                        return;
14556                    }
14557                    break;
14558                default:
14559                    Slog.e(TAG, "Invalid new component state: " + newState);
14560                    return;
14561                }
14562            }
14563            scheduleWritePackageRestrictionsLocked(userId);
14564            components = mPendingBroadcasts.get(userId, packageName);
14565            final boolean newPackage = components == null;
14566            if (newPackage) {
14567                components = new ArrayList<String>();
14568            }
14569            if (!components.contains(componentName)) {
14570                components.add(componentName);
14571            }
14572            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14573                sendNow = true;
14574                // Purge entry from pending broadcast list if another one exists already
14575                // since we are sending one right away.
14576                mPendingBroadcasts.remove(userId, packageName);
14577            } else {
14578                if (newPackage) {
14579                    mPendingBroadcasts.put(userId, packageName, components);
14580                }
14581                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14582                    // Schedule a message
14583                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14584                }
14585            }
14586        }
14587
14588        long callingId = Binder.clearCallingIdentity();
14589        try {
14590            if (sendNow) {
14591                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14592                sendPackageChangedBroadcast(packageName,
14593                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14594            }
14595        } finally {
14596            Binder.restoreCallingIdentity(callingId);
14597        }
14598    }
14599
14600    private void sendPackageChangedBroadcast(String packageName,
14601            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14602        if (DEBUG_INSTALL)
14603            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14604                    + componentNames);
14605        Bundle extras = new Bundle(4);
14606        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14607        String nameList[] = new String[componentNames.size()];
14608        componentNames.toArray(nameList);
14609        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14610        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14611        extras.putInt(Intent.EXTRA_UID, packageUid);
14612        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14613                new int[] {UserHandle.getUserId(packageUid)});
14614    }
14615
14616    @Override
14617    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14618        if (!sUserManager.exists(userId)) return;
14619        final int uid = Binder.getCallingUid();
14620        final int permission = mContext.checkCallingOrSelfPermission(
14621                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14622        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14623        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14624        // writer
14625        synchronized (mPackages) {
14626            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14627                    allowedByPermission, uid, userId)) {
14628                scheduleWritePackageRestrictionsLocked(userId);
14629            }
14630        }
14631    }
14632
14633    @Override
14634    public String getInstallerPackageName(String packageName) {
14635        // reader
14636        synchronized (mPackages) {
14637            return mSettings.getInstallerPackageNameLPr(packageName);
14638        }
14639    }
14640
14641    @Override
14642    public int getApplicationEnabledSetting(String packageName, int userId) {
14643        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14644        int uid = Binder.getCallingUid();
14645        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14646        // reader
14647        synchronized (mPackages) {
14648            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14649        }
14650    }
14651
14652    @Override
14653    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14654        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14655        int uid = Binder.getCallingUid();
14656        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14657        // reader
14658        synchronized (mPackages) {
14659            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14660        }
14661    }
14662
14663    @Override
14664    public void enterSafeMode() {
14665        enforceSystemOrRoot("Only the system can request entering safe mode");
14666
14667        if (!mSystemReady) {
14668            mSafeMode = true;
14669        }
14670    }
14671
14672    @Override
14673    public void systemReady() {
14674        mSystemReady = true;
14675
14676        // Read the compatibilty setting when the system is ready.
14677        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14678                mContext.getContentResolver(),
14679                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14680        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14681        if (DEBUG_SETTINGS) {
14682            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14683        }
14684
14685        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14686
14687        synchronized (mPackages) {
14688            // Verify that all of the preferred activity components actually
14689            // exist.  It is possible for applications to be updated and at
14690            // that point remove a previously declared activity component that
14691            // had been set as a preferred activity.  We try to clean this up
14692            // the next time we encounter that preferred activity, but it is
14693            // possible for the user flow to never be able to return to that
14694            // situation so here we do a sanity check to make sure we haven't
14695            // left any junk around.
14696            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14697            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14698                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14699                removed.clear();
14700                for (PreferredActivity pa : pir.filterSet()) {
14701                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14702                        removed.add(pa);
14703                    }
14704                }
14705                if (removed.size() > 0) {
14706                    for (int r=0; r<removed.size(); r++) {
14707                        PreferredActivity pa = removed.get(r);
14708                        Slog.w(TAG, "Removing dangling preferred activity: "
14709                                + pa.mPref.mComponent);
14710                        pir.removeFilter(pa);
14711                    }
14712                    mSettings.writePackageRestrictionsLPr(
14713                            mSettings.mPreferredActivities.keyAt(i));
14714                }
14715            }
14716
14717            for (int userId : UserManagerService.getInstance().getUserIds()) {
14718                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14719                    grantPermissionsUserIds = ArrayUtils.appendInt(
14720                            grantPermissionsUserIds, userId);
14721                }
14722            }
14723        }
14724        sUserManager.systemReady();
14725
14726        // If we upgraded grant all default permissions before kicking off.
14727        for (int userId : grantPermissionsUserIds) {
14728            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14729        }
14730
14731        // Kick off any messages waiting for system ready
14732        if (mPostSystemReadyMessages != null) {
14733            for (Message msg : mPostSystemReadyMessages) {
14734                msg.sendToTarget();
14735            }
14736            mPostSystemReadyMessages = null;
14737        }
14738
14739        // Watch for external volumes that come and go over time
14740        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14741        storage.registerListener(mStorageListener);
14742
14743        mInstallerService.systemReady();
14744        mPackageDexOptimizer.systemReady();
14745
14746        MountServiceInternal mountServiceInternal = LocalServices.getService(
14747                MountServiceInternal.class);
14748        mountServiceInternal.addExternalStoragePolicy(
14749                new MountServiceInternal.ExternalStorageMountPolicy() {
14750            @Override
14751            public int getMountMode(int uid, String packageName) {
14752                if (Process.isIsolated(uid)) {
14753                    return Zygote.MOUNT_EXTERNAL_NONE;
14754                }
14755                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14756                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14757                }
14758                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14759                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14760                }
14761                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14762                    return Zygote.MOUNT_EXTERNAL_READ;
14763                }
14764                return Zygote.MOUNT_EXTERNAL_WRITE;
14765            }
14766
14767            @Override
14768            public boolean hasExternalStorage(int uid, String packageName) {
14769                return true;
14770            }
14771        });
14772    }
14773
14774    @Override
14775    public boolean isSafeMode() {
14776        return mSafeMode;
14777    }
14778
14779    @Override
14780    public boolean hasSystemUidErrors() {
14781        return mHasSystemUidErrors;
14782    }
14783
14784    static String arrayToString(int[] array) {
14785        StringBuffer buf = new StringBuffer(128);
14786        buf.append('[');
14787        if (array != null) {
14788            for (int i=0; i<array.length; i++) {
14789                if (i > 0) buf.append(", ");
14790                buf.append(array[i]);
14791            }
14792        }
14793        buf.append(']');
14794        return buf.toString();
14795    }
14796
14797    static class DumpState {
14798        public static final int DUMP_LIBS = 1 << 0;
14799        public static final int DUMP_FEATURES = 1 << 1;
14800        public static final int DUMP_RESOLVERS = 1 << 2;
14801        public static final int DUMP_PERMISSIONS = 1 << 3;
14802        public static final int DUMP_PACKAGES = 1 << 4;
14803        public static final int DUMP_SHARED_USERS = 1 << 5;
14804        public static final int DUMP_MESSAGES = 1 << 6;
14805        public static final int DUMP_PROVIDERS = 1 << 7;
14806        public static final int DUMP_VERIFIERS = 1 << 8;
14807        public static final int DUMP_PREFERRED = 1 << 9;
14808        public static final int DUMP_PREFERRED_XML = 1 << 10;
14809        public static final int DUMP_KEYSETS = 1 << 11;
14810        public static final int DUMP_VERSION = 1 << 12;
14811        public static final int DUMP_INSTALLS = 1 << 13;
14812        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14813        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14814
14815        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14816
14817        private int mTypes;
14818
14819        private int mOptions;
14820
14821        private boolean mTitlePrinted;
14822
14823        private SharedUserSetting mSharedUser;
14824
14825        public boolean isDumping(int type) {
14826            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14827                return true;
14828            }
14829
14830            return (mTypes & type) != 0;
14831        }
14832
14833        public void setDump(int type) {
14834            mTypes |= type;
14835        }
14836
14837        public boolean isOptionEnabled(int option) {
14838            return (mOptions & option) != 0;
14839        }
14840
14841        public void setOptionEnabled(int option) {
14842            mOptions |= option;
14843        }
14844
14845        public boolean onTitlePrinted() {
14846            final boolean printed = mTitlePrinted;
14847            mTitlePrinted = true;
14848            return printed;
14849        }
14850
14851        public boolean getTitlePrinted() {
14852            return mTitlePrinted;
14853        }
14854
14855        public void setTitlePrinted(boolean enabled) {
14856            mTitlePrinted = enabled;
14857        }
14858
14859        public SharedUserSetting getSharedUser() {
14860            return mSharedUser;
14861        }
14862
14863        public void setSharedUser(SharedUserSetting user) {
14864            mSharedUser = user;
14865        }
14866    }
14867
14868    @Override
14869    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14870        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14871                != PackageManager.PERMISSION_GRANTED) {
14872            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14873                    + Binder.getCallingPid()
14874                    + ", uid=" + Binder.getCallingUid()
14875                    + " without permission "
14876                    + android.Manifest.permission.DUMP);
14877            return;
14878        }
14879
14880        DumpState dumpState = new DumpState();
14881        boolean fullPreferred = false;
14882        boolean checkin = false;
14883
14884        String packageName = null;
14885        ArraySet<String> permissionNames = null;
14886
14887        int opti = 0;
14888        while (opti < args.length) {
14889            String opt = args[opti];
14890            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14891                break;
14892            }
14893            opti++;
14894
14895            if ("-a".equals(opt)) {
14896                // Right now we only know how to print all.
14897            } else if ("-h".equals(opt)) {
14898                pw.println("Package manager dump options:");
14899                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14900                pw.println("    --checkin: dump for a checkin");
14901                pw.println("    -f: print details of intent filters");
14902                pw.println("    -h: print this help");
14903                pw.println("  cmd may be one of:");
14904                pw.println("    l[ibraries]: list known shared libraries");
14905                pw.println("    f[ibraries]: list device features");
14906                pw.println("    k[eysets]: print known keysets");
14907                pw.println("    r[esolvers]: dump intent resolvers");
14908                pw.println("    perm[issions]: dump permissions");
14909                pw.println("    permission [name ...]: dump declaration and use of given permission");
14910                pw.println("    pref[erred]: print preferred package settings");
14911                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14912                pw.println("    prov[iders]: dump content providers");
14913                pw.println("    p[ackages]: dump installed packages");
14914                pw.println("    s[hared-users]: dump shared user IDs");
14915                pw.println("    m[essages]: print collected runtime messages");
14916                pw.println("    v[erifiers]: print package verifier info");
14917                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14918                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14919                pw.println("    version: print database version info");
14920                pw.println("    write: write current settings now");
14921                pw.println("    installs: details about install sessions");
14922                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14923                pw.println("    <package.name>: info about given package");
14924                return;
14925            } else if ("--checkin".equals(opt)) {
14926                checkin = true;
14927            } else if ("-f".equals(opt)) {
14928                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14929            } else {
14930                pw.println("Unknown argument: " + opt + "; use -h for help");
14931            }
14932        }
14933
14934        // Is the caller requesting to dump a particular piece of data?
14935        if (opti < args.length) {
14936            String cmd = args[opti];
14937            opti++;
14938            // Is this a package name?
14939            if ("android".equals(cmd) || cmd.contains(".")) {
14940                packageName = cmd;
14941                // When dumping a single package, we always dump all of its
14942                // filter information since the amount of data will be reasonable.
14943                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14944            } else if ("check-permission".equals(cmd)) {
14945                if (opti >= args.length) {
14946                    pw.println("Error: check-permission missing permission argument");
14947                    return;
14948                }
14949                String perm = args[opti];
14950                opti++;
14951                if (opti >= args.length) {
14952                    pw.println("Error: check-permission missing package argument");
14953                    return;
14954                }
14955                String pkg = args[opti];
14956                opti++;
14957                int user = UserHandle.getUserId(Binder.getCallingUid());
14958                if (opti < args.length) {
14959                    try {
14960                        user = Integer.parseInt(args[opti]);
14961                    } catch (NumberFormatException e) {
14962                        pw.println("Error: check-permission user argument is not a number: "
14963                                + args[opti]);
14964                        return;
14965                    }
14966                }
14967                pw.println(checkPermission(perm, pkg, user));
14968                return;
14969            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14970                dumpState.setDump(DumpState.DUMP_LIBS);
14971            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14972                dumpState.setDump(DumpState.DUMP_FEATURES);
14973            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14974                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14975            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14976                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14977            } else if ("permission".equals(cmd)) {
14978                if (opti >= args.length) {
14979                    pw.println("Error: permission requires permission name");
14980                    return;
14981                }
14982                permissionNames = new ArraySet<>();
14983                while (opti < args.length) {
14984                    permissionNames.add(args[opti]);
14985                    opti++;
14986                }
14987                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14988                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14989            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14990                dumpState.setDump(DumpState.DUMP_PREFERRED);
14991            } else if ("preferred-xml".equals(cmd)) {
14992                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14993                if (opti < args.length && "--full".equals(args[opti])) {
14994                    fullPreferred = true;
14995                    opti++;
14996                }
14997            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14998                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14999            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15000                dumpState.setDump(DumpState.DUMP_PACKAGES);
15001            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15002                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15003            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15004                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15005            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15006                dumpState.setDump(DumpState.DUMP_MESSAGES);
15007            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15008                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15009            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15010                    || "intent-filter-verifiers".equals(cmd)) {
15011                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15012            } else if ("version".equals(cmd)) {
15013                dumpState.setDump(DumpState.DUMP_VERSION);
15014            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15015                dumpState.setDump(DumpState.DUMP_KEYSETS);
15016            } else if ("installs".equals(cmd)) {
15017                dumpState.setDump(DumpState.DUMP_INSTALLS);
15018            } else if ("write".equals(cmd)) {
15019                synchronized (mPackages) {
15020                    mSettings.writeLPr();
15021                    pw.println("Settings written.");
15022                    return;
15023                }
15024            }
15025        }
15026
15027        if (checkin) {
15028            pw.println("vers,1");
15029        }
15030
15031        // reader
15032        synchronized (mPackages) {
15033            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15034                if (!checkin) {
15035                    if (dumpState.onTitlePrinted())
15036                        pw.println();
15037                    pw.println("Database versions:");
15038                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15039                }
15040            }
15041
15042            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15043                if (!checkin) {
15044                    if (dumpState.onTitlePrinted())
15045                        pw.println();
15046                    pw.println("Verifiers:");
15047                    pw.print("  Required: ");
15048                    pw.print(mRequiredVerifierPackage);
15049                    pw.print(" (uid=");
15050                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15051                    pw.println(")");
15052                } else if (mRequiredVerifierPackage != null) {
15053                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15054                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15055                }
15056            }
15057
15058            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15059                    packageName == null) {
15060                if (mIntentFilterVerifierComponent != null) {
15061                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15062                    if (!checkin) {
15063                        if (dumpState.onTitlePrinted())
15064                            pw.println();
15065                        pw.println("Intent Filter Verifier:");
15066                        pw.print("  Using: ");
15067                        pw.print(verifierPackageName);
15068                        pw.print(" (uid=");
15069                        pw.print(getPackageUid(verifierPackageName, 0));
15070                        pw.println(")");
15071                    } else if (verifierPackageName != null) {
15072                        pw.print("ifv,"); pw.print(verifierPackageName);
15073                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15074                    }
15075                } else {
15076                    pw.println();
15077                    pw.println("No Intent Filter Verifier available!");
15078                }
15079            }
15080
15081            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15082                boolean printedHeader = false;
15083                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15084                while (it.hasNext()) {
15085                    String name = it.next();
15086                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15087                    if (!checkin) {
15088                        if (!printedHeader) {
15089                            if (dumpState.onTitlePrinted())
15090                                pw.println();
15091                            pw.println("Libraries:");
15092                            printedHeader = true;
15093                        }
15094                        pw.print("  ");
15095                    } else {
15096                        pw.print("lib,");
15097                    }
15098                    pw.print(name);
15099                    if (!checkin) {
15100                        pw.print(" -> ");
15101                    }
15102                    if (ent.path != null) {
15103                        if (!checkin) {
15104                            pw.print("(jar) ");
15105                            pw.print(ent.path);
15106                        } else {
15107                            pw.print(",jar,");
15108                            pw.print(ent.path);
15109                        }
15110                    } else {
15111                        if (!checkin) {
15112                            pw.print("(apk) ");
15113                            pw.print(ent.apk);
15114                        } else {
15115                            pw.print(",apk,");
15116                            pw.print(ent.apk);
15117                        }
15118                    }
15119                    pw.println();
15120                }
15121            }
15122
15123            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15124                if (dumpState.onTitlePrinted())
15125                    pw.println();
15126                if (!checkin) {
15127                    pw.println("Features:");
15128                }
15129                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15130                while (it.hasNext()) {
15131                    String name = it.next();
15132                    if (!checkin) {
15133                        pw.print("  ");
15134                    } else {
15135                        pw.print("feat,");
15136                    }
15137                    pw.println(name);
15138                }
15139            }
15140
15141            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15142                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15143                        : "Activity Resolver Table:", "  ", packageName,
15144                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15145                    dumpState.setTitlePrinted(true);
15146                }
15147                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15148                        : "Receiver Resolver Table:", "  ", packageName,
15149                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15150                    dumpState.setTitlePrinted(true);
15151                }
15152                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15153                        : "Service Resolver Table:", "  ", packageName,
15154                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15155                    dumpState.setTitlePrinted(true);
15156                }
15157                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15158                        : "Provider Resolver Table:", "  ", packageName,
15159                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15160                    dumpState.setTitlePrinted(true);
15161                }
15162            }
15163
15164            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15165                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15166                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15167                    int user = mSettings.mPreferredActivities.keyAt(i);
15168                    if (pir.dump(pw,
15169                            dumpState.getTitlePrinted()
15170                                ? "\nPreferred Activities User " + user + ":"
15171                                : "Preferred Activities User " + user + ":", "  ",
15172                            packageName, true, false)) {
15173                        dumpState.setTitlePrinted(true);
15174                    }
15175                }
15176            }
15177
15178            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15179                pw.flush();
15180                FileOutputStream fout = new FileOutputStream(fd);
15181                BufferedOutputStream str = new BufferedOutputStream(fout);
15182                XmlSerializer serializer = new FastXmlSerializer();
15183                try {
15184                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15185                    serializer.startDocument(null, true);
15186                    serializer.setFeature(
15187                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15188                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15189                    serializer.endDocument();
15190                    serializer.flush();
15191                } catch (IllegalArgumentException e) {
15192                    pw.println("Failed writing: " + e);
15193                } catch (IllegalStateException e) {
15194                    pw.println("Failed writing: " + e);
15195                } catch (IOException e) {
15196                    pw.println("Failed writing: " + e);
15197                }
15198            }
15199
15200            if (!checkin
15201                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15202                    && packageName == null) {
15203                pw.println();
15204                int count = mSettings.mPackages.size();
15205                if (count == 0) {
15206                    pw.println("No applications!");
15207                    pw.println();
15208                } else {
15209                    final String prefix = "  ";
15210                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15211                    if (allPackageSettings.size() == 0) {
15212                        pw.println("No domain preferred apps!");
15213                        pw.println();
15214                    } else {
15215                        pw.println("App verification status:");
15216                        pw.println();
15217                        count = 0;
15218                        for (PackageSetting ps : allPackageSettings) {
15219                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15220                            if (ivi == null || ivi.getPackageName() == null) continue;
15221                            pw.println(prefix + "Package: " + ivi.getPackageName());
15222                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15223                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15224                            pw.println();
15225                            count++;
15226                        }
15227                        if (count == 0) {
15228                            pw.println(prefix + "No app verification established.");
15229                            pw.println();
15230                        }
15231                        for (int userId : sUserManager.getUserIds()) {
15232                            pw.println("App linkages for user " + userId + ":");
15233                            pw.println();
15234                            count = 0;
15235                            for (PackageSetting ps : allPackageSettings) {
15236                                final long status = ps.getDomainVerificationStatusForUser(userId);
15237                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15238                                    continue;
15239                                }
15240                                pw.println(prefix + "Package: " + ps.name);
15241                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15242                                String statusStr = IntentFilterVerificationInfo.
15243                                        getStatusStringFromValue(status);
15244                                pw.println(prefix + "Status:  " + statusStr);
15245                                pw.println();
15246                                count++;
15247                            }
15248                            if (count == 0) {
15249                                pw.println(prefix + "No configured app linkages.");
15250                                pw.println();
15251                            }
15252                        }
15253                    }
15254                }
15255            }
15256
15257            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15258                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15259                if (packageName == null && permissionNames == null) {
15260                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15261                        if (iperm == 0) {
15262                            if (dumpState.onTitlePrinted())
15263                                pw.println();
15264                            pw.println("AppOp Permissions:");
15265                        }
15266                        pw.print("  AppOp Permission ");
15267                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15268                        pw.println(":");
15269                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15270                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15271                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15272                        }
15273                    }
15274                }
15275            }
15276
15277            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15278                boolean printedSomething = false;
15279                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15280                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15281                        continue;
15282                    }
15283                    if (!printedSomething) {
15284                        if (dumpState.onTitlePrinted())
15285                            pw.println();
15286                        pw.println("Registered ContentProviders:");
15287                        printedSomething = true;
15288                    }
15289                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15290                    pw.print("    "); pw.println(p.toString());
15291                }
15292                printedSomething = false;
15293                for (Map.Entry<String, PackageParser.Provider> entry :
15294                        mProvidersByAuthority.entrySet()) {
15295                    PackageParser.Provider p = entry.getValue();
15296                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15297                        continue;
15298                    }
15299                    if (!printedSomething) {
15300                        if (dumpState.onTitlePrinted())
15301                            pw.println();
15302                        pw.println("ContentProvider Authorities:");
15303                        printedSomething = true;
15304                    }
15305                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15306                    pw.print("    "); pw.println(p.toString());
15307                    if (p.info != null && p.info.applicationInfo != null) {
15308                        final String appInfo = p.info.applicationInfo.toString();
15309                        pw.print("      applicationInfo="); pw.println(appInfo);
15310                    }
15311                }
15312            }
15313
15314            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15315                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15316            }
15317
15318            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15319                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15320            }
15321
15322            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15323                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15324            }
15325
15326            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15327                // XXX should handle packageName != null by dumping only install data that
15328                // the given package is involved with.
15329                if (dumpState.onTitlePrinted()) pw.println();
15330                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15331            }
15332
15333            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15334                if (dumpState.onTitlePrinted()) pw.println();
15335                mSettings.dumpReadMessagesLPr(pw, dumpState);
15336
15337                pw.println();
15338                pw.println("Package warning messages:");
15339                BufferedReader in = null;
15340                String line = null;
15341                try {
15342                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15343                    while ((line = in.readLine()) != null) {
15344                        if (line.contains("ignored: updated version")) continue;
15345                        pw.println(line);
15346                    }
15347                } catch (IOException ignored) {
15348                } finally {
15349                    IoUtils.closeQuietly(in);
15350                }
15351            }
15352
15353            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15354                BufferedReader in = null;
15355                String line = null;
15356                try {
15357                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15358                    while ((line = in.readLine()) != null) {
15359                        if (line.contains("ignored: updated version")) continue;
15360                        pw.print("msg,");
15361                        pw.println(line);
15362                    }
15363                } catch (IOException ignored) {
15364                } finally {
15365                    IoUtils.closeQuietly(in);
15366                }
15367            }
15368        }
15369    }
15370
15371    private String dumpDomainString(String packageName) {
15372        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15373        List<IntentFilter> filters = getAllIntentFilters(packageName);
15374
15375        ArraySet<String> result = new ArraySet<>();
15376        if (iviList.size() > 0) {
15377            for (IntentFilterVerificationInfo ivi : iviList) {
15378                for (String host : ivi.getDomains()) {
15379                    result.add(host);
15380                }
15381            }
15382        }
15383        if (filters != null && filters.size() > 0) {
15384            for (IntentFilter filter : filters) {
15385                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15386                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15387                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15388                    result.addAll(filter.getHostsList());
15389                }
15390            }
15391        }
15392
15393        StringBuilder sb = new StringBuilder(result.size() * 16);
15394        for (String domain : result) {
15395            if (sb.length() > 0) sb.append(" ");
15396            sb.append(domain);
15397        }
15398        return sb.toString();
15399    }
15400
15401    // ------- apps on sdcard specific code -------
15402    static final boolean DEBUG_SD_INSTALL = false;
15403
15404    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15405
15406    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15407
15408    private boolean mMediaMounted = false;
15409
15410    static String getEncryptKey() {
15411        try {
15412            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15413                    SD_ENCRYPTION_KEYSTORE_NAME);
15414            if (sdEncKey == null) {
15415                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15416                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15417                if (sdEncKey == null) {
15418                    Slog.e(TAG, "Failed to create encryption keys");
15419                    return null;
15420                }
15421            }
15422            return sdEncKey;
15423        } catch (NoSuchAlgorithmException nsae) {
15424            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15425            return null;
15426        } catch (IOException ioe) {
15427            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15428            return null;
15429        }
15430    }
15431
15432    /*
15433     * Update media status on PackageManager.
15434     */
15435    @Override
15436    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15437        int callingUid = Binder.getCallingUid();
15438        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15439            throw new SecurityException("Media status can only be updated by the system");
15440        }
15441        // reader; this apparently protects mMediaMounted, but should probably
15442        // be a different lock in that case.
15443        synchronized (mPackages) {
15444            Log.i(TAG, "Updating external media status from "
15445                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15446                    + (mediaStatus ? "mounted" : "unmounted"));
15447            if (DEBUG_SD_INSTALL)
15448                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15449                        + ", mMediaMounted=" + mMediaMounted);
15450            if (mediaStatus == mMediaMounted) {
15451                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15452                        : 0, -1);
15453                mHandler.sendMessage(msg);
15454                return;
15455            }
15456            mMediaMounted = mediaStatus;
15457        }
15458        // Queue up an async operation since the package installation may take a
15459        // little while.
15460        mHandler.post(new Runnable() {
15461            public void run() {
15462                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15463            }
15464        });
15465    }
15466
15467    /**
15468     * Called by MountService when the initial ASECs to scan are available.
15469     * Should block until all the ASEC containers are finished being scanned.
15470     */
15471    public void scanAvailableAsecs() {
15472        updateExternalMediaStatusInner(true, false, false);
15473        if (mShouldRestoreconData) {
15474            SELinuxMMAC.setRestoreconDone();
15475            mShouldRestoreconData = false;
15476        }
15477    }
15478
15479    /*
15480     * Collect information of applications on external media, map them against
15481     * existing containers and update information based on current mount status.
15482     * Please note that we always have to report status if reportStatus has been
15483     * set to true especially when unloading packages.
15484     */
15485    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15486            boolean externalStorage) {
15487        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15488        int[] uidArr = EmptyArray.INT;
15489
15490        final String[] list = PackageHelper.getSecureContainerList();
15491        if (ArrayUtils.isEmpty(list)) {
15492            Log.i(TAG, "No secure containers found");
15493        } else {
15494            // Process list of secure containers and categorize them
15495            // as active or stale based on their package internal state.
15496
15497            // reader
15498            synchronized (mPackages) {
15499                for (String cid : list) {
15500                    // Leave stages untouched for now; installer service owns them
15501                    if (PackageInstallerService.isStageName(cid)) continue;
15502
15503                    if (DEBUG_SD_INSTALL)
15504                        Log.i(TAG, "Processing container " + cid);
15505                    String pkgName = getAsecPackageName(cid);
15506                    if (pkgName == null) {
15507                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15508                        continue;
15509                    }
15510                    if (DEBUG_SD_INSTALL)
15511                        Log.i(TAG, "Looking for pkg : " + pkgName);
15512
15513                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15514                    if (ps == null) {
15515                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15516                        continue;
15517                    }
15518
15519                    /*
15520                     * Skip packages that are not external if we're unmounting
15521                     * external storage.
15522                     */
15523                    if (externalStorage && !isMounted && !isExternal(ps)) {
15524                        continue;
15525                    }
15526
15527                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15528                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15529                    // The package status is changed only if the code path
15530                    // matches between settings and the container id.
15531                    if (ps.codePathString != null
15532                            && ps.codePathString.startsWith(args.getCodePath())) {
15533                        if (DEBUG_SD_INSTALL) {
15534                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15535                                    + " at code path: " + ps.codePathString);
15536                        }
15537
15538                        // We do have a valid package installed on sdcard
15539                        processCids.put(args, ps.codePathString);
15540                        final int uid = ps.appId;
15541                        if (uid != -1) {
15542                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15543                        }
15544                    } else {
15545                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15546                                + ps.codePathString);
15547                    }
15548                }
15549            }
15550
15551            Arrays.sort(uidArr);
15552        }
15553
15554        // Process packages with valid entries.
15555        if (isMounted) {
15556            if (DEBUG_SD_INSTALL)
15557                Log.i(TAG, "Loading packages");
15558            loadMediaPackages(processCids, uidArr);
15559            startCleaningPackages();
15560            mInstallerService.onSecureContainersAvailable();
15561        } else {
15562            if (DEBUG_SD_INSTALL)
15563                Log.i(TAG, "Unloading packages");
15564            unloadMediaPackages(processCids, uidArr, reportStatus);
15565        }
15566    }
15567
15568    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15569            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15570        final int size = infos.size();
15571        final String[] packageNames = new String[size];
15572        final int[] packageUids = new int[size];
15573        for (int i = 0; i < size; i++) {
15574            final ApplicationInfo info = infos.get(i);
15575            packageNames[i] = info.packageName;
15576            packageUids[i] = info.uid;
15577        }
15578        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15579                finishedReceiver);
15580    }
15581
15582    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15583            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15584        sendResourcesChangedBroadcast(mediaStatus, replacing,
15585                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15586    }
15587
15588    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15589            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15590        int size = pkgList.length;
15591        if (size > 0) {
15592            // Send broadcasts here
15593            Bundle extras = new Bundle();
15594            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15595            if (uidArr != null) {
15596                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15597            }
15598            if (replacing) {
15599                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15600            }
15601            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15602                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15603            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15604        }
15605    }
15606
15607   /*
15608     * Look at potentially valid container ids from processCids If package
15609     * information doesn't match the one on record or package scanning fails,
15610     * the cid is added to list of removeCids. We currently don't delete stale
15611     * containers.
15612     */
15613    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15614        ArrayList<String> pkgList = new ArrayList<String>();
15615        Set<AsecInstallArgs> keys = processCids.keySet();
15616
15617        for (AsecInstallArgs args : keys) {
15618            String codePath = processCids.get(args);
15619            if (DEBUG_SD_INSTALL)
15620                Log.i(TAG, "Loading container : " + args.cid);
15621            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15622            try {
15623                // Make sure there are no container errors first.
15624                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15625                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15626                            + " when installing from sdcard");
15627                    continue;
15628                }
15629                // Check code path here.
15630                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15631                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15632                            + " does not match one in settings " + codePath);
15633                    continue;
15634                }
15635                // Parse package
15636                int parseFlags = mDefParseFlags;
15637                if (args.isExternalAsec()) {
15638                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15639                }
15640                if (args.isFwdLocked()) {
15641                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15642                }
15643
15644                synchronized (mInstallLock) {
15645                    PackageParser.Package pkg = null;
15646                    try {
15647                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15648                    } catch (PackageManagerException e) {
15649                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15650                    }
15651                    // Scan the package
15652                    if (pkg != null) {
15653                        /*
15654                         * TODO why is the lock being held? doPostInstall is
15655                         * called in other places without the lock. This needs
15656                         * to be straightened out.
15657                         */
15658                        // writer
15659                        synchronized (mPackages) {
15660                            retCode = PackageManager.INSTALL_SUCCEEDED;
15661                            pkgList.add(pkg.packageName);
15662                            // Post process args
15663                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15664                                    pkg.applicationInfo.uid);
15665                        }
15666                    } else {
15667                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15668                    }
15669                }
15670
15671            } finally {
15672                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15673                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15674                }
15675            }
15676        }
15677        // writer
15678        synchronized (mPackages) {
15679            // If the platform SDK has changed since the last time we booted,
15680            // we need to re-grant app permission to catch any new ones that
15681            // appear. This is really a hack, and means that apps can in some
15682            // cases get permissions that the user didn't initially explicitly
15683            // allow... it would be nice to have some better way to handle
15684            // this situation.
15685            final VersionInfo ver = mSettings.getExternalVersion();
15686
15687            int updateFlags = UPDATE_PERMISSIONS_ALL;
15688            if (ver.sdkVersion != mSdkVersion) {
15689                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15690                        + mSdkVersion + "; regranting permissions for external");
15691                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15692            }
15693            updatePermissionsLPw(null, null, updateFlags);
15694
15695            // Yay, everything is now upgraded
15696            ver.forceCurrent();
15697
15698            // can downgrade to reader
15699            // Persist settings
15700            mSettings.writeLPr();
15701        }
15702        // Send a broadcast to let everyone know we are done processing
15703        if (pkgList.size() > 0) {
15704            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15705        }
15706    }
15707
15708   /*
15709     * Utility method to unload a list of specified containers
15710     */
15711    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15712        // Just unmount all valid containers.
15713        for (AsecInstallArgs arg : cidArgs) {
15714            synchronized (mInstallLock) {
15715                arg.doPostDeleteLI(false);
15716           }
15717       }
15718   }
15719
15720    /*
15721     * Unload packages mounted on external media. This involves deleting package
15722     * data from internal structures, sending broadcasts about diabled packages,
15723     * gc'ing to free up references, unmounting all secure containers
15724     * corresponding to packages on external media, and posting a
15725     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15726     * that we always have to post this message if status has been requested no
15727     * matter what.
15728     */
15729    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15730            final boolean reportStatus) {
15731        if (DEBUG_SD_INSTALL)
15732            Log.i(TAG, "unloading media packages");
15733        ArrayList<String> pkgList = new ArrayList<String>();
15734        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15735        final Set<AsecInstallArgs> keys = processCids.keySet();
15736        for (AsecInstallArgs args : keys) {
15737            String pkgName = args.getPackageName();
15738            if (DEBUG_SD_INSTALL)
15739                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15740            // Delete package internally
15741            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15742            synchronized (mInstallLock) {
15743                boolean res = deletePackageLI(pkgName, null, false, null, null,
15744                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15745                if (res) {
15746                    pkgList.add(pkgName);
15747                } else {
15748                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15749                    failedList.add(args);
15750                }
15751            }
15752        }
15753
15754        // reader
15755        synchronized (mPackages) {
15756            // We didn't update the settings after removing each package;
15757            // write them now for all packages.
15758            mSettings.writeLPr();
15759        }
15760
15761        // We have to absolutely send UPDATED_MEDIA_STATUS only
15762        // after confirming that all the receivers processed the ordered
15763        // broadcast when packages get disabled, force a gc to clean things up.
15764        // and unload all the containers.
15765        if (pkgList.size() > 0) {
15766            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15767                    new IIntentReceiver.Stub() {
15768                public void performReceive(Intent intent, int resultCode, String data,
15769                        Bundle extras, boolean ordered, boolean sticky,
15770                        int sendingUser) throws RemoteException {
15771                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15772                            reportStatus ? 1 : 0, 1, keys);
15773                    mHandler.sendMessage(msg);
15774                }
15775            });
15776        } else {
15777            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15778                    keys);
15779            mHandler.sendMessage(msg);
15780        }
15781    }
15782
15783    private void loadPrivatePackages(VolumeInfo vol) {
15784        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15785        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15786        synchronized (mInstallLock) {
15787        synchronized (mPackages) {
15788            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15789            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15790            for (PackageSetting ps : packages) {
15791                final PackageParser.Package pkg;
15792                try {
15793                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15794                    loaded.add(pkg.applicationInfo);
15795                } catch (PackageManagerException e) {
15796                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15797                }
15798
15799                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15800                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15801                }
15802            }
15803
15804            int updateFlags = UPDATE_PERMISSIONS_ALL;
15805            if (ver.sdkVersion != mSdkVersion) {
15806                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15807                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15808                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15809            }
15810            updatePermissionsLPw(null, null, updateFlags);
15811
15812            // Yay, everything is now upgraded
15813            ver.forceCurrent();
15814
15815            mSettings.writeLPr();
15816        }
15817        }
15818
15819        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15820        sendResourcesChangedBroadcast(true, false, loaded, null);
15821    }
15822
15823    private void unloadPrivatePackages(VolumeInfo vol) {
15824        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15825        synchronized (mInstallLock) {
15826        synchronized (mPackages) {
15827            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15828            for (PackageSetting ps : packages) {
15829                if (ps.pkg == null) continue;
15830
15831                final ApplicationInfo info = ps.pkg.applicationInfo;
15832                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15833                if (deletePackageLI(ps.name, null, false, null, null,
15834                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15835                    unloaded.add(info);
15836                } else {
15837                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15838                }
15839            }
15840
15841            mSettings.writeLPr();
15842        }
15843        }
15844
15845        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15846        sendResourcesChangedBroadcast(false, false, unloaded, null);
15847    }
15848
15849    /**
15850     * Examine all users present on given mounted volume, and destroy data
15851     * belonging to users that are no longer valid, or whose user ID has been
15852     * recycled.
15853     */
15854    private void reconcileUsers(String volumeUuid) {
15855        final File[] files = FileUtils
15856                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15857        for (File file : files) {
15858            if (!file.isDirectory()) continue;
15859
15860            final int userId;
15861            final UserInfo info;
15862            try {
15863                userId = Integer.parseInt(file.getName());
15864                info = sUserManager.getUserInfo(userId);
15865            } catch (NumberFormatException e) {
15866                Slog.w(TAG, "Invalid user directory " + file);
15867                continue;
15868            }
15869
15870            boolean destroyUser = false;
15871            if (info == null) {
15872                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15873                        + " because no matching user was found");
15874                destroyUser = true;
15875            } else {
15876                try {
15877                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15878                } catch (IOException e) {
15879                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15880                            + " because we failed to enforce serial number: " + e);
15881                    destroyUser = true;
15882                }
15883            }
15884
15885            if (destroyUser) {
15886                synchronized (mInstallLock) {
15887                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15888                }
15889            }
15890        }
15891
15892        final UserManager um = mContext.getSystemService(UserManager.class);
15893        for (UserInfo user : um.getUsers()) {
15894            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15895            if (userDir.exists()) continue;
15896
15897            try {
15898                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15899                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15900            } catch (IOException e) {
15901                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15902            }
15903        }
15904    }
15905
15906    /**
15907     * Examine all apps present on given mounted volume, and destroy apps that
15908     * aren't expected, either due to uninstallation or reinstallation on
15909     * another volume.
15910     */
15911    private void reconcileApps(String volumeUuid) {
15912        final File[] files = FileUtils
15913                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15914        for (File file : files) {
15915            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15916                    && !PackageInstallerService.isStageName(file.getName());
15917            if (!isPackage) {
15918                // Ignore entries which are not packages
15919                continue;
15920            }
15921
15922            boolean destroyApp = false;
15923            String packageName = null;
15924            try {
15925                final PackageLite pkg = PackageParser.parsePackageLite(file,
15926                        PackageParser.PARSE_MUST_BE_APK);
15927                packageName = pkg.packageName;
15928
15929                synchronized (mPackages) {
15930                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15931                    if (ps == null) {
15932                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15933                                + volumeUuid + " because we found no install record");
15934                        destroyApp = true;
15935                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15936                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15937                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15938                        destroyApp = true;
15939                    }
15940                }
15941
15942            } catch (PackageParserException e) {
15943                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15944                destroyApp = true;
15945            }
15946
15947            if (destroyApp) {
15948                synchronized (mInstallLock) {
15949                    if (packageName != null) {
15950                        removeDataDirsLI(volumeUuid, packageName);
15951                    }
15952                    if (file.isDirectory()) {
15953                        mInstaller.rmPackageDir(file.getAbsolutePath());
15954                    } else {
15955                        file.delete();
15956                    }
15957                }
15958            }
15959        }
15960    }
15961
15962    private void unfreezePackage(String packageName) {
15963        synchronized (mPackages) {
15964            final PackageSetting ps = mSettings.mPackages.get(packageName);
15965            if (ps != null) {
15966                ps.frozen = false;
15967            }
15968        }
15969    }
15970
15971    @Override
15972    public int movePackage(final String packageName, final String volumeUuid) {
15973        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15974
15975        final int moveId = mNextMoveId.getAndIncrement();
15976        try {
15977            movePackageInternal(packageName, volumeUuid, moveId);
15978        } catch (PackageManagerException e) {
15979            Slog.w(TAG, "Failed to move " + packageName, e);
15980            mMoveCallbacks.notifyStatusChanged(moveId,
15981                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15982        }
15983        return moveId;
15984    }
15985
15986    private void movePackageInternal(final String packageName, final String volumeUuid,
15987            final int moveId) throws PackageManagerException {
15988        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15989        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15990        final PackageManager pm = mContext.getPackageManager();
15991
15992        final boolean currentAsec;
15993        final String currentVolumeUuid;
15994        final File codeFile;
15995        final String installerPackageName;
15996        final String packageAbiOverride;
15997        final int appId;
15998        final String seinfo;
15999        final String label;
16000
16001        // reader
16002        synchronized (mPackages) {
16003            final PackageParser.Package pkg = mPackages.get(packageName);
16004            final PackageSetting ps = mSettings.mPackages.get(packageName);
16005            if (pkg == null || ps == null) {
16006                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16007            }
16008
16009            if (pkg.applicationInfo.isSystemApp()) {
16010                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16011                        "Cannot move system application");
16012            }
16013
16014            if (pkg.applicationInfo.isExternalAsec()) {
16015                currentAsec = true;
16016                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16017            } else if (pkg.applicationInfo.isForwardLocked()) {
16018                currentAsec = true;
16019                currentVolumeUuid = "forward_locked";
16020            } else {
16021                currentAsec = false;
16022                currentVolumeUuid = ps.volumeUuid;
16023
16024                final File probe = new File(pkg.codePath);
16025                final File probeOat = new File(probe, "oat");
16026                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16027                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16028                            "Move only supported for modern cluster style installs");
16029                }
16030            }
16031
16032            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16033                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16034                        "Package already moved to " + volumeUuid);
16035            }
16036
16037            if (ps.frozen) {
16038                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16039                        "Failed to move already frozen package");
16040            }
16041            ps.frozen = true;
16042
16043            codeFile = new File(pkg.codePath);
16044            installerPackageName = ps.installerPackageName;
16045            packageAbiOverride = ps.cpuAbiOverrideString;
16046            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16047            seinfo = pkg.applicationInfo.seinfo;
16048            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16049        }
16050
16051        // Now that we're guarded by frozen state, kill app during move
16052        final long token = Binder.clearCallingIdentity();
16053        try {
16054            killApplication(packageName, appId, "move pkg");
16055        } finally {
16056            Binder.restoreCallingIdentity(token);
16057        }
16058
16059        final Bundle extras = new Bundle();
16060        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16061        extras.putString(Intent.EXTRA_TITLE, label);
16062        mMoveCallbacks.notifyCreated(moveId, extras);
16063
16064        int installFlags;
16065        final boolean moveCompleteApp;
16066        final File measurePath;
16067
16068        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16069            installFlags = INSTALL_INTERNAL;
16070            moveCompleteApp = !currentAsec;
16071            measurePath = Environment.getDataAppDirectory(volumeUuid);
16072        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16073            installFlags = INSTALL_EXTERNAL;
16074            moveCompleteApp = false;
16075            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16076        } else {
16077            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16078            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16079                    || !volume.isMountedWritable()) {
16080                unfreezePackage(packageName);
16081                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16082                        "Move location not mounted private volume");
16083            }
16084
16085            Preconditions.checkState(!currentAsec);
16086
16087            installFlags = INSTALL_INTERNAL;
16088            moveCompleteApp = true;
16089            measurePath = Environment.getDataAppDirectory(volumeUuid);
16090        }
16091
16092        final PackageStats stats = new PackageStats(null, -1);
16093        synchronized (mInstaller) {
16094            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16095                unfreezePackage(packageName);
16096                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16097                        "Failed to measure package size");
16098            }
16099        }
16100
16101        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16102                + stats.dataSize);
16103
16104        final long startFreeBytes = measurePath.getFreeSpace();
16105        final long sizeBytes;
16106        if (moveCompleteApp) {
16107            sizeBytes = stats.codeSize + stats.dataSize;
16108        } else {
16109            sizeBytes = stats.codeSize;
16110        }
16111
16112        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16113            unfreezePackage(packageName);
16114            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16115                    "Not enough free space to move");
16116        }
16117
16118        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16119
16120        final CountDownLatch installedLatch = new CountDownLatch(1);
16121        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16122            @Override
16123            public void onUserActionRequired(Intent intent) throws RemoteException {
16124                throw new IllegalStateException();
16125            }
16126
16127            @Override
16128            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16129                    Bundle extras) throws RemoteException {
16130                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16131                        + PackageManager.installStatusToString(returnCode, msg));
16132
16133                installedLatch.countDown();
16134
16135                // Regardless of success or failure of the move operation,
16136                // always unfreeze the package
16137                unfreezePackage(packageName);
16138
16139                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16140                switch (status) {
16141                    case PackageInstaller.STATUS_SUCCESS:
16142                        mMoveCallbacks.notifyStatusChanged(moveId,
16143                                PackageManager.MOVE_SUCCEEDED);
16144                        break;
16145                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16146                        mMoveCallbacks.notifyStatusChanged(moveId,
16147                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16148                        break;
16149                    default:
16150                        mMoveCallbacks.notifyStatusChanged(moveId,
16151                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16152                        break;
16153                }
16154            }
16155        };
16156
16157        final MoveInfo move;
16158        if (moveCompleteApp) {
16159            // Kick off a thread to report progress estimates
16160            new Thread() {
16161                @Override
16162                public void run() {
16163                    while (true) {
16164                        try {
16165                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16166                                break;
16167                            }
16168                        } catch (InterruptedException ignored) {
16169                        }
16170
16171                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16172                        final int progress = 10 + (int) MathUtils.constrain(
16173                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16174                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16175                    }
16176                }
16177            }.start();
16178
16179            final String dataAppName = codeFile.getName();
16180            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16181                    dataAppName, appId, seinfo);
16182        } else {
16183            move = null;
16184        }
16185
16186        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16187
16188        final Message msg = mHandler.obtainMessage(INIT_COPY);
16189        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16190        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16191                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16192        mHandler.sendMessage(msg);
16193    }
16194
16195    @Override
16196    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16197        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16198
16199        final int realMoveId = mNextMoveId.getAndIncrement();
16200        final Bundle extras = new Bundle();
16201        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16202        mMoveCallbacks.notifyCreated(realMoveId, extras);
16203
16204        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16205            @Override
16206            public void onCreated(int moveId, Bundle extras) {
16207                // Ignored
16208            }
16209
16210            @Override
16211            public void onStatusChanged(int moveId, int status, long estMillis) {
16212                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16213            }
16214        };
16215
16216        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16217        storage.setPrimaryStorageUuid(volumeUuid, callback);
16218        return realMoveId;
16219    }
16220
16221    @Override
16222    public int getMoveStatus(int moveId) {
16223        mContext.enforceCallingOrSelfPermission(
16224                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16225        return mMoveCallbacks.mLastStatus.get(moveId);
16226    }
16227
16228    @Override
16229    public void registerMoveCallback(IPackageMoveObserver callback) {
16230        mContext.enforceCallingOrSelfPermission(
16231                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16232        mMoveCallbacks.register(callback);
16233    }
16234
16235    @Override
16236    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16237        mContext.enforceCallingOrSelfPermission(
16238                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16239        mMoveCallbacks.unregister(callback);
16240    }
16241
16242    @Override
16243    public boolean setInstallLocation(int loc) {
16244        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16245                null);
16246        if (getInstallLocation() == loc) {
16247            return true;
16248        }
16249        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16250                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16251            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16252                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16253            return true;
16254        }
16255        return false;
16256   }
16257
16258    @Override
16259    public int getInstallLocation() {
16260        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16261                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16262                PackageHelper.APP_INSTALL_AUTO);
16263    }
16264
16265    /** Called by UserManagerService */
16266    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16267        mDirtyUsers.remove(userHandle);
16268        mSettings.removeUserLPw(userHandle);
16269        mPendingBroadcasts.remove(userHandle);
16270        if (mInstaller != null) {
16271            // Technically, we shouldn't be doing this with the package lock
16272            // held.  However, this is very rare, and there is already so much
16273            // other disk I/O going on, that we'll let it slide for now.
16274            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16275            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16276                final String volumeUuid = vol.getFsUuid();
16277                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16278                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16279            }
16280        }
16281        mUserNeedsBadging.delete(userHandle);
16282        removeUnusedPackagesLILPw(userManager, userHandle);
16283    }
16284
16285    /**
16286     * We're removing userHandle and would like to remove any downloaded packages
16287     * that are no longer in use by any other user.
16288     * @param userHandle the user being removed
16289     */
16290    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16291        final boolean DEBUG_CLEAN_APKS = false;
16292        int [] users = userManager.getUserIdsLPr();
16293        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16294        while (psit.hasNext()) {
16295            PackageSetting ps = psit.next();
16296            if (ps.pkg == null) {
16297                continue;
16298            }
16299            final String packageName = ps.pkg.packageName;
16300            // Skip over if system app
16301            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16302                continue;
16303            }
16304            if (DEBUG_CLEAN_APKS) {
16305                Slog.i(TAG, "Checking package " + packageName);
16306            }
16307            boolean keep = false;
16308            for (int i = 0; i < users.length; i++) {
16309                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16310                    keep = true;
16311                    if (DEBUG_CLEAN_APKS) {
16312                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16313                                + users[i]);
16314                    }
16315                    break;
16316                }
16317            }
16318            if (!keep) {
16319                if (DEBUG_CLEAN_APKS) {
16320                    Slog.i(TAG, "  Removing package " + packageName);
16321                }
16322                mHandler.post(new Runnable() {
16323                    public void run() {
16324                        deletePackageX(packageName, userHandle, 0);
16325                    } //end run
16326                });
16327            }
16328        }
16329    }
16330
16331    /** Called by UserManagerService */
16332    void createNewUserLILPw(int userHandle) {
16333        if (mInstaller != null) {
16334            mInstaller.createUserConfig(userHandle);
16335            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16336            applyFactoryDefaultBrowserLPw(userHandle);
16337            primeDomainVerificationsLPw(userHandle);
16338        }
16339    }
16340
16341    void newUserCreated(final int userHandle) {
16342        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16343    }
16344
16345    @Override
16346    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16347        mContext.enforceCallingOrSelfPermission(
16348                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16349                "Only package verification agents can read the verifier device identity");
16350
16351        synchronized (mPackages) {
16352            return mSettings.getVerifierDeviceIdentityLPw();
16353        }
16354    }
16355
16356    @Override
16357    public void setPermissionEnforced(String permission, boolean enforced) {
16358        // TODO: Now that we no longer change GID for storage, this should to away.
16359        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16360                "setPermissionEnforced");
16361        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16362            synchronized (mPackages) {
16363                if (mSettings.mReadExternalStorageEnforced == null
16364                        || mSettings.mReadExternalStorageEnforced != enforced) {
16365                    mSettings.mReadExternalStorageEnforced = enforced;
16366                    mSettings.writeLPr();
16367                }
16368            }
16369            // kill any non-foreground processes so we restart them and
16370            // grant/revoke the GID.
16371            final IActivityManager am = ActivityManagerNative.getDefault();
16372            if (am != null) {
16373                final long token = Binder.clearCallingIdentity();
16374                try {
16375                    am.killProcessesBelowForeground("setPermissionEnforcement");
16376                } catch (RemoteException e) {
16377                } finally {
16378                    Binder.restoreCallingIdentity(token);
16379                }
16380            }
16381        } else {
16382            throw new IllegalArgumentException("No selective enforcement for " + permission);
16383        }
16384    }
16385
16386    @Override
16387    @Deprecated
16388    public boolean isPermissionEnforced(String permission) {
16389        return true;
16390    }
16391
16392    @Override
16393    public boolean isStorageLow() {
16394        final long token = Binder.clearCallingIdentity();
16395        try {
16396            final DeviceStorageMonitorInternal
16397                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16398            if (dsm != null) {
16399                return dsm.isMemoryLow();
16400            } else {
16401                return false;
16402            }
16403        } finally {
16404            Binder.restoreCallingIdentity(token);
16405        }
16406    }
16407
16408    @Override
16409    public IPackageInstaller getPackageInstaller() {
16410        return mInstallerService;
16411    }
16412
16413    private boolean userNeedsBadging(int userId) {
16414        int index = mUserNeedsBadging.indexOfKey(userId);
16415        if (index < 0) {
16416            final UserInfo userInfo;
16417            final long token = Binder.clearCallingIdentity();
16418            try {
16419                userInfo = sUserManager.getUserInfo(userId);
16420            } finally {
16421                Binder.restoreCallingIdentity(token);
16422            }
16423            final boolean b;
16424            if (userInfo != null && userInfo.isManagedProfile()) {
16425                b = true;
16426            } else {
16427                b = false;
16428            }
16429            mUserNeedsBadging.put(userId, b);
16430            return b;
16431        }
16432        return mUserNeedsBadging.valueAt(index);
16433    }
16434
16435    @Override
16436    public KeySet getKeySetByAlias(String packageName, String alias) {
16437        if (packageName == null || alias == null) {
16438            return null;
16439        }
16440        synchronized(mPackages) {
16441            final PackageParser.Package pkg = mPackages.get(packageName);
16442            if (pkg == null) {
16443                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16444                throw new IllegalArgumentException("Unknown package: " + packageName);
16445            }
16446            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16447            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16448        }
16449    }
16450
16451    @Override
16452    public KeySet getSigningKeySet(String packageName) {
16453        if (packageName == null) {
16454            return null;
16455        }
16456        synchronized(mPackages) {
16457            final PackageParser.Package pkg = mPackages.get(packageName);
16458            if (pkg == null) {
16459                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16460                throw new IllegalArgumentException("Unknown package: " + packageName);
16461            }
16462            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16463                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16464                throw new SecurityException("May not access signing KeySet of other apps.");
16465            }
16466            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16467            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16468        }
16469    }
16470
16471    @Override
16472    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16473        if (packageName == null || ks == null) {
16474            return false;
16475        }
16476        synchronized(mPackages) {
16477            final PackageParser.Package pkg = mPackages.get(packageName);
16478            if (pkg == null) {
16479                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16480                throw new IllegalArgumentException("Unknown package: " + packageName);
16481            }
16482            IBinder ksh = ks.getToken();
16483            if (ksh instanceof KeySetHandle) {
16484                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16485                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16486            }
16487            return false;
16488        }
16489    }
16490
16491    @Override
16492    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16493        if (packageName == null || ks == null) {
16494            return false;
16495        }
16496        synchronized(mPackages) {
16497            final PackageParser.Package pkg = mPackages.get(packageName);
16498            if (pkg == null) {
16499                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16500                throw new IllegalArgumentException("Unknown package: " + packageName);
16501            }
16502            IBinder ksh = ks.getToken();
16503            if (ksh instanceof KeySetHandle) {
16504                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16505                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16506            }
16507            return false;
16508        }
16509    }
16510
16511    public void getUsageStatsIfNoPackageUsageInfo() {
16512        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16513            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16514            if (usm == null) {
16515                throw new IllegalStateException("UsageStatsManager must be initialized");
16516            }
16517            long now = System.currentTimeMillis();
16518            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16519            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16520                String packageName = entry.getKey();
16521                PackageParser.Package pkg = mPackages.get(packageName);
16522                if (pkg == null) {
16523                    continue;
16524                }
16525                UsageStats usage = entry.getValue();
16526                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16527                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16528            }
16529        }
16530    }
16531
16532    /**
16533     * Check and throw if the given before/after packages would be considered a
16534     * downgrade.
16535     */
16536    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16537            throws PackageManagerException {
16538        if (after.versionCode < before.mVersionCode) {
16539            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16540                    "Update version code " + after.versionCode + " is older than current "
16541                    + before.mVersionCode);
16542        } else if (after.versionCode == before.mVersionCode) {
16543            if (after.baseRevisionCode < before.baseRevisionCode) {
16544                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16545                        "Update base revision code " + after.baseRevisionCode
16546                        + " is older than current " + before.baseRevisionCode);
16547            }
16548
16549            if (!ArrayUtils.isEmpty(after.splitNames)) {
16550                for (int i = 0; i < after.splitNames.length; i++) {
16551                    final String splitName = after.splitNames[i];
16552                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16553                    if (j != -1) {
16554                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16555                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16556                                    "Update split " + splitName + " revision code "
16557                                    + after.splitRevisionCodes[i] + " is older than current "
16558                                    + before.splitRevisionCodes[j]);
16559                        }
16560                    }
16561                }
16562            }
16563        }
16564    }
16565
16566    private static class MoveCallbacks extends Handler {
16567        private static final int MSG_CREATED = 1;
16568        private static final int MSG_STATUS_CHANGED = 2;
16569
16570        private final RemoteCallbackList<IPackageMoveObserver>
16571                mCallbacks = new RemoteCallbackList<>();
16572
16573        private final SparseIntArray mLastStatus = new SparseIntArray();
16574
16575        public MoveCallbacks(Looper looper) {
16576            super(looper);
16577        }
16578
16579        public void register(IPackageMoveObserver callback) {
16580            mCallbacks.register(callback);
16581        }
16582
16583        public void unregister(IPackageMoveObserver callback) {
16584            mCallbacks.unregister(callback);
16585        }
16586
16587        @Override
16588        public void handleMessage(Message msg) {
16589            final SomeArgs args = (SomeArgs) msg.obj;
16590            final int n = mCallbacks.beginBroadcast();
16591            for (int i = 0; i < n; i++) {
16592                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16593                try {
16594                    invokeCallback(callback, msg.what, args);
16595                } catch (RemoteException ignored) {
16596                }
16597            }
16598            mCallbacks.finishBroadcast();
16599            args.recycle();
16600        }
16601
16602        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16603                throws RemoteException {
16604            switch (what) {
16605                case MSG_CREATED: {
16606                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16607                    break;
16608                }
16609                case MSG_STATUS_CHANGED: {
16610                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16611                    break;
16612                }
16613            }
16614        }
16615
16616        private void notifyCreated(int moveId, Bundle extras) {
16617            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16618
16619            final SomeArgs args = SomeArgs.obtain();
16620            args.argi1 = moveId;
16621            args.arg2 = extras;
16622            obtainMessage(MSG_CREATED, args).sendToTarget();
16623        }
16624
16625        private void notifyStatusChanged(int moveId, int status) {
16626            notifyStatusChanged(moveId, status, -1);
16627        }
16628
16629        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16630            Slog.v(TAG, "Move " + moveId + " status " + status);
16631
16632            final SomeArgs args = SomeArgs.obtain();
16633            args.argi1 = moveId;
16634            args.argi2 = status;
16635            args.arg3 = estMillis;
16636            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16637
16638            synchronized (mLastStatus) {
16639                mLastStatus.put(moveId, status);
16640            }
16641        }
16642    }
16643
16644    private final class OnPermissionChangeListeners extends Handler {
16645        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16646
16647        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16648                new RemoteCallbackList<>();
16649
16650        public OnPermissionChangeListeners(Looper looper) {
16651            super(looper);
16652        }
16653
16654        @Override
16655        public void handleMessage(Message msg) {
16656            switch (msg.what) {
16657                case MSG_ON_PERMISSIONS_CHANGED: {
16658                    final int uid = msg.arg1;
16659                    handleOnPermissionsChanged(uid);
16660                } break;
16661            }
16662        }
16663
16664        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16665            mPermissionListeners.register(listener);
16666
16667        }
16668
16669        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16670            mPermissionListeners.unregister(listener);
16671        }
16672
16673        public void onPermissionsChanged(int uid) {
16674            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16675                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16676            }
16677        }
16678
16679        private void handleOnPermissionsChanged(int uid) {
16680            final int count = mPermissionListeners.beginBroadcast();
16681            try {
16682                for (int i = 0; i < count; i++) {
16683                    IOnPermissionsChangeListener callback = mPermissionListeners
16684                            .getBroadcastItem(i);
16685                    try {
16686                        callback.onPermissionsChanged(uid);
16687                    } catch (RemoteException e) {
16688                        Log.e(TAG, "Permission listener is dead", e);
16689                    }
16690                }
16691            } finally {
16692                mPermissionListeners.finishBroadcast();
16693            }
16694        }
16695    }
16696
16697    private class PackageManagerInternalImpl extends PackageManagerInternal {
16698        @Override
16699        public void setLocationPackagesProvider(PackagesProvider provider) {
16700            synchronized (mPackages) {
16701                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16702            }
16703        }
16704
16705        @Override
16706        public void setImePackagesProvider(PackagesProvider provider) {
16707            synchronized (mPackages) {
16708                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16709            }
16710        }
16711
16712        @Override
16713        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16714            synchronized (mPackages) {
16715                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16716            }
16717        }
16718
16719        @Override
16720        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16721            synchronized (mPackages) {
16722                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16723            }
16724        }
16725
16726        @Override
16727        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16728            synchronized (mPackages) {
16729                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16730            }
16731        }
16732
16733        @Override
16734        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16735            synchronized (mPackages) {
16736                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16737            }
16738        }
16739
16740        @Override
16741        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16742            synchronized (mPackages) {
16743                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16744            }
16745        }
16746
16747        @Override
16748        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16749            synchronized (mPackages) {
16750                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16751                        packageName, userId);
16752            }
16753        }
16754
16755        @Override
16756        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16757            synchronized (mPackages) {
16758                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16759                        packageName, userId);
16760            }
16761        }
16762        @Override
16763        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16764            synchronized (mPackages) {
16765                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16766                        packageName, userId);
16767            }
16768        }
16769    }
16770
16771    @Override
16772    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16773        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16774        synchronized (mPackages) {
16775            final long identity = Binder.clearCallingIdentity();
16776            try {
16777                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16778                        packageNames, userId);
16779            } finally {
16780                Binder.restoreCallingIdentity(identity);
16781            }
16782        }
16783    }
16784
16785    private static void enforceSystemOrPhoneCaller(String tag) {
16786        int callingUid = Binder.getCallingUid();
16787        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16788            throw new SecurityException(
16789                    "Cannot call " + tag + " from UID " + callingUid);
16790        }
16791    }
16792}
16793