PackageManagerService.java revision b4fdb933cb7d48fd2b298a84e209cd7288f8a2c5
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
87
88import android.Manifest;
89import android.app.ActivityManager;
90import android.app.ActivityManagerNative;
91import android.app.AppGlobals;
92import android.app.IActivityManager;
93import android.app.admin.IDevicePolicyManager;
94import android.app.backup.IBackupManager;
95import android.app.usage.UsageStats;
96import android.app.usage.UsageStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.AppsQueryHelper;
109import android.content.pm.FeatureInfo;
110import android.content.pm.IOnPermissionsChangeListener;
111import android.content.pm.IPackageDataObserver;
112import android.content.pm.IPackageDeleteObserver;
113import android.content.pm.IPackageDeleteObserver2;
114import android.content.pm.IPackageInstallObserver2;
115import android.content.pm.IPackageInstaller;
116import android.content.pm.IPackageManager;
117import android.content.pm.IPackageMoveObserver;
118import android.content.pm.IPackageStatsObserver;
119import android.content.pm.InstrumentationInfo;
120import android.content.pm.IntentFilterVerificationInfo;
121import android.content.pm.KeySet;
122import android.content.pm.ManifestDigest;
123import android.content.pm.PackageCleanItem;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageInfoLite;
126import android.content.pm.PackageInstaller;
127import android.content.pm.PackageManager;
128import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
129import android.content.pm.PackageManagerInternal;
130import android.content.pm.PackageParser;
131import android.content.pm.PackageParser.ActivityIntentInfo;
132import android.content.pm.PackageParser.PackageLite;
133import android.content.pm.PackageParser.PackageParserException;
134import android.content.pm.PackageStats;
135import android.content.pm.PackageUserState;
136import android.content.pm.ParceledListSlice;
137import android.content.pm.PermissionGroupInfo;
138import android.content.pm.PermissionInfo;
139import android.content.pm.ProviderInfo;
140import android.content.pm.ResolveInfo;
141import android.content.pm.ServiceInfo;
142import android.content.pm.Signature;
143import android.content.pm.UserInfo;
144import android.content.pm.VerificationParams;
145import android.content.pm.VerifierDeviceIdentity;
146import android.content.pm.VerifierInfo;
147import android.content.res.Resources;
148import android.hardware.display.DisplayManager;
149import android.net.Uri;
150import android.os.Debug;
151import android.os.Binder;
152import android.os.Build;
153import android.os.Bundle;
154import android.os.Environment;
155import android.os.Environment.UserEnvironment;
156import android.os.FileUtils;
157import android.os.Handler;
158import android.os.IBinder;
159import android.os.Looper;
160import android.os.Message;
161import android.os.Parcel;
162import android.os.ParcelFileDescriptor;
163import android.os.Process;
164import android.os.RemoteCallbackList;
165import android.os.RemoteException;
166import android.os.ResultReceiver;
167import android.os.SELinux;
168import android.os.ServiceManager;
169import android.os.SystemClock;
170import android.os.SystemProperties;
171import android.os.Trace;
172import android.os.UserHandle;
173import android.os.UserManager;
174import android.os.storage.IMountService;
175import android.os.storage.MountServiceInternal;
176import android.os.storage.StorageEventListener;
177import android.os.storage.StorageManager;
178import android.os.storage.VolumeInfo;
179import android.os.storage.VolumeRecord;
180import android.security.KeyStore;
181import android.security.SystemKeyStore;
182import android.system.ErrnoException;
183import android.system.Os;
184import android.system.StructStat;
185import android.text.TextUtils;
186import android.text.format.DateUtils;
187import android.util.ArrayMap;
188import android.util.ArraySet;
189import android.util.AtomicFile;
190import android.util.DisplayMetrics;
191import android.util.EventLog;
192import android.util.ExceptionUtils;
193import android.util.Log;
194import android.util.LogPrinter;
195import android.util.MathUtils;
196import android.util.PrintStreamPrinter;
197import android.util.Slog;
198import android.util.SparseArray;
199import android.util.SparseBooleanArray;
200import android.util.SparseIntArray;
201import android.util.Xml;
202import android.view.Display;
203
204import dalvik.system.DexFile;
205import dalvik.system.VMRuntime;
206
207import libcore.io.IoUtils;
208import libcore.util.EmptyArray;
209
210import com.android.internal.R;
211import com.android.internal.annotations.GuardedBy;
212import com.android.internal.app.EphemeralResolveInfo;
213import com.android.internal.app.IMediaContainerService;
214import com.android.internal.app.ResolverActivity;
215import com.android.internal.content.NativeLibraryHelper;
216import com.android.internal.content.PackageHelper;
217import com.android.internal.os.IParcelFileDescriptorFactory;
218import com.android.internal.os.SomeArgs;
219import com.android.internal.os.Zygote;
220import com.android.internal.util.ArrayUtils;
221import com.android.internal.util.FastPrintWriter;
222import com.android.internal.util.FastXmlSerializer;
223import com.android.internal.util.IndentingPrintWriter;
224import com.android.internal.util.Preconditions;
225import com.android.server.EventLogTags;
226import com.android.server.FgThread;
227import com.android.server.IntentResolver;
228import com.android.server.LocalServices;
229import com.android.server.ServiceThread;
230import com.android.server.SystemConfig;
231import com.android.server.Watchdog;
232import com.android.server.pm.PermissionsState.PermissionState;
233import com.android.server.pm.Settings.DatabaseVersion;
234import com.android.server.pm.Settings.VersionInfo;
235import com.android.server.storage.DeviceStorageMonitorInternal;
236
237import org.xmlpull.v1.XmlPullParser;
238import org.xmlpull.v1.XmlPullParserException;
239import org.xmlpull.v1.XmlSerializer;
240
241import java.io.BufferedInputStream;
242import java.io.BufferedOutputStream;
243import java.io.BufferedReader;
244import java.io.ByteArrayInputStream;
245import java.io.ByteArrayOutputStream;
246import java.io.File;
247import java.io.FileDescriptor;
248import java.io.FileNotFoundException;
249import java.io.FileOutputStream;
250import java.io.FileReader;
251import java.io.FilenameFilter;
252import java.io.IOException;
253import java.io.InputStream;
254import java.io.PrintWriter;
255import java.nio.charset.StandardCharsets;
256import java.security.MessageDigest;
257import java.security.NoSuchAlgorithmException;
258import java.security.PublicKey;
259import java.security.cert.CertificateEncodingException;
260import java.security.cert.CertificateException;
261import java.text.SimpleDateFormat;
262import java.util.ArrayList;
263import java.util.Arrays;
264import java.util.Collection;
265import java.util.Collections;
266import java.util.Comparator;
267import java.util.Date;
268import java.util.Iterator;
269import java.util.List;
270import java.util.Map;
271import java.util.Objects;
272import java.util.Set;
273import java.util.concurrent.CountDownLatch;
274import java.util.concurrent.TimeUnit;
275import java.util.concurrent.atomic.AtomicBoolean;
276import java.util.concurrent.atomic.AtomicInteger;
277import java.util.concurrent.atomic.AtomicLong;
278
279/**
280 * Keep track of all those .apks everywhere.
281 *
282 * This is very central to the platform's security; please run the unit
283 * tests whenever making modifications here:
284 *
285runtest -c android.content.pm.PackageManagerTests frameworks-core
286 *
287 * {@hide}
288 */
289public class PackageManagerService extends IPackageManager.Stub {
290    static final String TAG = "PackageManager";
291    static final boolean DEBUG_SETTINGS = false;
292    static final boolean DEBUG_PREFERRED = false;
293    static final boolean DEBUG_UPGRADE = false;
294    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
295    private static final boolean DEBUG_BACKUP = false;
296    private static final boolean DEBUG_INSTALL = false;
297    private static final boolean DEBUG_REMOVE = false;
298    private static final boolean DEBUG_BROADCASTS = false;
299    private static final boolean DEBUG_SHOW_INFO = false;
300    private static final boolean DEBUG_PACKAGE_INFO = false;
301    private static final boolean DEBUG_INTENT_MATCHING = false;
302    private static final boolean DEBUG_PACKAGE_SCANNING = false;
303    private static final boolean DEBUG_VERIFY = false;
304    private static final boolean DEBUG_DEXOPT = false;
305    private static final boolean DEBUG_ABI_SELECTION = false;
306    private static final boolean DEBUG_EPHEMERAL = false;
307
308    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
309
310    private static final int RADIO_UID = Process.PHONE_UID;
311    private static final int LOG_UID = Process.LOG_UID;
312    private static final int NFC_UID = Process.NFC_UID;
313    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
314    private static final int SHELL_UID = Process.SHELL_UID;
315
316    // Cap the size of permission trees that 3rd party apps can define
317    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
318
319    // Suffix used during package installation when copying/moving
320    // package apks to install directory.
321    private static final String INSTALL_PACKAGE_SUFFIX = "-";
322
323    static final int SCAN_NO_DEX = 1<<1;
324    static final int SCAN_FORCE_DEX = 1<<2;
325    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
326    static final int SCAN_NEW_INSTALL = 1<<4;
327    static final int SCAN_NO_PATHS = 1<<5;
328    static final int SCAN_UPDATE_TIME = 1<<6;
329    static final int SCAN_DEFER_DEX = 1<<7;
330    static final int SCAN_BOOTING = 1<<8;
331    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
332    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
333    static final int SCAN_REPLACING = 1<<11;
334    static final int SCAN_REQUIRE_KNOWN = 1<<12;
335    static final int SCAN_MOVE = 1<<13;
336    static final int SCAN_INITIAL = 1<<14;
337
338    static final int REMOVE_CHATTY = 1<<16;
339
340    private static final int[] EMPTY_INT_ARRAY = new int[0];
341
342    /**
343     * Timeout (in milliseconds) after which the watchdog should declare that
344     * our handler thread is wedged.  The usual default for such things is one
345     * minute but we sometimes do very lengthy I/O operations on this thread,
346     * such as installing multi-gigabyte applications, so ours needs to be longer.
347     */
348    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
349
350    /**
351     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
352     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
353     * settings entry if available, otherwise we use the hardcoded default.  If it's been
354     * more than this long since the last fstrim, we force one during the boot sequence.
355     *
356     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
357     * one gets run at the next available charging+idle time.  This final mandatory
358     * no-fstrim check kicks in only of the other scheduling criteria is never met.
359     */
360    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
361
362    /**
363     * Whether verification is enabled by default.
364     */
365    private static final boolean DEFAULT_VERIFY_ENABLE = true;
366
367    /**
368     * The default maximum time to wait for the verification agent to return in
369     * milliseconds.
370     */
371    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
372
373    /**
374     * The default response for package verification timeout.
375     *
376     * This can be either PackageManager.VERIFICATION_ALLOW or
377     * PackageManager.VERIFICATION_REJECT.
378     */
379    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
380
381    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
382
383    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
384            DEFAULT_CONTAINER_PACKAGE,
385            "com.android.defcontainer.DefaultContainerService");
386
387    private static final String KILL_APP_REASON_GIDS_CHANGED =
388            "permission grant or revoke changed gids";
389
390    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
391            "permissions revoked";
392
393    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
394
395    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
396
397    /** Permission grant: not grant the permission. */
398    private static final int GRANT_DENIED = 1;
399
400    /** Permission grant: grant the permission as an install permission. */
401    private static final int GRANT_INSTALL = 2;
402
403    /** Permission grant: grant the permission as an install permission for a legacy app. */
404    private static final int GRANT_INSTALL_LEGACY = 3;
405
406    /** Permission grant: grant the permission as a runtime one. */
407    private static final int GRANT_RUNTIME = 4;
408
409    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
410    private static final int GRANT_UPGRADE = 5;
411
412    /** Canonical intent used to identify what counts as a "web browser" app */
413    private static final Intent sBrowserIntent;
414    static {
415        sBrowserIntent = new Intent();
416        sBrowserIntent.setAction(Intent.ACTION_VIEW);
417        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
418        sBrowserIntent.setData(Uri.parse("http:"));
419    }
420
421    final ServiceThread mHandlerThread;
422
423    final PackageHandler mHandler;
424
425    /**
426     * Messages for {@link #mHandler} that need to wait for system ready before
427     * being dispatched.
428     */
429    private ArrayList<Message> mPostSystemReadyMessages;
430
431    final int mSdkVersion = Build.VERSION.SDK_INT;
432
433    final Context mContext;
434    final boolean mFactoryTest;
435    final boolean mOnlyCore;
436    final DisplayMetrics mMetrics;
437    final int mDefParseFlags;
438    final String[] mSeparateProcesses;
439    final boolean mIsUpgrade;
440
441    // This is where all application persistent data goes.
442    final File mAppDataDir;
443
444    // This is where all application persistent data goes for secondary users.
445    final File mUserAppDataDir;
446
447    /** The location for ASEC container files on internal storage. */
448    final String mAsecInternalPath;
449
450    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
451    // LOCK HELD.  Can be called with mInstallLock held.
452    @GuardedBy("mInstallLock")
453    final Installer mInstaller;
454
455    /** Directory where installed third-party apps stored */
456    final File mAppInstallDir;
457
458    /**
459     * Directory to which applications installed internally have their
460     * 32 bit native libraries copied.
461     */
462    private File mAppLib32InstallDir;
463
464    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
465    // apps.
466    final File mDrmAppPrivateInstallDir;
467
468    // ----------------------------------------------------------------
469
470    // Lock for state used when installing and doing other long running
471    // operations.  Methods that must be called with this lock held have
472    // the suffix "LI".
473    final Object mInstallLock = new Object();
474
475    // ----------------------------------------------------------------
476
477    // Keys are String (package name), values are Package.  This also serves
478    // as the lock for the global state.  Methods that must be called with
479    // this lock held have the prefix "LP".
480    @GuardedBy("mPackages")
481    final ArrayMap<String, PackageParser.Package> mPackages =
482            new ArrayMap<String, PackageParser.Package>();
483
484    // Tracks available target package names -> overlay package paths.
485    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
486        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
487
488    /**
489     * Tracks new system packages [received in an OTA] that we expect to
490     * find updated user-installed versions. Keys are package name, values
491     * are package location.
492     */
493    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
494
495    /**
496     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
497     */
498    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
499    /**
500     * Whether or not system app permissions should be promoted from install to runtime.
501     */
502    boolean mPromoteSystemApps;
503
504    final Settings mSettings;
505    boolean mRestoredSettings;
506
507    // System configuration read by SystemConfig.
508    final int[] mGlobalGids;
509    final SparseArray<ArraySet<String>> mSystemPermissions;
510    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
511
512    // If mac_permissions.xml was found for seinfo labeling.
513    boolean mFoundPolicyFile;
514
515    // If a recursive restorecon of /data/data/<pkg> is needed.
516    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
517
518    public static final class SharedLibraryEntry {
519        public final String path;
520        public final String apk;
521
522        SharedLibraryEntry(String _path, String _apk) {
523            path = _path;
524            apk = _apk;
525        }
526    }
527
528    // Currently known shared libraries.
529    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
530            new ArrayMap<String, SharedLibraryEntry>();
531
532    // All available activities, for your resolving pleasure.
533    final ActivityIntentResolver mActivities =
534            new ActivityIntentResolver();
535
536    // All available receivers, for your resolving pleasure.
537    final ActivityIntentResolver mReceivers =
538            new ActivityIntentResolver();
539
540    // All available services, for your resolving pleasure.
541    final ServiceIntentResolver mServices = new ServiceIntentResolver();
542
543    // All available providers, for your resolving pleasure.
544    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
545
546    // Mapping from provider base names (first directory in content URI codePath)
547    // to the provider information.
548    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
549            new ArrayMap<String, PackageParser.Provider>();
550
551    // Mapping from instrumentation class names to info about them.
552    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
553            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
554
555    // Mapping from permission names to info about them.
556    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
557            new ArrayMap<String, PackageParser.PermissionGroup>();
558
559    // Packages whose data we have transfered into another package, thus
560    // should no longer exist.
561    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
562
563    // Broadcast actions that are only available to the system.
564    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
565
566    /** List of packages waiting for verification. */
567    final SparseArray<PackageVerificationState> mPendingVerification
568            = new SparseArray<PackageVerificationState>();
569
570    /** Set of packages associated with each app op permission. */
571    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
572
573    final PackageInstallerService mInstallerService;
574
575    private final PackageDexOptimizer mPackageDexOptimizer;
576
577    private AtomicInteger mNextMoveId = new AtomicInteger();
578    private final MoveCallbacks mMoveCallbacks;
579
580    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
581
582    // Cache of users who need badging.
583    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
584
585    /** Token for keys in mPendingVerification. */
586    private int mPendingVerificationToken = 0;
587
588    volatile boolean mSystemReady;
589    volatile boolean mSafeMode;
590    volatile boolean mHasSystemUidErrors;
591
592    ApplicationInfo mAndroidApplication;
593    final ActivityInfo mResolveActivity = new ActivityInfo();
594    final ResolveInfo mResolveInfo = new ResolveInfo();
595    ComponentName mResolveComponentName;
596    PackageParser.Package mPlatformPackage;
597    ComponentName mCustomResolverComponentName;
598
599    boolean mResolverReplaced = false;
600
601    private final ComponentName mIntentFilterVerifierComponent;
602    private int mIntentFilterVerificationToken = 0;
603
604    /** Component that knows whether or not an ephemeral application exists */
605    final ComponentName mEphemeralResolverComponent;
606    /** The service connection to the ephemeral resolver */
607    final EphemeralResolverConnection mEphemeralResolverConnection;
608
609    /** Component used to install ephemeral applications */
610    final ComponentName mEphemeralInstallerComponent;
611    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
612    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
613
614    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
615            = new SparseArray<IntentFilterVerificationState>();
616
617    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
618            new DefaultPermissionGrantPolicy(this);
619
620    private static class IFVerificationParams {
621        PackageParser.Package pkg;
622        boolean replacing;
623        int userId;
624        int verifierUid;
625
626        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
627                int _userId, int _verifierUid) {
628            pkg = _pkg;
629            replacing = _replacing;
630            userId = _userId;
631            replacing = _replacing;
632            verifierUid = _verifierUid;
633        }
634    }
635
636    private interface IntentFilterVerifier<T extends IntentFilter> {
637        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
638                                               T filter, String packageName);
639        void startVerifications(int userId);
640        void receiveVerificationResponse(int verificationId);
641    }
642
643    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
644        private Context mContext;
645        private ComponentName mIntentFilterVerifierComponent;
646        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
647
648        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
649            mContext = context;
650            mIntentFilterVerifierComponent = verifierComponent;
651        }
652
653        private String getDefaultScheme() {
654            return IntentFilter.SCHEME_HTTPS;
655        }
656
657        @Override
658        public void startVerifications(int userId) {
659            // Launch verifications requests
660            int count = mCurrentIntentFilterVerifications.size();
661            for (int n=0; n<count; n++) {
662                int verificationId = mCurrentIntentFilterVerifications.get(n);
663                final IntentFilterVerificationState ivs =
664                        mIntentFilterVerificationStates.get(verificationId);
665
666                String packageName = ivs.getPackageName();
667
668                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
669                final int filterCount = filters.size();
670                ArraySet<String> domainsSet = new ArraySet<>();
671                for (int m=0; m<filterCount; m++) {
672                    PackageParser.ActivityIntentInfo filter = filters.get(m);
673                    domainsSet.addAll(filter.getHostsList());
674                }
675                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
676                synchronized (mPackages) {
677                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
678                            packageName, domainsList) != null) {
679                        scheduleWriteSettingsLocked();
680                    }
681                }
682                sendVerificationRequest(userId, verificationId, ivs);
683            }
684            mCurrentIntentFilterVerifications.clear();
685        }
686
687        private void sendVerificationRequest(int userId, int verificationId,
688                IntentFilterVerificationState ivs) {
689
690            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
691            verificationIntent.putExtra(
692                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
693                    verificationId);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
696                    getDefaultScheme());
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
699                    ivs.getHostsString());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
702                    ivs.getPackageName());
703            verificationIntent.setComponent(mIntentFilterVerifierComponent);
704            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
705
706            UserHandle user = new UserHandle(userId);
707            mContext.sendBroadcastAsUser(verificationIntent, user);
708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
709                    "Sending IntentFilter verification broadcast");
710        }
711
712        public void receiveVerificationResponse(int verificationId) {
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714
715            final boolean verified = ivs.isVerified();
716
717            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
718            final int count = filters.size();
719            if (DEBUG_DOMAIN_VERIFICATION) {
720                Slog.i(TAG, "Received verification response " + verificationId
721                        + " for " + count + " filters, verified=" + verified);
722            }
723            for (int n=0; n<count; n++) {
724                PackageParser.ActivityIntentInfo filter = filters.get(n);
725                filter.setVerified(verified);
726
727                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
728                        + " verified with result:" + verified + " and hosts:"
729                        + ivs.getHostsString());
730            }
731
732            mIntentFilterVerificationStates.remove(verificationId);
733
734            final String packageName = ivs.getPackageName();
735            IntentFilterVerificationInfo ivi = null;
736
737            synchronized (mPackages) {
738                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
739            }
740            if (ivi == null) {
741                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
742                        + verificationId + " packageName:" + packageName);
743                return;
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
746                    "Updating IntentFilterVerificationInfo for package " + packageName
747                            +" verificationId:" + verificationId);
748
749            synchronized (mPackages) {
750                if (verified) {
751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
752                } else {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
754                }
755                scheduleWriteSettingsLocked();
756
757                final int userId = ivs.getUserId();
758                if (userId != UserHandle.USER_ALL) {
759                    final int userStatus =
760                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
761
762                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
763                    boolean needUpdate = false;
764
765                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
766                    // already been set by the User thru the Disambiguation dialog
767                    switch (userStatus) {
768                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
769                            if (verified) {
770                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
771                            } else {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
773                            }
774                            needUpdate = true;
775                            break;
776
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                                needUpdate = true;
781                            }
782                            break;
783
784                        default:
785                            // Nothing to do
786                    }
787
788                    if (needUpdate) {
789                        mSettings.updateIntentFilterVerificationStatusLPw(
790                                packageName, updatedStatus, userId);
791                        scheduleWritePackageRestrictionsLocked(userId);
792                    }
793                }
794            }
795        }
796
797        @Override
798        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
799                    ActivityIntentInfo filter, String packageName) {
800            if (!hasValidDomains(filter)) {
801                return false;
802            }
803            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
804            if (ivs == null) {
805                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
806                        packageName);
807            }
808            if (DEBUG_DOMAIN_VERIFICATION) {
809                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
810            }
811            ivs.addFilter(filter);
812            return true;
813        }
814
815        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
816                int userId, int verificationId, String packageName) {
817            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
818                    verifierUid, userId, packageName);
819            ivs.setPendingState();
820            synchronized (mPackages) {
821                mIntentFilterVerificationStates.append(verificationId, ivs);
822                mCurrentIntentFilterVerifications.add(verificationId);
823            }
824            return ivs;
825        }
826    }
827
828    private static boolean hasValidDomains(ActivityIntentInfo filter) {
829        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
830                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
831                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
832    }
833
834    private IntentFilterVerifier mIntentFilterVerifier;
835
836    // Set of pending broadcasts for aggregating enable/disable of components.
837    static class PendingPackageBroadcasts {
838        // for each user id, a map of <package name -> components within that package>
839        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
840
841        public PendingPackageBroadcasts() {
842            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
843        }
844
845        public ArrayList<String> get(int userId, String packageName) {
846            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
847            return packages.get(packageName);
848        }
849
850        public void put(int userId, String packageName, ArrayList<String> components) {
851            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
852            packages.put(packageName, components);
853        }
854
855        public void remove(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
857            if (packages != null) {
858                packages.remove(packageName);
859            }
860        }
861
862        public void remove(int userId) {
863            mUidMap.remove(userId);
864        }
865
866        public int userIdCount() {
867            return mUidMap.size();
868        }
869
870        public int userIdAt(int n) {
871            return mUidMap.keyAt(n);
872        }
873
874        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
875            return mUidMap.get(userId);
876        }
877
878        public int size() {
879            // total number of pending broadcast entries across all userIds
880            int num = 0;
881            for (int i = 0; i< mUidMap.size(); i++) {
882                num += mUidMap.valueAt(i).size();
883            }
884            return num;
885        }
886
887        public void clear() {
888            mUidMap.clear();
889        }
890
891        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
892            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
893            if (map == null) {
894                map = new ArrayMap<String, ArrayList<String>>();
895                mUidMap.put(userId, map);
896            }
897            return map;
898        }
899    }
900    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
901
902    // Service Connection to remote media container service to copy
903    // package uri's from external media onto secure containers
904    // or internal storage.
905    private IMediaContainerService mContainerService = null;
906
907    static final int SEND_PENDING_BROADCAST = 1;
908    static final int MCS_BOUND = 3;
909    static final int END_COPY = 4;
910    static final int INIT_COPY = 5;
911    static final int MCS_UNBIND = 6;
912    static final int START_CLEANING_PACKAGE = 7;
913    static final int FIND_INSTALL_LOC = 8;
914    static final int POST_INSTALL = 9;
915    static final int MCS_RECONNECT = 10;
916    static final int MCS_GIVE_UP = 11;
917    static final int UPDATED_MEDIA_STATUS = 12;
918    static final int WRITE_SETTINGS = 13;
919    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
920    static final int PACKAGE_VERIFIED = 15;
921    static final int CHECK_PENDING_VERIFICATION = 16;
922    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
923    static final int INTENT_FILTER_VERIFIED = 18;
924
925    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
926
927    // Delay time in millisecs
928    static final int BROADCAST_DELAY = 10 * 1000;
929
930    static UserManagerService sUserManager;
931
932    // Stores a list of users whose package restrictions file needs to be updated
933    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
934
935    final private DefaultContainerConnection mDefContainerConn =
936            new DefaultContainerConnection();
937    class DefaultContainerConnection implements ServiceConnection {
938        public void onServiceConnected(ComponentName name, IBinder service) {
939            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
940            IMediaContainerService imcs =
941                IMediaContainerService.Stub.asInterface(service);
942            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
943        }
944
945        public void onServiceDisconnected(ComponentName name) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
947        }
948    }
949
950    // Recordkeeping of restore-after-install operations that are currently in flight
951    // between the Package Manager and the Backup Manager
952    class PostInstallData {
953        public InstallArgs args;
954        public PackageInstalledInfo res;
955
956        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
957            args = _a;
958            res = _r;
959        }
960    }
961
962    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
963    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
964
965    // XML tags for backup/restore of various bits of state
966    private static final String TAG_PREFERRED_BACKUP = "pa";
967    private static final String TAG_DEFAULT_APPS = "da";
968    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
969
970    final String mRequiredVerifierPackage;
971    final String mRequiredInstallerPackage;
972
973    private final PackageUsage mPackageUsage = new PackageUsage();
974
975    private class PackageUsage {
976        private static final int WRITE_INTERVAL
977            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
978
979        private final Object mFileLock = new Object();
980        private final AtomicLong mLastWritten = new AtomicLong(0);
981        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
982
983        private boolean mIsHistoricalPackageUsageAvailable = true;
984
985        boolean isHistoricalPackageUsageAvailable() {
986            return mIsHistoricalPackageUsageAvailable;
987        }
988
989        void write(boolean force) {
990            if (force) {
991                writeInternal();
992                return;
993            }
994            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
995                && !DEBUG_DEXOPT) {
996                return;
997            }
998            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
999                new Thread("PackageUsage_DiskWriter") {
1000                    @Override
1001                    public void run() {
1002                        try {
1003                            writeInternal();
1004                        } finally {
1005                            mBackgroundWriteRunning.set(false);
1006                        }
1007                    }
1008                }.start();
1009            }
1010        }
1011
1012        private void writeInternal() {
1013            synchronized (mPackages) {
1014                synchronized (mFileLock) {
1015                    AtomicFile file = getFile();
1016                    FileOutputStream f = null;
1017                    try {
1018                        f = file.startWrite();
1019                        BufferedOutputStream out = new BufferedOutputStream(f);
1020                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1021                        StringBuilder sb = new StringBuilder();
1022                        for (PackageParser.Package pkg : mPackages.values()) {
1023                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1024                                continue;
1025                            }
1026                            sb.setLength(0);
1027                            sb.append(pkg.packageName);
1028                            sb.append(' ');
1029                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1030                            sb.append('\n');
1031                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1032                        }
1033                        out.flush();
1034                        file.finishWrite(f);
1035                    } catch (IOException e) {
1036                        if (f != null) {
1037                            file.failWrite(f);
1038                        }
1039                        Log.e(TAG, "Failed to write package usage times", e);
1040                    }
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        void readLP() {
1047            synchronized (mFileLock) {
1048                AtomicFile file = getFile();
1049                BufferedInputStream in = null;
1050                try {
1051                    in = new BufferedInputStream(file.openRead());
1052                    StringBuffer sb = new StringBuffer();
1053                    while (true) {
1054                        String packageName = readToken(in, sb, ' ');
1055                        if (packageName == null) {
1056                            break;
1057                        }
1058                        String timeInMillisString = readToken(in, sb, '\n');
1059                        if (timeInMillisString == null) {
1060                            throw new IOException("Failed to find last usage time for package "
1061                                                  + packageName);
1062                        }
1063                        PackageParser.Package pkg = mPackages.get(packageName);
1064                        if (pkg == null) {
1065                            continue;
1066                        }
1067                        long timeInMillis;
1068                        try {
1069                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1070                        } catch (NumberFormatException e) {
1071                            throw new IOException("Failed to parse " + timeInMillisString
1072                                                  + " as a long.", e);
1073                        }
1074                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1075                    }
1076                } catch (FileNotFoundException expected) {
1077                    mIsHistoricalPackageUsageAvailable = false;
1078                } catch (IOException e) {
1079                    Log.w(TAG, "Failed to read package usage times", e);
1080                } finally {
1081                    IoUtils.closeQuietly(in);
1082                }
1083            }
1084            mLastWritten.set(SystemClock.elapsedRealtime());
1085        }
1086
1087        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1088                throws IOException {
1089            sb.setLength(0);
1090            while (true) {
1091                int ch = in.read();
1092                if (ch == -1) {
1093                    if (sb.length() == 0) {
1094                        return null;
1095                    }
1096                    throw new IOException("Unexpected EOF");
1097                }
1098                if (ch == endOfToken) {
1099                    return sb.toString();
1100                }
1101                sb.append((char)ch);
1102            }
1103        }
1104
1105        private AtomicFile getFile() {
1106            File dataDir = Environment.getDataDirectory();
1107            File systemDir = new File(dataDir, "system");
1108            File fname = new File(systemDir, "package-usage.list");
1109            return new AtomicFile(fname);
1110        }
1111    }
1112
1113    class PackageHandler extends Handler {
1114        private boolean mBound = false;
1115        final ArrayList<HandlerParams> mPendingInstalls =
1116            new ArrayList<HandlerParams>();
1117
1118        private boolean connectToService() {
1119            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1120                    " DefaultContainerService");
1121            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1124                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                mBound = true;
1127                return true;
1128            }
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130            return false;
1131        }
1132
1133        private void disconnectService() {
1134            mContainerService = null;
1135            mBound = false;
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            mContext.unbindService(mDefContainerConn);
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139        }
1140
1141        PackageHandler(Looper looper) {
1142            super(looper);
1143        }
1144
1145        public void handleMessage(Message msg) {
1146            try {
1147                doHandleMessage(msg);
1148            } finally {
1149                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150            }
1151        }
1152
1153        void doHandleMessage(Message msg) {
1154            switch (msg.what) {
1155                case INIT_COPY: {
1156                    HandlerParams params = (HandlerParams) msg.obj;
1157                    int idx = mPendingInstalls.size();
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1159                    // If a bind was already initiated we dont really
1160                    // need to do anything. The pending install
1161                    // will be processed later on.
1162                    if (!mBound) {
1163                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1164                                System.identityHashCode(mHandler));
1165                        // If this is the only one pending we might
1166                        // have to bind to the service again.
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            params.serviceError();
1170                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                    System.identityHashCode(mHandler));
1172                            if (params.traceMethod != null) {
1173                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1174                                        params.traceCookie);
1175                            }
1176                            return;
1177                        } else {
1178                            // Once we bind to the service, the first
1179                            // pending request will be processed.
1180                            mPendingInstalls.add(idx, params);
1181                        }
1182                    } else {
1183                        mPendingInstalls.add(idx, params);
1184                        // Already bound to the service. Just make
1185                        // sure we trigger off processing the first request.
1186                        if (idx == 0) {
1187                            mHandler.sendEmptyMessage(MCS_BOUND);
1188                        }
1189                    }
1190                    break;
1191                }
1192                case MCS_BOUND: {
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1194                    if (msg.obj != null) {
1195                        mContainerService = (IMediaContainerService) msg.obj;
1196                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                System.identityHashCode(mHandler));
1198                    }
1199                    if (mContainerService == null) {
1200                        if (!mBound) {
1201                            // Something seriously wrong since we are not bound and we are not
1202                            // waiting for connection. Bail out.
1203                            Slog.e(TAG, "Cannot bind to media container service");
1204                            for (HandlerParams params : mPendingInstalls) {
1205                                // Indicate service bind error
1206                                params.serviceError();
1207                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1208                                        System.identityHashCode(params));
1209                                if (params.traceMethod != null) {
1210                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1211                                            params.traceMethod, params.traceCookie);
1212                                }
1213                                return;
1214                            }
1215                            mPendingInstalls.clear();
1216                        } else {
1217                            Slog.w(TAG, "Waiting to connect to media container service");
1218                        }
1219                    } else if (mPendingInstalls.size() > 0) {
1220                        HandlerParams params = mPendingInstalls.get(0);
1221                        if (params != null) {
1222                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1223                                    System.identityHashCode(params));
1224                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1225                            if (params.startCopy()) {
1226                                // We are done...  look for more work or to
1227                                // go idle.
1228                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1229                                        "Checking for more work or unbind...");
1230                                // Delete pending install
1231                                if (mPendingInstalls.size() > 0) {
1232                                    mPendingInstalls.remove(0);
1233                                }
1234                                if (mPendingInstalls.size() == 0) {
1235                                    if (mBound) {
1236                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                                "Posting delayed MCS_UNBIND");
1238                                        removeMessages(MCS_UNBIND);
1239                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1240                                        // Unbind after a little delay, to avoid
1241                                        // continual thrashing.
1242                                        sendMessageDelayed(ubmsg, 10000);
1243                                    }
1244                                } else {
1245                                    // There are more pending requests in queue.
1246                                    // Just post MCS_BOUND message to trigger processing
1247                                    // of next pending install.
1248                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                            "Posting MCS_BOUND for next work");
1250                                    mHandler.sendEmptyMessage(MCS_BOUND);
1251                                }
1252                            }
1253                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1254                        }
1255                    } else {
1256                        // Should never happen ideally.
1257                        Slog.w(TAG, "Empty queue");
1258                    }
1259                    break;
1260                }
1261                case MCS_RECONNECT: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1263                    if (mPendingInstalls.size() > 0) {
1264                        if (mBound) {
1265                            disconnectService();
1266                        }
1267                        if (!connectToService()) {
1268                            Slog.e(TAG, "Failed to bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                            }
1275                            mPendingInstalls.clear();
1276                        }
1277                    }
1278                    break;
1279                }
1280                case MCS_UNBIND: {
1281                    // If there is no actual work left, then time to unbind.
1282                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1283
1284                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1285                        if (mBound) {
1286                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1287
1288                            disconnectService();
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        // There are more pending requests in queue.
1292                        // Just post MCS_BOUND message to trigger processing
1293                        // of next pending install.
1294                        mHandler.sendEmptyMessage(MCS_BOUND);
1295                    }
1296
1297                    break;
1298                }
1299                case MCS_GIVE_UP: {
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1301                    HandlerParams params = mPendingInstalls.remove(0);
1302                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1303                            System.identityHashCode(params));
1304                    break;
1305                }
1306                case SEND_PENDING_BROADCAST: {
1307                    String packages[];
1308                    ArrayList<String> components[];
1309                    int size = 0;
1310                    int uids[];
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1312                    synchronized (mPackages) {
1313                        if (mPendingBroadcasts == null) {
1314                            return;
1315                        }
1316                        size = mPendingBroadcasts.size();
1317                        if (size <= 0) {
1318                            // Nothing to be done. Just return
1319                            return;
1320                        }
1321                        packages = new String[size];
1322                        components = new ArrayList[size];
1323                        uids = new int[size];
1324                        int i = 0;  // filling out the above arrays
1325
1326                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1327                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1328                            Iterator<Map.Entry<String, ArrayList<String>>> it
1329                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1330                                            .entrySet().iterator();
1331                            while (it.hasNext() && i < size) {
1332                                Map.Entry<String, ArrayList<String>> ent = it.next();
1333                                packages[i] = ent.getKey();
1334                                components[i] = ent.getValue();
1335                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1336                                uids[i] = (ps != null)
1337                                        ? UserHandle.getUid(packageUserId, ps.appId)
1338                                        : -1;
1339                                i++;
1340                            }
1341                        }
1342                        size = i;
1343                        mPendingBroadcasts.clear();
1344                    }
1345                    // Send broadcasts
1346                    for (int i = 0; i < size; i++) {
1347                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1348                    }
1349                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350                    break;
1351                }
1352                case START_CLEANING_PACKAGE: {
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    final String packageName = (String)msg.obj;
1355                    final int userId = msg.arg1;
1356                    final boolean andCode = msg.arg2 != 0;
1357                    synchronized (mPackages) {
1358                        if (userId == UserHandle.USER_ALL) {
1359                            int[] users = sUserManager.getUserIds();
1360                            for (int user : users) {
1361                                mSettings.addPackageToCleanLPw(
1362                                        new PackageCleanItem(user, packageName, andCode));
1363                            }
1364                        } else {
1365                            mSettings.addPackageToCleanLPw(
1366                                    new PackageCleanItem(userId, packageName, andCode));
1367                        }
1368                    }
1369                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370                    startCleaningPackages();
1371                } break;
1372                case POST_INSTALL: {
1373                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1374                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1375                    mRunningInstalls.delete(msg.arg1);
1376                    boolean deleteOld = false;
1377
1378                    if (data != null) {
1379                        InstallArgs args = data.args;
1380                        PackageInstalledInfo res = data.res;
1381
1382                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1383                            final String packageName = res.pkg.applicationInfo.packageName;
1384                            res.removedInfo.sendBroadcast(false, true, false);
1385                            Bundle extras = new Bundle(1);
1386                            extras.putInt(Intent.EXTRA_UID, res.uid);
1387
1388                            // Now that we successfully installed the package, grant runtime
1389                            // permissions if requested before broadcasting the install.
1390                            if ((args.installFlags
1391                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1392                                    && res.pkg.applicationInfo.targetSdkVersion
1393                                            >= Build.VERSION_CODES.M) {
1394                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1395                                        args.installGrantPermissions);
1396                            }
1397
1398                            // Determine the set of users who are adding this
1399                            // package for the first time vs. those who are seeing
1400                            // an update.
1401                            int[] firstUsers;
1402                            int[] updateUsers = new int[0];
1403                            if (res.origUsers == null || res.origUsers.length == 0) {
1404                                firstUsers = res.newUsers;
1405                            } else {
1406                                firstUsers = new int[0];
1407                                for (int i=0; i<res.newUsers.length; i++) {
1408                                    int user = res.newUsers[i];
1409                                    boolean isNew = true;
1410                                    for (int j=0; j<res.origUsers.length; j++) {
1411                                        if (res.origUsers[j] == user) {
1412                                            isNew = false;
1413                                            break;
1414                                        }
1415                                    }
1416                                    if (isNew) {
1417                                        int[] newFirst = new int[firstUsers.length+1];
1418                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1419                                                firstUsers.length);
1420                                        newFirst[firstUsers.length] = user;
1421                                        firstUsers = newFirst;
1422                                    } else {
1423                                        int[] newUpdate = new int[updateUsers.length+1];
1424                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1425                                                updateUsers.length);
1426                                        newUpdate[updateUsers.length] = user;
1427                                        updateUsers = newUpdate;
1428                                    }
1429                                }
1430                            }
1431                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1432                                    packageName, extras, 0, null, null, firstUsers);
1433                            final boolean update = res.removedInfo.removedPackage != null;
1434                            if (update) {
1435                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1436                            }
1437                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1438                                    packageName, extras, 0, null, null, updateUsers);
1439                            if (update) {
1440                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1441                                        packageName, extras, 0, null, null, updateUsers);
1442                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1443                                        null, null, 0, packageName, null, updateUsers);
1444
1445                                // treat asec-hosted packages like removable media on upgrade
1446                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1447                                    if (DEBUG_INSTALL) {
1448                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1449                                                + " is ASEC-hosted -> AVAILABLE");
1450                                    }
1451                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1452                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1453                                    pkgList.add(packageName);
1454                                    sendResourcesChangedBroadcast(true, true,
1455                                            pkgList,uidArray, null);
1456                                }
1457                            }
1458                            if (res.removedInfo.args != null) {
1459                                // Remove the replaced package's older resources safely now
1460                                deleteOld = true;
1461                            }
1462
1463                            // If this app is a browser and it's newly-installed for some
1464                            // users, clear any default-browser state in those users
1465                            if (firstUsers.length > 0) {
1466                                // the app's nature doesn't depend on the user, so we can just
1467                                // check its browser nature in any user and generalize.
1468                                if (packageIsBrowser(packageName, firstUsers[0])) {
1469                                    synchronized (mPackages) {
1470                                        for (int userId : firstUsers) {
1471                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1472                                        }
1473                                    }
1474                                }
1475                            }
1476                            // Log current value of "unknown sources" setting
1477                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1478                                getUnknownSourcesSettings());
1479                        }
1480                        // Force a gc to clear up things
1481                        Runtime.getRuntime().gc();
1482                        // We delete after a gc for applications  on sdcard.
1483                        if (deleteOld) {
1484                            synchronized (mInstallLock) {
1485                                res.removedInfo.args.doPostDeleteLI(true);
1486                            }
1487                        }
1488                        if (args.observer != null) {
1489                            try {
1490                                Bundle extras = extrasForInstallResult(res);
1491                                args.observer.onPackageInstalled(res.name, res.returnCode,
1492                                        res.returnMsg, extras);
1493                            } catch (RemoteException e) {
1494                                Slog.i(TAG, "Observer no longer exists.");
1495                            }
1496                        }
1497                        if (args.traceMethod != null) {
1498                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1499                                    args.traceCookie);
1500                        }
1501                        return;
1502                    } else {
1503                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1504                    }
1505
1506                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1507                } break;
1508                case UPDATED_MEDIA_STATUS: {
1509                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1510                    boolean reportStatus = msg.arg1 == 1;
1511                    boolean doGc = msg.arg2 == 1;
1512                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1513                    if (doGc) {
1514                        // Force a gc to clear up stale containers.
1515                        Runtime.getRuntime().gc();
1516                    }
1517                    if (msg.obj != null) {
1518                        @SuppressWarnings("unchecked")
1519                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1520                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1521                        // Unload containers
1522                        unloadAllContainers(args);
1523                    }
1524                    if (reportStatus) {
1525                        try {
1526                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1527                            PackageHelper.getMountService().finishMediaUpdate();
1528                        } catch (RemoteException e) {
1529                            Log.e(TAG, "MountService not running?");
1530                        }
1531                    }
1532                } break;
1533                case WRITE_SETTINGS: {
1534                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1535                    synchronized (mPackages) {
1536                        removeMessages(WRITE_SETTINGS);
1537                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1538                        mSettings.writeLPr();
1539                        mDirtyUsers.clear();
1540                    }
1541                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1542                } break;
1543                case WRITE_PACKAGE_RESTRICTIONS: {
1544                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1545                    synchronized (mPackages) {
1546                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1547                        for (int userId : mDirtyUsers) {
1548                            mSettings.writePackageRestrictionsLPr(userId);
1549                        }
1550                        mDirtyUsers.clear();
1551                    }
1552                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1553                } break;
1554                case CHECK_PENDING_VERIFICATION: {
1555                    final int verificationId = msg.arg1;
1556                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1557
1558                    if ((state != null) && !state.timeoutExtended()) {
1559                        final InstallArgs args = state.getInstallArgs();
1560                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1561
1562                        Slog.i(TAG, "Verification timed out for " + originUri);
1563                        mPendingVerification.remove(verificationId);
1564
1565                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1566
1567                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1568                            Slog.i(TAG, "Continuing with installation of " + originUri);
1569                            state.setVerifierResponse(Binder.getCallingUid(),
1570                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1571                            broadcastPackageVerified(verificationId, originUri,
1572                                    PackageManager.VERIFICATION_ALLOW,
1573                                    state.getInstallArgs().getUser());
1574                            try {
1575                                ret = args.copyApk(mContainerService, true);
1576                            } catch (RemoteException e) {
1577                                Slog.e(TAG, "Could not contact the ContainerService");
1578                            }
1579                        } else {
1580                            broadcastPackageVerified(verificationId, originUri,
1581                                    PackageManager.VERIFICATION_REJECT,
1582                                    state.getInstallArgs().getUser());
1583                        }
1584
1585                        Trace.asyncTraceEnd(
1586                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1587
1588                        processPendingInstall(args, ret);
1589                        mHandler.sendEmptyMessage(MCS_UNBIND);
1590                    }
1591                    break;
1592                }
1593                case PACKAGE_VERIFIED: {
1594                    final int verificationId = msg.arg1;
1595
1596                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1597                    if (state == null) {
1598                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1599                        break;
1600                    }
1601
1602                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1603
1604                    state.setVerifierResponse(response.callerUid, response.code);
1605
1606                    if (state.isVerificationComplete()) {
1607                        mPendingVerification.remove(verificationId);
1608
1609                        final InstallArgs args = state.getInstallArgs();
1610                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1611
1612                        int ret;
1613                        if (state.isInstallAllowed()) {
1614                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1615                            broadcastPackageVerified(verificationId, originUri,
1616                                    response.code, state.getInstallArgs().getUser());
1617                            try {
1618                                ret = args.copyApk(mContainerService, true);
1619                            } catch (RemoteException e) {
1620                                Slog.e(TAG, "Could not contact the ContainerService");
1621                            }
1622                        } else {
1623                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1624                        }
1625
1626                        Trace.asyncTraceEnd(
1627                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1628
1629                        processPendingInstall(args, ret);
1630                        mHandler.sendEmptyMessage(MCS_UNBIND);
1631                    }
1632
1633                    break;
1634                }
1635                case START_INTENT_FILTER_VERIFICATIONS: {
1636                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1637                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1638                            params.replacing, params.pkg);
1639                    break;
1640                }
1641                case INTENT_FILTER_VERIFIED: {
1642                    final int verificationId = msg.arg1;
1643
1644                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1645                            verificationId);
1646                    if (state == null) {
1647                        Slog.w(TAG, "Invalid IntentFilter verification token "
1648                                + verificationId + " received");
1649                        break;
1650                    }
1651
1652                    final int userId = state.getUserId();
1653
1654                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1655                            "Processing IntentFilter verification with token:"
1656                            + verificationId + " and userId:" + userId);
1657
1658                    final IntentFilterVerificationResponse response =
1659                            (IntentFilterVerificationResponse) msg.obj;
1660
1661                    state.setVerifierResponse(response.callerUid, response.code);
1662
1663                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1664                            "IntentFilter verification with token:" + verificationId
1665                            + " and userId:" + userId
1666                            + " is settings verifier response with response code:"
1667                            + response.code);
1668
1669                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1670                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1671                                + response.getFailedDomainsString());
1672                    }
1673
1674                    if (state.isVerificationComplete()) {
1675                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1676                    } else {
1677                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1678                                "IntentFilter verification with token:" + verificationId
1679                                + " was not said to be complete");
1680                    }
1681
1682                    break;
1683                }
1684            }
1685        }
1686    }
1687
1688    private StorageEventListener mStorageListener = new StorageEventListener() {
1689        @Override
1690        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1691            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1692                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1693                    final String volumeUuid = vol.getFsUuid();
1694
1695                    // Clean up any users or apps that were removed or recreated
1696                    // while this volume was missing
1697                    reconcileUsers(volumeUuid);
1698                    reconcileApps(volumeUuid);
1699
1700                    // Clean up any install sessions that expired or were
1701                    // cancelled while this volume was missing
1702                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1703
1704                    loadPrivatePackages(vol);
1705
1706                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1707                    unloadPrivatePackages(vol);
1708                }
1709            }
1710
1711            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1712                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1713                    updateExternalMediaStatus(true, false);
1714                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1715                    updateExternalMediaStatus(false, false);
1716                }
1717            }
1718        }
1719
1720        @Override
1721        public void onVolumeForgotten(String fsUuid) {
1722            if (TextUtils.isEmpty(fsUuid)) {
1723                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1724                return;
1725            }
1726
1727            // Remove any apps installed on the forgotten volume
1728            synchronized (mPackages) {
1729                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1730                for (PackageSetting ps : packages) {
1731                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1732                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1733                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1734                }
1735
1736                mSettings.onVolumeForgotten(fsUuid);
1737                mSettings.writeLPr();
1738            }
1739        }
1740    };
1741
1742    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1743            String[] grantedPermissions) {
1744        if (userId >= UserHandle.USER_SYSTEM) {
1745            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1746        } else if (userId == UserHandle.USER_ALL) {
1747            final int[] userIds;
1748            synchronized (mPackages) {
1749                userIds = UserManagerService.getInstance().getUserIds();
1750            }
1751            for (int someUserId : userIds) {
1752                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1753            }
1754        }
1755
1756        // We could have touched GID membership, so flush out packages.list
1757        synchronized (mPackages) {
1758            mSettings.writePackageListLPr();
1759        }
1760    }
1761
1762    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1763            String[] grantedPermissions) {
1764        SettingBase sb = (SettingBase) pkg.mExtras;
1765        if (sb == null) {
1766            return;
1767        }
1768
1769        PermissionsState permissionsState = sb.getPermissionsState();
1770
1771        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1772                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1773
1774        synchronized (mPackages) {
1775            for (String permission : pkg.requestedPermissions) {
1776                BasePermission bp = mSettings.mPermissions.get(permission);
1777                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1778                        && (grantedPermissions == null
1779                               || ArrayUtils.contains(grantedPermissions, permission))) {
1780                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1781                    // Installer cannot change immutable permissions.
1782                    if ((flags & immutableFlags) == 0) {
1783                        grantRuntimePermission(pkg.packageName, permission, userId);
1784                    }
1785                }
1786            }
1787        }
1788    }
1789
1790    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1791        Bundle extras = null;
1792        switch (res.returnCode) {
1793            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1794                extras = new Bundle();
1795                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1796                        res.origPermission);
1797                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1798                        res.origPackage);
1799                break;
1800            }
1801            case PackageManager.INSTALL_SUCCEEDED: {
1802                extras = new Bundle();
1803                extras.putBoolean(Intent.EXTRA_REPLACING,
1804                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1805                break;
1806            }
1807        }
1808        return extras;
1809    }
1810
1811    void scheduleWriteSettingsLocked() {
1812        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1813            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1814        }
1815    }
1816
1817    void scheduleWritePackageRestrictionsLocked(int userId) {
1818        if (!sUserManager.exists(userId)) return;
1819        mDirtyUsers.add(userId);
1820        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1821            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1822        }
1823    }
1824
1825    public static PackageManagerService main(Context context, Installer installer,
1826            boolean factoryTest, boolean onlyCore) {
1827        PackageManagerService m = new PackageManagerService(context, installer,
1828                factoryTest, onlyCore);
1829        m.enableSystemUserApps();
1830        ServiceManager.addService("package", m);
1831        return m;
1832    }
1833
1834    private void enableSystemUserApps() {
1835        if (!UserManager.isSplitSystemUser()) {
1836            return;
1837        }
1838        // For system user, enable apps based on the following conditions:
1839        // - app is whitelisted or belong to one of these groups:
1840        //   -- system app which has no launcher icons
1841        //   -- system app which has INTERACT_ACROSS_USERS permission
1842        //   -- system IME app
1843        // - app is not in the blacklist
1844        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1845        Set<String> enableApps = new ArraySet<>();
1846        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1847                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1848                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1849        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1850        enableApps.addAll(wlApps);
1851        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1852        enableApps.removeAll(blApps);
1853
1854        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1855                UserHandle.SYSTEM);
1856        final int systemAppsSize = systemApps.size();
1857        synchronized (mPackages) {
1858            for (int i = 0; i < systemAppsSize; i++) {
1859                String pName = systemApps.get(i);
1860                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1861                // Should not happen, but we shouldn't be failing if it does
1862                if (pkgSetting == null) {
1863                    continue;
1864                }
1865                boolean installed = enableApps.contains(pName);
1866                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1867            }
1868        }
1869    }
1870
1871    static String[] splitString(String str, char sep) {
1872        int count = 1;
1873        int i = 0;
1874        while ((i=str.indexOf(sep, i)) >= 0) {
1875            count++;
1876            i++;
1877        }
1878
1879        String[] res = new String[count];
1880        i=0;
1881        count = 0;
1882        int lastI=0;
1883        while ((i=str.indexOf(sep, i)) >= 0) {
1884            res[count] = str.substring(lastI, i);
1885            count++;
1886            i++;
1887            lastI = i;
1888        }
1889        res[count] = str.substring(lastI, str.length());
1890        return res;
1891    }
1892
1893    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1894        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1895                Context.DISPLAY_SERVICE);
1896        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1897    }
1898
1899    public PackageManagerService(Context context, Installer installer,
1900            boolean factoryTest, boolean onlyCore) {
1901        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1902                SystemClock.uptimeMillis());
1903
1904        if (mSdkVersion <= 0) {
1905            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1906        }
1907
1908        mContext = context;
1909        mFactoryTest = factoryTest;
1910        mOnlyCore = onlyCore;
1911        mMetrics = new DisplayMetrics();
1912        mSettings = new Settings(mPackages);
1913        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1914                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1915        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1916                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1917        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1918                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1919        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1920                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1921        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1922                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1923        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1924                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1925
1926        String separateProcesses = SystemProperties.get("debug.separate_processes");
1927        if (separateProcesses != null && separateProcesses.length() > 0) {
1928            if ("*".equals(separateProcesses)) {
1929                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1930                mSeparateProcesses = null;
1931                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1932            } else {
1933                mDefParseFlags = 0;
1934                mSeparateProcesses = separateProcesses.split(",");
1935                Slog.w(TAG, "Running with debug.separate_processes: "
1936                        + separateProcesses);
1937            }
1938        } else {
1939            mDefParseFlags = 0;
1940            mSeparateProcesses = null;
1941        }
1942
1943        mInstaller = installer;
1944        mPackageDexOptimizer = new PackageDexOptimizer(this);
1945        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1946
1947        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1948                FgThread.get().getLooper());
1949
1950        getDefaultDisplayMetrics(context, mMetrics);
1951
1952        SystemConfig systemConfig = SystemConfig.getInstance();
1953        mGlobalGids = systemConfig.getGlobalGids();
1954        mSystemPermissions = systemConfig.getSystemPermissions();
1955        mAvailableFeatures = systemConfig.getAvailableFeatures();
1956
1957        synchronized (mInstallLock) {
1958        // writer
1959        synchronized (mPackages) {
1960            mHandlerThread = new ServiceThread(TAG,
1961                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1962            mHandlerThread.start();
1963            mHandler = new PackageHandler(mHandlerThread.getLooper());
1964            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1965
1966            File dataDir = Environment.getDataDirectory();
1967            mAppDataDir = new File(dataDir, "data");
1968            mAppInstallDir = new File(dataDir, "app");
1969            mAppLib32InstallDir = new File(dataDir, "app-lib");
1970            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1971            mUserAppDataDir = new File(dataDir, "user");
1972            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1973
1974            sUserManager = new UserManagerService(context, this, mPackages);
1975
1976            // Propagate permission configuration in to package manager.
1977            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1978                    = systemConfig.getPermissions();
1979            for (int i=0; i<permConfig.size(); i++) {
1980                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1981                BasePermission bp = mSettings.mPermissions.get(perm.name);
1982                if (bp == null) {
1983                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1984                    mSettings.mPermissions.put(perm.name, bp);
1985                }
1986                if (perm.gids != null) {
1987                    bp.setGids(perm.gids, perm.perUser);
1988                }
1989            }
1990
1991            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1992            for (int i=0; i<libConfig.size(); i++) {
1993                mSharedLibraries.put(libConfig.keyAt(i),
1994                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1995            }
1996
1997            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1998
1999            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2000
2001            String customResolverActivity = Resources.getSystem().getString(
2002                    R.string.config_customResolverActivity);
2003            if (TextUtils.isEmpty(customResolverActivity)) {
2004                customResolverActivity = null;
2005            } else {
2006                mCustomResolverComponentName = ComponentName.unflattenFromString(
2007                        customResolverActivity);
2008            }
2009
2010            long startTime = SystemClock.uptimeMillis();
2011
2012            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2013                    startTime);
2014
2015            // Set flag to monitor and not change apk file paths when
2016            // scanning install directories.
2017            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2018
2019            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2020            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2021
2022            if (bootClassPath == null) {
2023                Slog.w(TAG, "No BOOTCLASSPATH found!");
2024            }
2025
2026            if (systemServerClassPath == null) {
2027                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2028            }
2029
2030            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2031            final String[] dexCodeInstructionSets =
2032                    getDexCodeInstructionSets(
2033                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2034
2035            /**
2036             * Ensure all external libraries have had dexopt run on them.
2037             */
2038            if (mSharedLibraries.size() > 0) {
2039                // NOTE: For now, we're compiling these system "shared libraries"
2040                // (and framework jars) into all available architectures. It's possible
2041                // to compile them only when we come across an app that uses them (there's
2042                // already logic for that in scanPackageLI) but that adds some complexity.
2043                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2044                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2045                        final String lib = libEntry.path;
2046                        if (lib == null) {
2047                            continue;
2048                        }
2049
2050                        try {
2051                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2052                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2053                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2054                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2055                            }
2056                        } catch (FileNotFoundException e) {
2057                            Slog.w(TAG, "Library not found: " + lib);
2058                        } catch (IOException e) {
2059                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2060                                    + e.getMessage());
2061                        }
2062                    }
2063                }
2064            }
2065
2066            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2067
2068            final VersionInfo ver = mSettings.getInternalVersion();
2069            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2070            // when upgrading from pre-M, promote system app permissions from install to runtime
2071            mPromoteSystemApps =
2072                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2073
2074            // save off the names of pre-existing system packages prior to scanning; we don't
2075            // want to automatically grant runtime permissions for new system apps
2076            if (mPromoteSystemApps) {
2077                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2078                while (pkgSettingIter.hasNext()) {
2079                    PackageSetting ps = pkgSettingIter.next();
2080                    if (isSystemApp(ps)) {
2081                        mExistingSystemPackages.add(ps.name);
2082                    }
2083                }
2084            }
2085
2086            // Collect vendor overlay packages.
2087            // (Do this before scanning any apps.)
2088            // For security and version matching reason, only consider
2089            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2090            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2091            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2092                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2093
2094            // Find base frameworks (resource packages without code).
2095            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2096                    | PackageParser.PARSE_IS_SYSTEM_DIR
2097                    | PackageParser.PARSE_IS_PRIVILEGED,
2098                    scanFlags | SCAN_NO_DEX, 0);
2099
2100            // Collected privileged system packages.
2101            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2102            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2103                    | PackageParser.PARSE_IS_SYSTEM_DIR
2104                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2105
2106            // Collect ordinary system packages.
2107            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2108            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2109                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2110
2111            // Collect all vendor packages.
2112            File vendorAppDir = new File("/vendor/app");
2113            try {
2114                vendorAppDir = vendorAppDir.getCanonicalFile();
2115            } catch (IOException e) {
2116                // failed to look up canonical path, continue with original one
2117            }
2118            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2119                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2120
2121            // Collect all OEM packages.
2122            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2123            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2124                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2125
2126            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2127            mInstaller.moveFiles();
2128
2129            // Prune any system packages that no longer exist.
2130            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2131            if (!mOnlyCore) {
2132                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2133                while (psit.hasNext()) {
2134                    PackageSetting ps = psit.next();
2135
2136                    /*
2137                     * If this is not a system app, it can't be a
2138                     * disable system app.
2139                     */
2140                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2141                        continue;
2142                    }
2143
2144                    /*
2145                     * If the package is scanned, it's not erased.
2146                     */
2147                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2148                    if (scannedPkg != null) {
2149                        /*
2150                         * If the system app is both scanned and in the
2151                         * disabled packages list, then it must have been
2152                         * added via OTA. Remove it from the currently
2153                         * scanned package so the previously user-installed
2154                         * application can be scanned.
2155                         */
2156                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2157                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2158                                    + ps.name + "; removing system app.  Last known codePath="
2159                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2160                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2161                                    + scannedPkg.mVersionCode);
2162                            removePackageLI(ps, true);
2163                            mExpectingBetter.put(ps.name, ps.codePath);
2164                        }
2165
2166                        continue;
2167                    }
2168
2169                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2170                        psit.remove();
2171                        logCriticalInfo(Log.WARN, "System package " + ps.name
2172                                + " no longer exists; wiping its data");
2173                        removeDataDirsLI(null, ps.name);
2174                    } else {
2175                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2176                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2177                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2178                        }
2179                    }
2180                }
2181            }
2182
2183            //look for any incomplete package installations
2184            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2185            //clean up list
2186            for(int i = 0; i < deletePkgsList.size(); i++) {
2187                //clean up here
2188                cleanupInstallFailedPackage(deletePkgsList.get(i));
2189            }
2190            //delete tmp files
2191            deleteTempPackageFiles();
2192
2193            // Remove any shared userIDs that have no associated packages
2194            mSettings.pruneSharedUsersLPw();
2195
2196            if (!mOnlyCore) {
2197                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2198                        SystemClock.uptimeMillis());
2199                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2200
2201                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2202                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2203
2204                /**
2205                 * Remove disable package settings for any updated system
2206                 * apps that were removed via an OTA. If they're not a
2207                 * previously-updated app, remove them completely.
2208                 * Otherwise, just revoke their system-level permissions.
2209                 */
2210                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2211                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2212                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2213
2214                    String msg;
2215                    if (deletedPkg == null) {
2216                        msg = "Updated system package " + deletedAppName
2217                                + " no longer exists; wiping its data";
2218                        removeDataDirsLI(null, deletedAppName);
2219                    } else {
2220                        msg = "Updated system app + " + deletedAppName
2221                                + " no longer present; removing system privileges for "
2222                                + deletedAppName;
2223
2224                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2225
2226                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2227                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2228                    }
2229                    logCriticalInfo(Log.WARN, msg);
2230                }
2231
2232                /**
2233                 * Make sure all system apps that we expected to appear on
2234                 * the userdata partition actually showed up. If they never
2235                 * appeared, crawl back and revive the system version.
2236                 */
2237                for (int i = 0; i < mExpectingBetter.size(); i++) {
2238                    final String packageName = mExpectingBetter.keyAt(i);
2239                    if (!mPackages.containsKey(packageName)) {
2240                        final File scanFile = mExpectingBetter.valueAt(i);
2241
2242                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2243                                + " but never showed up; reverting to system");
2244
2245                        final int reparseFlags;
2246                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2247                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2248                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2249                                    | PackageParser.PARSE_IS_PRIVILEGED;
2250                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2251                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2252                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2253                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2254                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2255                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2256                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2257                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2258                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2259                        } else {
2260                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2261                            continue;
2262                        }
2263
2264                        mSettings.enableSystemPackageLPw(packageName);
2265
2266                        try {
2267                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2268                        } catch (PackageManagerException e) {
2269                            Slog.e(TAG, "Failed to parse original system package: "
2270                                    + e.getMessage());
2271                        }
2272                    }
2273                }
2274            }
2275            mExpectingBetter.clear();
2276
2277            // Now that we know all of the shared libraries, update all clients to have
2278            // the correct library paths.
2279            updateAllSharedLibrariesLPw();
2280
2281            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2282                // NOTE: We ignore potential failures here during a system scan (like
2283                // the rest of the commands above) because there's precious little we
2284                // can do about it. A settings error is reported, though.
2285                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2286                        false /* boot complete */);
2287            }
2288
2289            // Now that we know all the packages we are keeping,
2290            // read and update their last usage times.
2291            mPackageUsage.readLP();
2292
2293            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2294                    SystemClock.uptimeMillis());
2295            Slog.i(TAG, "Time to scan packages: "
2296                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2297                    + " seconds");
2298
2299            // If the platform SDK has changed since the last time we booted,
2300            // we need to re-grant app permission to catch any new ones that
2301            // appear.  This is really a hack, and means that apps can in some
2302            // cases get permissions that the user didn't initially explicitly
2303            // allow...  it would be nice to have some better way to handle
2304            // this situation.
2305            int updateFlags = UPDATE_PERMISSIONS_ALL;
2306            if (ver.sdkVersion != mSdkVersion) {
2307                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2308                        + mSdkVersion + "; regranting permissions for internal storage");
2309                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2310            }
2311            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2312            ver.sdkVersion = mSdkVersion;
2313
2314            // If this is the first boot or an update from pre-M, and it is a normal
2315            // boot, then we need to initialize the default preferred apps across
2316            // all defined users.
2317            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2318                for (UserInfo user : sUserManager.getUsers(true)) {
2319                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2320                    applyFactoryDefaultBrowserLPw(user.id);
2321                    primeDomainVerificationsLPw(user.id);
2322                }
2323            }
2324
2325            // If this is first boot after an OTA, and a normal boot, then
2326            // we need to clear code cache directories.
2327            if (mIsUpgrade && !onlyCore) {
2328                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2329                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2330                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2331                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2332                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2333                    }
2334                }
2335                ver.fingerprint = Build.FINGERPRINT;
2336            }
2337
2338            checkDefaultBrowser();
2339
2340            // clear only after permissions and other defaults have been updated
2341            mExistingSystemPackages.clear();
2342            mPromoteSystemApps = false;
2343
2344            // All the changes are done during package scanning.
2345            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2346
2347            // can downgrade to reader
2348            mSettings.writeLPr();
2349
2350            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2351                    SystemClock.uptimeMillis());
2352
2353            mRequiredVerifierPackage = getRequiredVerifierLPr();
2354            mRequiredInstallerPackage = getRequiredInstallerLPr();
2355
2356            mInstallerService = new PackageInstallerService(context, this);
2357
2358            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2359            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2360                    mIntentFilterVerifierComponent);
2361
2362            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2363            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2364            // both the installer and resolver must be present to enable ephemeral
2365            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2366                if (DEBUG_EPHEMERAL) {
2367                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2368                            + " installer:" + ephemeralInstallerComponent);
2369                }
2370                mEphemeralResolverComponent = ephemeralResolverComponent;
2371                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2372                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2373                mEphemeralResolverConnection =
2374                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2375            } else {
2376                if (DEBUG_EPHEMERAL) {
2377                    final String missingComponent =
2378                            (ephemeralResolverComponent == null)
2379                            ? (ephemeralInstallerComponent == null)
2380                                    ? "resolver and installer"
2381                                    : "resolver"
2382                            : "installer";
2383                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2384                }
2385                mEphemeralResolverComponent = null;
2386                mEphemeralInstallerComponent = null;
2387                mEphemeralResolverConnection = null;
2388            }
2389        } // synchronized (mPackages)
2390        } // synchronized (mInstallLock)
2391
2392        // Now after opening every single application zip, make sure they
2393        // are all flushed.  Not really needed, but keeps things nice and
2394        // tidy.
2395        Runtime.getRuntime().gc();
2396
2397        // The initial scanning above does many calls into installd while
2398        // holding the mPackages lock, but we're mostly interested in yelling
2399        // once we have a booted system.
2400        mInstaller.setWarnIfHeld(mPackages);
2401
2402        // Expose private service for system components to use.
2403        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2404    }
2405
2406    @Override
2407    public boolean isFirstBoot() {
2408        return !mRestoredSettings;
2409    }
2410
2411    @Override
2412    public boolean isOnlyCoreApps() {
2413        return mOnlyCore;
2414    }
2415
2416    @Override
2417    public boolean isUpgrade() {
2418        return mIsUpgrade;
2419    }
2420
2421    private String getRequiredVerifierLPr() {
2422        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2423        // We only care about verifier that's installed under system user.
2424        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2425                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2426
2427        String requiredVerifier = null;
2428
2429        final int N = receivers.size();
2430        for (int i = 0; i < N; i++) {
2431            final ResolveInfo info = receivers.get(i);
2432
2433            if (info.activityInfo == null) {
2434                continue;
2435            }
2436
2437            final String packageName = info.activityInfo.packageName;
2438
2439            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2440                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2441                continue;
2442            }
2443
2444            if (requiredVerifier != null) {
2445                throw new RuntimeException("There can be only one required verifier");
2446            }
2447
2448            requiredVerifier = packageName;
2449        }
2450
2451        return requiredVerifier;
2452    }
2453
2454    private String getRequiredInstallerLPr() {
2455        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2456        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2457        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2458
2459        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2460                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2461
2462        String requiredInstaller = null;
2463
2464        final int N = installers.size();
2465        for (int i = 0; i < N; i++) {
2466            final ResolveInfo info = installers.get(i);
2467            final String packageName = info.activityInfo.packageName;
2468
2469            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2470                continue;
2471            }
2472
2473            if (requiredInstaller != null) {
2474                throw new RuntimeException("There must be one required installer");
2475            }
2476
2477            requiredInstaller = packageName;
2478        }
2479
2480        if (requiredInstaller == null) {
2481            throw new RuntimeException("There must be one required installer");
2482        }
2483
2484        return requiredInstaller;
2485    }
2486
2487    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2488        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2489        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2490                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2491
2492        ComponentName verifierComponentName = null;
2493
2494        int priority = -1000;
2495        final int N = receivers.size();
2496        for (int i = 0; i < N; i++) {
2497            final ResolveInfo info = receivers.get(i);
2498
2499            if (info.activityInfo == null) {
2500                continue;
2501            }
2502
2503            final String packageName = info.activityInfo.packageName;
2504
2505            final PackageSetting ps = mSettings.mPackages.get(packageName);
2506            if (ps == null) {
2507                continue;
2508            }
2509
2510            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2511                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2512                continue;
2513            }
2514
2515            // Select the IntentFilterVerifier with the highest priority
2516            if (priority < info.priority) {
2517                priority = info.priority;
2518                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2519                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2520                        + verifierComponentName + " with priority: " + info.priority);
2521            }
2522        }
2523
2524        return verifierComponentName;
2525    }
2526
2527    private ComponentName getEphemeralResolverLPr() {
2528        final String[] packageArray =
2529                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2530        if (packageArray.length == 0) {
2531            if (DEBUG_EPHEMERAL) {
2532                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2533            }
2534            return null;
2535        }
2536
2537        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2538        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2539                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2540
2541        final int N = resolvers.size();
2542        if (N == 0) {
2543            if (DEBUG_EPHEMERAL) {
2544                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2545            }
2546            return null;
2547        }
2548
2549        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2550        for (int i = 0; i < N; i++) {
2551            final ResolveInfo info = resolvers.get(i);
2552
2553            if (info.serviceInfo == null) {
2554                continue;
2555            }
2556
2557            final String packageName = info.serviceInfo.packageName;
2558            if (!possiblePackages.contains(packageName)) {
2559                if (DEBUG_EPHEMERAL) {
2560                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2561                            + " pkg: " + packageName + ", info:" + info);
2562                }
2563                continue;
2564            }
2565
2566            if (DEBUG_EPHEMERAL) {
2567                Slog.v(TAG, "Ephemeral resolver found;"
2568                        + " pkg: " + packageName + ", info:" + info);
2569            }
2570            return new ComponentName(packageName, info.serviceInfo.name);
2571        }
2572        if (DEBUG_EPHEMERAL) {
2573            Slog.v(TAG, "Ephemeral resolver NOT found");
2574        }
2575        return null;
2576    }
2577
2578    private ComponentName getEphemeralInstallerLPr() {
2579        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2580        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2581        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2582        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2583                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2584
2585        ComponentName ephemeralInstaller = null;
2586
2587        final int N = installers.size();
2588        for (int i = 0; i < N; i++) {
2589            final ResolveInfo info = installers.get(i);
2590            final String packageName = info.activityInfo.packageName;
2591
2592            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2593                if (DEBUG_EPHEMERAL) {
2594                    Slog.d(TAG, "Ephemeral installer is not system app;"
2595                            + " pkg: " + packageName + ", info:" + info);
2596                }
2597                continue;
2598            }
2599
2600            if (ephemeralInstaller != null) {
2601                throw new RuntimeException("There must only be one ephemeral installer");
2602            }
2603
2604            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2605        }
2606
2607        return ephemeralInstaller;
2608    }
2609
2610    private void primeDomainVerificationsLPw(int userId) {
2611        if (DEBUG_DOMAIN_VERIFICATION) {
2612            Slog.d(TAG, "Priming domain verifications in user " + userId);
2613        }
2614
2615        SystemConfig systemConfig = SystemConfig.getInstance();
2616        ArraySet<String> packages = systemConfig.getLinkedApps();
2617        ArraySet<String> domains = new ArraySet<String>();
2618
2619        for (String packageName : packages) {
2620            PackageParser.Package pkg = mPackages.get(packageName);
2621            if (pkg != null) {
2622                if (!pkg.isSystemApp()) {
2623                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2624                    continue;
2625                }
2626
2627                domains.clear();
2628                for (PackageParser.Activity a : pkg.activities) {
2629                    for (ActivityIntentInfo filter : a.intents) {
2630                        if (hasValidDomains(filter)) {
2631                            domains.addAll(filter.getHostsList());
2632                        }
2633                    }
2634                }
2635
2636                if (domains.size() > 0) {
2637                    if (DEBUG_DOMAIN_VERIFICATION) {
2638                        Slog.v(TAG, "      + " + packageName);
2639                    }
2640                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2641                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2642                    // and then 'always' in the per-user state actually used for intent resolution.
2643                    final IntentFilterVerificationInfo ivi;
2644                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2645                            new ArrayList<String>(domains));
2646                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2647                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2648                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2649                } else {
2650                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2651                            + "' does not handle web links");
2652                }
2653            } else {
2654                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2655            }
2656        }
2657
2658        scheduleWritePackageRestrictionsLocked(userId);
2659        scheduleWriteSettingsLocked();
2660    }
2661
2662    private void applyFactoryDefaultBrowserLPw(int userId) {
2663        // The default browser app's package name is stored in a string resource,
2664        // with a product-specific overlay used for vendor customization.
2665        String browserPkg = mContext.getResources().getString(
2666                com.android.internal.R.string.default_browser);
2667        if (!TextUtils.isEmpty(browserPkg)) {
2668            // non-empty string => required to be a known package
2669            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2670            if (ps == null) {
2671                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2672                browserPkg = null;
2673            } else {
2674                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2675            }
2676        }
2677
2678        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2679        // default.  If there's more than one, just leave everything alone.
2680        if (browserPkg == null) {
2681            calculateDefaultBrowserLPw(userId);
2682        }
2683    }
2684
2685    private void calculateDefaultBrowserLPw(int userId) {
2686        List<String> allBrowsers = resolveAllBrowserApps(userId);
2687        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2688        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2689    }
2690
2691    private List<String> resolveAllBrowserApps(int userId) {
2692        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2693        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2694                PackageManager.MATCH_ALL, userId);
2695
2696        final int count = list.size();
2697        List<String> result = new ArrayList<String>(count);
2698        for (int i=0; i<count; i++) {
2699            ResolveInfo info = list.get(i);
2700            if (info.activityInfo == null
2701                    || !info.handleAllWebDataURI
2702                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2703                    || result.contains(info.activityInfo.packageName)) {
2704                continue;
2705            }
2706            result.add(info.activityInfo.packageName);
2707        }
2708
2709        return result;
2710    }
2711
2712    private boolean packageIsBrowser(String packageName, int userId) {
2713        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2714                PackageManager.MATCH_ALL, userId);
2715        final int N = list.size();
2716        for (int i = 0; i < N; i++) {
2717            ResolveInfo info = list.get(i);
2718            if (packageName.equals(info.activityInfo.packageName)) {
2719                return true;
2720            }
2721        }
2722        return false;
2723    }
2724
2725    private void checkDefaultBrowser() {
2726        final int myUserId = UserHandle.myUserId();
2727        final String packageName = getDefaultBrowserPackageName(myUserId);
2728        if (packageName != null) {
2729            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2730            if (info == null) {
2731                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2732                synchronized (mPackages) {
2733                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2734                }
2735            }
2736        }
2737    }
2738
2739    @Override
2740    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2741            throws RemoteException {
2742        try {
2743            return super.onTransact(code, data, reply, flags);
2744        } catch (RuntimeException e) {
2745            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2746                Slog.wtf(TAG, "Package Manager Crash", e);
2747            }
2748            throw e;
2749        }
2750    }
2751
2752    void cleanupInstallFailedPackage(PackageSetting ps) {
2753        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2754
2755        removeDataDirsLI(ps.volumeUuid, ps.name);
2756        if (ps.codePath != null) {
2757            if (ps.codePath.isDirectory()) {
2758                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2759            } else {
2760                ps.codePath.delete();
2761            }
2762        }
2763        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2764            if (ps.resourcePath.isDirectory()) {
2765                FileUtils.deleteContents(ps.resourcePath);
2766            }
2767            ps.resourcePath.delete();
2768        }
2769        mSettings.removePackageLPw(ps.name);
2770    }
2771
2772    static int[] appendInts(int[] cur, int[] add) {
2773        if (add == null) return cur;
2774        if (cur == null) return add;
2775        final int N = add.length;
2776        for (int i=0; i<N; i++) {
2777            cur = appendInt(cur, add[i]);
2778        }
2779        return cur;
2780    }
2781
2782    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2783        if (!sUserManager.exists(userId)) return null;
2784        final PackageSetting ps = (PackageSetting) p.mExtras;
2785        if (ps == null) {
2786            return null;
2787        }
2788
2789        final PermissionsState permissionsState = ps.getPermissionsState();
2790
2791        final int[] gids = permissionsState.computeGids(userId);
2792        final Set<String> permissions = permissionsState.getPermissions(userId);
2793        final PackageUserState state = ps.readUserState(userId);
2794
2795        return PackageParser.generatePackageInfo(p, gids, flags,
2796                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2797    }
2798
2799    @Override
2800    public boolean isPackageFrozen(String packageName) {
2801        synchronized (mPackages) {
2802            final PackageSetting ps = mSettings.mPackages.get(packageName);
2803            if (ps != null) {
2804                return ps.frozen;
2805            }
2806        }
2807        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2808        return true;
2809    }
2810
2811    @Override
2812    public boolean isPackageAvailable(String packageName, int userId) {
2813        if (!sUserManager.exists(userId)) return false;
2814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2815        synchronized (mPackages) {
2816            PackageParser.Package p = mPackages.get(packageName);
2817            if (p != null) {
2818                final PackageSetting ps = (PackageSetting) p.mExtras;
2819                if (ps != null) {
2820                    final PackageUserState state = ps.readUserState(userId);
2821                    if (state != null) {
2822                        return PackageParser.isAvailable(state);
2823                    }
2824                }
2825            }
2826        }
2827        return false;
2828    }
2829
2830    @Override
2831    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2832        if (!sUserManager.exists(userId)) return null;
2833        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2834        // reader
2835        synchronized (mPackages) {
2836            PackageParser.Package p = mPackages.get(packageName);
2837            if (DEBUG_PACKAGE_INFO)
2838                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2839            if (p != null) {
2840                return generatePackageInfo(p, flags, userId);
2841            }
2842            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2843                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2844            }
2845        }
2846        return null;
2847    }
2848
2849    @Override
2850    public String[] currentToCanonicalPackageNames(String[] names) {
2851        String[] out = new String[names.length];
2852        // reader
2853        synchronized (mPackages) {
2854            for (int i=names.length-1; i>=0; i--) {
2855                PackageSetting ps = mSettings.mPackages.get(names[i]);
2856                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2857            }
2858        }
2859        return out;
2860    }
2861
2862    @Override
2863    public String[] canonicalToCurrentPackageNames(String[] names) {
2864        String[] out = new String[names.length];
2865        // reader
2866        synchronized (mPackages) {
2867            for (int i=names.length-1; i>=0; i--) {
2868                String cur = mSettings.mRenamedPackages.get(names[i]);
2869                out[i] = cur != null ? cur : names[i];
2870            }
2871        }
2872        return out;
2873    }
2874
2875    @Override
2876    public int getPackageUid(String packageName, int userId) {
2877        return getPackageUidEtc(packageName, 0, userId);
2878    }
2879
2880    @Override
2881    public int getPackageUidEtc(String packageName, int flags, int userId) {
2882        if (!sUserManager.exists(userId)) return -1;
2883        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2884
2885        // reader
2886        synchronized (mPackages) {
2887            final PackageParser.Package p = mPackages.get(packageName);
2888            if (p != null) {
2889                return UserHandle.getUid(userId, p.applicationInfo.uid);
2890            }
2891            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2892                final PackageSetting ps = mSettings.mPackages.get(packageName);
2893                if (ps != null) {
2894                    return UserHandle.getUid(userId, ps.appId);
2895                }
2896            }
2897        }
2898
2899        return -1;
2900    }
2901
2902    @Override
2903    public int[] getPackageGids(String packageName, int userId) {
2904        return getPackageGidsEtc(packageName, 0, userId);
2905    }
2906
2907    @Override
2908    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2909        if (!sUserManager.exists(userId)) {
2910            return null;
2911        }
2912
2913        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2914                "getPackageGids");
2915
2916        // reader
2917        synchronized (mPackages) {
2918            final PackageParser.Package p = mPackages.get(packageName);
2919            if (p != null) {
2920                PackageSetting ps = (PackageSetting) p.mExtras;
2921                return ps.getPermissionsState().computeGids(userId);
2922            }
2923            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2924                final PackageSetting ps = mSettings.mPackages.get(packageName);
2925                if (ps != null) {
2926                    return ps.getPermissionsState().computeGids(userId);
2927                }
2928            }
2929        }
2930
2931        return null;
2932    }
2933
2934    static PermissionInfo generatePermissionInfo(
2935            BasePermission bp, int flags) {
2936        if (bp.perm != null) {
2937            return PackageParser.generatePermissionInfo(bp.perm, flags);
2938        }
2939        PermissionInfo pi = new PermissionInfo();
2940        pi.name = bp.name;
2941        pi.packageName = bp.sourcePackage;
2942        pi.nonLocalizedLabel = bp.name;
2943        pi.protectionLevel = bp.protectionLevel;
2944        return pi;
2945    }
2946
2947    @Override
2948    public PermissionInfo getPermissionInfo(String name, int flags) {
2949        // reader
2950        synchronized (mPackages) {
2951            final BasePermission p = mSettings.mPermissions.get(name);
2952            if (p != null) {
2953                return generatePermissionInfo(p, flags);
2954            }
2955            return null;
2956        }
2957    }
2958
2959    @Override
2960    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2961        // reader
2962        synchronized (mPackages) {
2963            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2964            for (BasePermission p : mSettings.mPermissions.values()) {
2965                if (group == null) {
2966                    if (p.perm == null || p.perm.info.group == null) {
2967                        out.add(generatePermissionInfo(p, flags));
2968                    }
2969                } else {
2970                    if (p.perm != null && group.equals(p.perm.info.group)) {
2971                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2972                    }
2973                }
2974            }
2975
2976            if (out.size() > 0) {
2977                return out;
2978            }
2979            return mPermissionGroups.containsKey(group) ? out : null;
2980        }
2981    }
2982
2983    @Override
2984    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2985        // reader
2986        synchronized (mPackages) {
2987            return PackageParser.generatePermissionGroupInfo(
2988                    mPermissionGroups.get(name), flags);
2989        }
2990    }
2991
2992    @Override
2993    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2994        // reader
2995        synchronized (mPackages) {
2996            final int N = mPermissionGroups.size();
2997            ArrayList<PermissionGroupInfo> out
2998                    = new ArrayList<PermissionGroupInfo>(N);
2999            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3000                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3001            }
3002            return out;
3003        }
3004    }
3005
3006    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3007            int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        PackageSetting ps = mSettings.mPackages.get(packageName);
3010        if (ps != null) {
3011            if (ps.pkg == null) {
3012                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3013                        flags, userId);
3014                if (pInfo != null) {
3015                    return pInfo.applicationInfo;
3016                }
3017                return null;
3018            }
3019            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3020                    ps.readUserState(userId), userId);
3021        }
3022        return null;
3023    }
3024
3025    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3026            int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        PackageSetting ps = mSettings.mPackages.get(packageName);
3029        if (ps != null) {
3030            PackageParser.Package pkg = ps.pkg;
3031            if (pkg == null) {
3032                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3033                    return null;
3034                }
3035                // Only data remains, so we aren't worried about code paths
3036                pkg = new PackageParser.Package(packageName);
3037                pkg.applicationInfo.packageName = packageName;
3038                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3039                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3040                pkg.applicationInfo.uid = ps.appId;
3041                pkg.applicationInfo.initForUser(userId);
3042                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3043                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3044            }
3045            return generatePackageInfo(pkg, flags, userId);
3046        }
3047        return null;
3048    }
3049
3050    @Override
3051    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3052        if (!sUserManager.exists(userId)) return null;
3053        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3054        // writer
3055        synchronized (mPackages) {
3056            PackageParser.Package p = mPackages.get(packageName);
3057            if (DEBUG_PACKAGE_INFO) Log.v(
3058                    TAG, "getApplicationInfo " + packageName
3059                    + ": " + p);
3060            if (p != null) {
3061                PackageSetting ps = mSettings.mPackages.get(packageName);
3062                if (ps == null) return null;
3063                // Note: isEnabledLP() does not apply here - always return info
3064                return PackageParser.generateApplicationInfo(
3065                        p, flags, ps.readUserState(userId), userId);
3066            }
3067            if ("android".equals(packageName)||"system".equals(packageName)) {
3068                return mAndroidApplication;
3069            }
3070            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3071                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3072            }
3073        }
3074        return null;
3075    }
3076
3077    @Override
3078    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3079            final IPackageDataObserver observer) {
3080        mContext.enforceCallingOrSelfPermission(
3081                android.Manifest.permission.CLEAR_APP_CACHE, null);
3082        // Queue up an async operation since clearing cache may take a little while.
3083        mHandler.post(new Runnable() {
3084            public void run() {
3085                mHandler.removeCallbacks(this);
3086                int retCode = -1;
3087                synchronized (mInstallLock) {
3088                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3089                    if (retCode < 0) {
3090                        Slog.w(TAG, "Couldn't clear application caches");
3091                    }
3092                }
3093                if (observer != null) {
3094                    try {
3095                        observer.onRemoveCompleted(null, (retCode >= 0));
3096                    } catch (RemoteException e) {
3097                        Slog.w(TAG, "RemoveException when invoking call back");
3098                    }
3099                }
3100            }
3101        });
3102    }
3103
3104    @Override
3105    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3106            final IntentSender pi) {
3107        mContext.enforceCallingOrSelfPermission(
3108                android.Manifest.permission.CLEAR_APP_CACHE, null);
3109        // Queue up an async operation since clearing cache may take a little while.
3110        mHandler.post(new Runnable() {
3111            public void run() {
3112                mHandler.removeCallbacks(this);
3113                int retCode = -1;
3114                synchronized (mInstallLock) {
3115                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3116                    if (retCode < 0) {
3117                        Slog.w(TAG, "Couldn't clear application caches");
3118                    }
3119                }
3120                if(pi != null) {
3121                    try {
3122                        // Callback via pending intent
3123                        int code = (retCode >= 0) ? 1 : 0;
3124                        pi.sendIntent(null, code, null,
3125                                null, null);
3126                    } catch (SendIntentException e1) {
3127                        Slog.i(TAG, "Failed to send pending intent");
3128                    }
3129                }
3130            }
3131        });
3132    }
3133
3134    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3135        synchronized (mInstallLock) {
3136            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3137                throw new IOException("Failed to free enough space");
3138            }
3139        }
3140    }
3141
3142    /**
3143     * Augment the given flags depending on current user running state. This is
3144     * purposefully done before acquiring {@link #mPackages} lock.
3145     */
3146    private int augmentFlagsForUser(int flags, int userId) {
3147        if (StorageManager.isFileBasedEncryptionEnabled()) {
3148            final IMountService mount = IMountService.Stub
3149                    .asInterface(ServiceManager.getService("mount"));
3150            if (mount == null) {
3151                // We must be early in boot, so the best we can do is assume the
3152                // user is fully running.
3153                Slog.w(TAG, "Early during boot, assuming not encrypted");
3154                return flags;
3155            }
3156            final long token = Binder.clearCallingIdentity();
3157            try {
3158                if (!mount.isUserKeyUnlocked(userId)) {
3159                    flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3160                }
3161            } catch (RemoteException e) {
3162                throw e.rethrowAsRuntimeException();
3163            } finally {
3164                Binder.restoreCallingIdentity(token);
3165            }
3166        }
3167        return flags;
3168    }
3169
3170    @Override
3171    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3172        if (!sUserManager.exists(userId)) return null;
3173        flags = augmentFlagsForUser(flags, userId);
3174        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3175        synchronized (mPackages) {
3176            PackageParser.Activity a = mActivities.mActivities.get(component);
3177
3178            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3179            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3180                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3181                if (ps == null) return null;
3182                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3183                        userId);
3184            }
3185            if (mResolveComponentName.equals(component)) {
3186                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3187                        new PackageUserState(), userId);
3188            }
3189        }
3190        return null;
3191    }
3192
3193    @Override
3194    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3195            String resolvedType) {
3196        synchronized (mPackages) {
3197            if (component.equals(mResolveComponentName)) {
3198                // The resolver supports EVERYTHING!
3199                return true;
3200            }
3201            PackageParser.Activity a = mActivities.mActivities.get(component);
3202            if (a == null) {
3203                return false;
3204            }
3205            for (int i=0; i<a.intents.size(); i++) {
3206                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3207                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3208                    return true;
3209                }
3210            }
3211            return false;
3212        }
3213    }
3214
3215    @Override
3216    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return null;
3218        flags = augmentFlagsForUser(flags, userId);
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3220        synchronized (mPackages) {
3221            PackageParser.Activity a = mReceivers.mActivities.get(component);
3222            if (DEBUG_PACKAGE_INFO) Log.v(
3223                TAG, "getReceiverInfo " + component + ": " + a);
3224            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3225                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3226                if (ps == null) return null;
3227                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3228                        userId);
3229            }
3230        }
3231        return null;
3232    }
3233
3234    @Override
3235    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3236        if (!sUserManager.exists(userId)) return null;
3237        flags = augmentFlagsForUser(flags, userId);
3238        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3239        synchronized (mPackages) {
3240            PackageParser.Service s = mServices.mServices.get(component);
3241            if (DEBUG_PACKAGE_INFO) Log.v(
3242                TAG, "getServiceInfo " + component + ": " + s);
3243            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3244                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3245                if (ps == null) return null;
3246                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3247                        userId);
3248            }
3249        }
3250        return null;
3251    }
3252
3253    @Override
3254    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3255        if (!sUserManager.exists(userId)) return null;
3256        flags = augmentFlagsForUser(flags, userId);
3257        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3258        synchronized (mPackages) {
3259            PackageParser.Provider p = mProviders.mProviders.get(component);
3260            if (DEBUG_PACKAGE_INFO) Log.v(
3261                TAG, "getProviderInfo " + component + ": " + p);
3262            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3263                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3264                if (ps == null) return null;
3265                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3266                        userId);
3267            }
3268        }
3269        return null;
3270    }
3271
3272    @Override
3273    public String[] getSystemSharedLibraryNames() {
3274        Set<String> libSet;
3275        synchronized (mPackages) {
3276            libSet = mSharedLibraries.keySet();
3277            int size = libSet.size();
3278            if (size > 0) {
3279                String[] libs = new String[size];
3280                libSet.toArray(libs);
3281                return libs;
3282            }
3283        }
3284        return null;
3285    }
3286
3287    /**
3288     * @hide
3289     */
3290    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3291        synchronized (mPackages) {
3292            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3293            if (lib != null && lib.apk != null) {
3294                return mPackages.get(lib.apk);
3295            }
3296        }
3297        return null;
3298    }
3299
3300    @Override
3301    public FeatureInfo[] getSystemAvailableFeatures() {
3302        Collection<FeatureInfo> featSet;
3303        synchronized (mPackages) {
3304            featSet = mAvailableFeatures.values();
3305            int size = featSet.size();
3306            if (size > 0) {
3307                FeatureInfo[] features = new FeatureInfo[size+1];
3308                featSet.toArray(features);
3309                FeatureInfo fi = new FeatureInfo();
3310                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3311                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3312                features[size] = fi;
3313                return features;
3314            }
3315        }
3316        return null;
3317    }
3318
3319    @Override
3320    public boolean hasSystemFeature(String name) {
3321        synchronized (mPackages) {
3322            return mAvailableFeatures.containsKey(name);
3323        }
3324    }
3325
3326    private void checkValidCaller(int uid, int userId) {
3327        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3328            return;
3329
3330        throw new SecurityException("Caller uid=" + uid
3331                + " is not privileged to communicate with user=" + userId);
3332    }
3333
3334    @Override
3335    public int checkPermission(String permName, String pkgName, int userId) {
3336        if (!sUserManager.exists(userId)) {
3337            return PackageManager.PERMISSION_DENIED;
3338        }
3339
3340        synchronized (mPackages) {
3341            final PackageParser.Package p = mPackages.get(pkgName);
3342            if (p != null && p.mExtras != null) {
3343                final PackageSetting ps = (PackageSetting) p.mExtras;
3344                final PermissionsState permissionsState = ps.getPermissionsState();
3345                if (permissionsState.hasPermission(permName, userId)) {
3346                    return PackageManager.PERMISSION_GRANTED;
3347                }
3348                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3349                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3350                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3351                    return PackageManager.PERMISSION_GRANTED;
3352                }
3353            }
3354        }
3355
3356        return PackageManager.PERMISSION_DENIED;
3357    }
3358
3359    @Override
3360    public int checkUidPermission(String permName, int uid) {
3361        final int userId = UserHandle.getUserId(uid);
3362
3363        if (!sUserManager.exists(userId)) {
3364            return PackageManager.PERMISSION_DENIED;
3365        }
3366
3367        synchronized (mPackages) {
3368            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3369            if (obj != null) {
3370                final SettingBase ps = (SettingBase) obj;
3371                final PermissionsState permissionsState = ps.getPermissionsState();
3372                if (permissionsState.hasPermission(permName, userId)) {
3373                    return PackageManager.PERMISSION_GRANTED;
3374                }
3375                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3376                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3377                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3378                    return PackageManager.PERMISSION_GRANTED;
3379                }
3380            } else {
3381                ArraySet<String> perms = mSystemPermissions.get(uid);
3382                if (perms != null) {
3383                    if (perms.contains(permName)) {
3384                        return PackageManager.PERMISSION_GRANTED;
3385                    }
3386                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3387                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3388                        return PackageManager.PERMISSION_GRANTED;
3389                    }
3390                }
3391            }
3392        }
3393
3394        return PackageManager.PERMISSION_DENIED;
3395    }
3396
3397    @Override
3398    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3399        if (UserHandle.getCallingUserId() != userId) {
3400            mContext.enforceCallingPermission(
3401                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3402                    "isPermissionRevokedByPolicy for user " + userId);
3403        }
3404
3405        if (checkPermission(permission, packageName, userId)
3406                == PackageManager.PERMISSION_GRANTED) {
3407            return false;
3408        }
3409
3410        final long identity = Binder.clearCallingIdentity();
3411        try {
3412            final int flags = getPermissionFlags(permission, packageName, userId);
3413            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3414        } finally {
3415            Binder.restoreCallingIdentity(identity);
3416        }
3417    }
3418
3419    @Override
3420    public String getPermissionControllerPackageName() {
3421        synchronized (mPackages) {
3422            return mRequiredInstallerPackage;
3423        }
3424    }
3425
3426    /**
3427     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3428     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3429     * @param checkShell TODO(yamasani):
3430     * @param message the message to log on security exception
3431     */
3432    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3433            boolean checkShell, String message) {
3434        if (userId < 0) {
3435            throw new IllegalArgumentException("Invalid userId " + userId);
3436        }
3437        if (checkShell) {
3438            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3439        }
3440        if (userId == UserHandle.getUserId(callingUid)) return;
3441        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3442            if (requireFullPermission) {
3443                mContext.enforceCallingOrSelfPermission(
3444                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3445            } else {
3446                try {
3447                    mContext.enforceCallingOrSelfPermission(
3448                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3449                } catch (SecurityException se) {
3450                    mContext.enforceCallingOrSelfPermission(
3451                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3452                }
3453            }
3454        }
3455    }
3456
3457    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3458        if (callingUid == Process.SHELL_UID) {
3459            if (userHandle >= 0
3460                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3461                throw new SecurityException("Shell does not have permission to access user "
3462                        + userHandle);
3463            } else if (userHandle < 0) {
3464                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3465                        + Debug.getCallers(3));
3466            }
3467        }
3468    }
3469
3470    private BasePermission findPermissionTreeLP(String permName) {
3471        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3472            if (permName.startsWith(bp.name) &&
3473                    permName.length() > bp.name.length() &&
3474                    permName.charAt(bp.name.length()) == '.') {
3475                return bp;
3476            }
3477        }
3478        return null;
3479    }
3480
3481    private BasePermission checkPermissionTreeLP(String permName) {
3482        if (permName != null) {
3483            BasePermission bp = findPermissionTreeLP(permName);
3484            if (bp != null) {
3485                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3486                    return bp;
3487                }
3488                throw new SecurityException("Calling uid "
3489                        + Binder.getCallingUid()
3490                        + " is not allowed to add to permission tree "
3491                        + bp.name + " owned by uid " + bp.uid);
3492            }
3493        }
3494        throw new SecurityException("No permission tree found for " + permName);
3495    }
3496
3497    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3498        if (s1 == null) {
3499            return s2 == null;
3500        }
3501        if (s2 == null) {
3502            return false;
3503        }
3504        if (s1.getClass() != s2.getClass()) {
3505            return false;
3506        }
3507        return s1.equals(s2);
3508    }
3509
3510    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3511        if (pi1.icon != pi2.icon) return false;
3512        if (pi1.logo != pi2.logo) return false;
3513        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3514        if (!compareStrings(pi1.name, pi2.name)) return false;
3515        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3516        // We'll take care of setting this one.
3517        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3518        // These are not currently stored in settings.
3519        //if (!compareStrings(pi1.group, pi2.group)) return false;
3520        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3521        //if (pi1.labelRes != pi2.labelRes) return false;
3522        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3523        return true;
3524    }
3525
3526    int permissionInfoFootprint(PermissionInfo info) {
3527        int size = info.name.length();
3528        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3529        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3530        return size;
3531    }
3532
3533    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3534        int size = 0;
3535        for (BasePermission perm : mSettings.mPermissions.values()) {
3536            if (perm.uid == tree.uid) {
3537                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3538            }
3539        }
3540        return size;
3541    }
3542
3543    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3544        // We calculate the max size of permissions defined by this uid and throw
3545        // if that plus the size of 'info' would exceed our stated maximum.
3546        if (tree.uid != Process.SYSTEM_UID) {
3547            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3548            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3549                throw new SecurityException("Permission tree size cap exceeded");
3550            }
3551        }
3552    }
3553
3554    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3555        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3556            throw new SecurityException("Label must be specified in permission");
3557        }
3558        BasePermission tree = checkPermissionTreeLP(info.name);
3559        BasePermission bp = mSettings.mPermissions.get(info.name);
3560        boolean added = bp == null;
3561        boolean changed = true;
3562        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3563        if (added) {
3564            enforcePermissionCapLocked(info, tree);
3565            bp = new BasePermission(info.name, tree.sourcePackage,
3566                    BasePermission.TYPE_DYNAMIC);
3567        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3568            throw new SecurityException(
3569                    "Not allowed to modify non-dynamic permission "
3570                    + info.name);
3571        } else {
3572            if (bp.protectionLevel == fixedLevel
3573                    && bp.perm.owner.equals(tree.perm.owner)
3574                    && bp.uid == tree.uid
3575                    && comparePermissionInfos(bp.perm.info, info)) {
3576                changed = false;
3577            }
3578        }
3579        bp.protectionLevel = fixedLevel;
3580        info = new PermissionInfo(info);
3581        info.protectionLevel = fixedLevel;
3582        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3583        bp.perm.info.packageName = tree.perm.info.packageName;
3584        bp.uid = tree.uid;
3585        if (added) {
3586            mSettings.mPermissions.put(info.name, bp);
3587        }
3588        if (changed) {
3589            if (!async) {
3590                mSettings.writeLPr();
3591            } else {
3592                scheduleWriteSettingsLocked();
3593            }
3594        }
3595        return added;
3596    }
3597
3598    @Override
3599    public boolean addPermission(PermissionInfo info) {
3600        synchronized (mPackages) {
3601            return addPermissionLocked(info, false);
3602        }
3603    }
3604
3605    @Override
3606    public boolean addPermissionAsync(PermissionInfo info) {
3607        synchronized (mPackages) {
3608            return addPermissionLocked(info, true);
3609        }
3610    }
3611
3612    @Override
3613    public void removePermission(String name) {
3614        synchronized (mPackages) {
3615            checkPermissionTreeLP(name);
3616            BasePermission bp = mSettings.mPermissions.get(name);
3617            if (bp != null) {
3618                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3619                    throw new SecurityException(
3620                            "Not allowed to modify non-dynamic permission "
3621                            + name);
3622                }
3623                mSettings.mPermissions.remove(name);
3624                mSettings.writeLPr();
3625            }
3626        }
3627    }
3628
3629    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3630            BasePermission bp) {
3631        int index = pkg.requestedPermissions.indexOf(bp.name);
3632        if (index == -1) {
3633            throw new SecurityException("Package " + pkg.packageName
3634                    + " has not requested permission " + bp.name);
3635        }
3636        if (!bp.isRuntime() && !bp.isDevelopment()) {
3637            throw new SecurityException("Permission " + bp.name
3638                    + " is not a changeable permission type");
3639        }
3640    }
3641
3642    @Override
3643    public void grantRuntimePermission(String packageName, String name, final int userId) {
3644        if (!sUserManager.exists(userId)) {
3645            Log.e(TAG, "No such user:" + userId);
3646            return;
3647        }
3648
3649        mContext.enforceCallingOrSelfPermission(
3650                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3651                "grantRuntimePermission");
3652
3653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3654                "grantRuntimePermission");
3655
3656        final int uid;
3657        final SettingBase sb;
3658
3659        synchronized (mPackages) {
3660            final PackageParser.Package pkg = mPackages.get(packageName);
3661            if (pkg == null) {
3662                throw new IllegalArgumentException("Unknown package: " + packageName);
3663            }
3664
3665            final BasePermission bp = mSettings.mPermissions.get(name);
3666            if (bp == null) {
3667                throw new IllegalArgumentException("Unknown permission: " + name);
3668            }
3669
3670            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3671
3672            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3673            sb = (SettingBase) pkg.mExtras;
3674            if (sb == null) {
3675                throw new IllegalArgumentException("Unknown package: " + packageName);
3676            }
3677
3678            final PermissionsState permissionsState = sb.getPermissionsState();
3679
3680            final int flags = permissionsState.getPermissionFlags(name, userId);
3681            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3682                throw new SecurityException("Cannot grant system fixed permission: "
3683                        + name + " for package: " + packageName);
3684            }
3685
3686            if (bp.isDevelopment()) {
3687                // Development permissions must be handled specially, since they are not
3688                // normal runtime permissions.  For now they apply to all users.
3689                if (permissionsState.grantInstallPermission(bp) !=
3690                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3691                    scheduleWriteSettingsLocked();
3692                }
3693                return;
3694            }
3695
3696            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3697                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3698                return;
3699            }
3700
3701            final int result = permissionsState.grantRuntimePermission(bp, userId);
3702            switch (result) {
3703                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3704                    return;
3705                }
3706
3707                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3708                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3709                    mHandler.post(new Runnable() {
3710                        @Override
3711                        public void run() {
3712                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3713                        }
3714                    });
3715                }
3716                break;
3717            }
3718
3719            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3720
3721            // Not critical if that is lost - app has to request again.
3722            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3723        }
3724
3725        // Only need to do this if user is initialized. Otherwise it's a new user
3726        // and there are no processes running as the user yet and there's no need
3727        // to make an expensive call to remount processes for the changed permissions.
3728        if (READ_EXTERNAL_STORAGE.equals(name)
3729                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3730            final long token = Binder.clearCallingIdentity();
3731            try {
3732                if (sUserManager.isInitialized(userId)) {
3733                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3734                            MountServiceInternal.class);
3735                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3736                }
3737            } finally {
3738                Binder.restoreCallingIdentity(token);
3739            }
3740        }
3741    }
3742
3743    @Override
3744    public void revokeRuntimePermission(String packageName, String name, int userId) {
3745        if (!sUserManager.exists(userId)) {
3746            Log.e(TAG, "No such user:" + userId);
3747            return;
3748        }
3749
3750        mContext.enforceCallingOrSelfPermission(
3751                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3752                "revokeRuntimePermission");
3753
3754        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3755                "revokeRuntimePermission");
3756
3757        final int appId;
3758
3759        synchronized (mPackages) {
3760            final PackageParser.Package pkg = mPackages.get(packageName);
3761            if (pkg == null) {
3762                throw new IllegalArgumentException("Unknown package: " + packageName);
3763            }
3764
3765            final BasePermission bp = mSettings.mPermissions.get(name);
3766            if (bp == null) {
3767                throw new IllegalArgumentException("Unknown permission: " + name);
3768            }
3769
3770            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3771
3772            SettingBase sb = (SettingBase) pkg.mExtras;
3773            if (sb == null) {
3774                throw new IllegalArgumentException("Unknown package: " + packageName);
3775            }
3776
3777            final PermissionsState permissionsState = sb.getPermissionsState();
3778
3779            final int flags = permissionsState.getPermissionFlags(name, userId);
3780            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3781                throw new SecurityException("Cannot revoke system fixed permission: "
3782                        + name + " for package: " + packageName);
3783            }
3784
3785            if (bp.isDevelopment()) {
3786                // Development permissions must be handled specially, since they are not
3787                // normal runtime permissions.  For now they apply to all users.
3788                if (permissionsState.revokeInstallPermission(bp) !=
3789                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3790                    scheduleWriteSettingsLocked();
3791                }
3792                return;
3793            }
3794
3795            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3796                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3797                return;
3798            }
3799
3800            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3801
3802            // Critical, after this call app should never have the permission.
3803            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3804
3805            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3806        }
3807
3808        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3809    }
3810
3811    @Override
3812    public void resetRuntimePermissions() {
3813        mContext.enforceCallingOrSelfPermission(
3814                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3815                "revokeRuntimePermission");
3816
3817        int callingUid = Binder.getCallingUid();
3818        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3819            mContext.enforceCallingOrSelfPermission(
3820                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3821                    "resetRuntimePermissions");
3822        }
3823
3824        synchronized (mPackages) {
3825            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3826            for (int userId : UserManagerService.getInstance().getUserIds()) {
3827                final int packageCount = mPackages.size();
3828                for (int i = 0; i < packageCount; i++) {
3829                    PackageParser.Package pkg = mPackages.valueAt(i);
3830                    if (!(pkg.mExtras instanceof PackageSetting)) {
3831                        continue;
3832                    }
3833                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3834                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3835                }
3836            }
3837        }
3838    }
3839
3840    @Override
3841    public int getPermissionFlags(String name, String packageName, int userId) {
3842        if (!sUserManager.exists(userId)) {
3843            return 0;
3844        }
3845
3846        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3847
3848        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3849                "getPermissionFlags");
3850
3851        synchronized (mPackages) {
3852            final PackageParser.Package pkg = mPackages.get(packageName);
3853            if (pkg == null) {
3854                throw new IllegalArgumentException("Unknown package: " + packageName);
3855            }
3856
3857            final BasePermission bp = mSettings.mPermissions.get(name);
3858            if (bp == null) {
3859                throw new IllegalArgumentException("Unknown permission: " + name);
3860            }
3861
3862            SettingBase sb = (SettingBase) pkg.mExtras;
3863            if (sb == null) {
3864                throw new IllegalArgumentException("Unknown package: " + packageName);
3865            }
3866
3867            PermissionsState permissionsState = sb.getPermissionsState();
3868            return permissionsState.getPermissionFlags(name, userId);
3869        }
3870    }
3871
3872    @Override
3873    public void updatePermissionFlags(String name, String packageName, int flagMask,
3874            int flagValues, int userId) {
3875        if (!sUserManager.exists(userId)) {
3876            return;
3877        }
3878
3879        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3880
3881        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3882                "updatePermissionFlags");
3883
3884        // Only the system can change these flags and nothing else.
3885        if (getCallingUid() != Process.SYSTEM_UID) {
3886            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3887            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3888            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3889            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3890        }
3891
3892        synchronized (mPackages) {
3893            final PackageParser.Package pkg = mPackages.get(packageName);
3894            if (pkg == null) {
3895                throw new IllegalArgumentException("Unknown package: " + packageName);
3896            }
3897
3898            final BasePermission bp = mSettings.mPermissions.get(name);
3899            if (bp == null) {
3900                throw new IllegalArgumentException("Unknown permission: " + name);
3901            }
3902
3903            SettingBase sb = (SettingBase) pkg.mExtras;
3904            if (sb == null) {
3905                throw new IllegalArgumentException("Unknown package: " + packageName);
3906            }
3907
3908            PermissionsState permissionsState = sb.getPermissionsState();
3909
3910            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3911
3912            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3913                // Install and runtime permissions are stored in different places,
3914                // so figure out what permission changed and persist the change.
3915                if (permissionsState.getInstallPermissionState(name) != null) {
3916                    scheduleWriteSettingsLocked();
3917                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3918                        || hadState) {
3919                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3920                }
3921            }
3922        }
3923    }
3924
3925    /**
3926     * Update the permission flags for all packages and runtime permissions of a user in order
3927     * to allow device or profile owner to remove POLICY_FIXED.
3928     */
3929    @Override
3930    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3931        if (!sUserManager.exists(userId)) {
3932            return;
3933        }
3934
3935        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3936
3937        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3938                "updatePermissionFlagsForAllApps");
3939
3940        // Only the system can change system fixed flags.
3941        if (getCallingUid() != Process.SYSTEM_UID) {
3942            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3943            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3944        }
3945
3946        synchronized (mPackages) {
3947            boolean changed = false;
3948            final int packageCount = mPackages.size();
3949            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3950                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3951                SettingBase sb = (SettingBase) pkg.mExtras;
3952                if (sb == null) {
3953                    continue;
3954                }
3955                PermissionsState permissionsState = sb.getPermissionsState();
3956                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3957                        userId, flagMask, flagValues);
3958            }
3959            if (changed) {
3960                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3961            }
3962        }
3963    }
3964
3965    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3966        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3967                != PackageManager.PERMISSION_GRANTED
3968            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3969                != PackageManager.PERMISSION_GRANTED) {
3970            throw new SecurityException(message + " requires "
3971                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3972                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3973        }
3974    }
3975
3976    @Override
3977    public boolean shouldShowRequestPermissionRationale(String permissionName,
3978            String packageName, int userId) {
3979        if (UserHandle.getCallingUserId() != userId) {
3980            mContext.enforceCallingPermission(
3981                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3982                    "canShowRequestPermissionRationale for user " + userId);
3983        }
3984
3985        final int uid = getPackageUid(packageName, userId);
3986        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3987            return false;
3988        }
3989
3990        if (checkPermission(permissionName, packageName, userId)
3991                == PackageManager.PERMISSION_GRANTED) {
3992            return false;
3993        }
3994
3995        final int flags;
3996
3997        final long identity = Binder.clearCallingIdentity();
3998        try {
3999            flags = getPermissionFlags(permissionName,
4000                    packageName, userId);
4001        } finally {
4002            Binder.restoreCallingIdentity(identity);
4003        }
4004
4005        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4006                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4007                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4008
4009        if ((flags & fixedFlags) != 0) {
4010            return false;
4011        }
4012
4013        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4014    }
4015
4016    @Override
4017    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4018        mContext.enforceCallingOrSelfPermission(
4019                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4020                "addOnPermissionsChangeListener");
4021
4022        synchronized (mPackages) {
4023            mOnPermissionChangeListeners.addListenerLocked(listener);
4024        }
4025    }
4026
4027    @Override
4028    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4029        synchronized (mPackages) {
4030            mOnPermissionChangeListeners.removeListenerLocked(listener);
4031        }
4032    }
4033
4034    @Override
4035    public boolean isProtectedBroadcast(String actionName) {
4036        synchronized (mPackages) {
4037            return mProtectedBroadcasts.contains(actionName);
4038        }
4039    }
4040
4041    @Override
4042    public int checkSignatures(String pkg1, String pkg2) {
4043        synchronized (mPackages) {
4044            final PackageParser.Package p1 = mPackages.get(pkg1);
4045            final PackageParser.Package p2 = mPackages.get(pkg2);
4046            if (p1 == null || p1.mExtras == null
4047                    || p2 == null || p2.mExtras == null) {
4048                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4049            }
4050            return compareSignatures(p1.mSignatures, p2.mSignatures);
4051        }
4052    }
4053
4054    @Override
4055    public int checkUidSignatures(int uid1, int uid2) {
4056        // Map to base uids.
4057        uid1 = UserHandle.getAppId(uid1);
4058        uid2 = UserHandle.getAppId(uid2);
4059        // reader
4060        synchronized (mPackages) {
4061            Signature[] s1;
4062            Signature[] s2;
4063            Object obj = mSettings.getUserIdLPr(uid1);
4064            if (obj != null) {
4065                if (obj instanceof SharedUserSetting) {
4066                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4067                } else if (obj instanceof PackageSetting) {
4068                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4069                } else {
4070                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4071                }
4072            } else {
4073                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4074            }
4075            obj = mSettings.getUserIdLPr(uid2);
4076            if (obj != null) {
4077                if (obj instanceof SharedUserSetting) {
4078                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4079                } else if (obj instanceof PackageSetting) {
4080                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4081                } else {
4082                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4083                }
4084            } else {
4085                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4086            }
4087            return compareSignatures(s1, s2);
4088        }
4089    }
4090
4091    private void killUid(int appId, int userId, String reason) {
4092        final long identity = Binder.clearCallingIdentity();
4093        try {
4094            IActivityManager am = ActivityManagerNative.getDefault();
4095            if (am != null) {
4096                try {
4097                    am.killUid(appId, userId, reason);
4098                } catch (RemoteException e) {
4099                    /* ignore - same process */
4100                }
4101            }
4102        } finally {
4103            Binder.restoreCallingIdentity(identity);
4104        }
4105    }
4106
4107    /**
4108     * Compares two sets of signatures. Returns:
4109     * <br />
4110     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4111     * <br />
4112     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4113     * <br />
4114     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4115     * <br />
4116     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4117     * <br />
4118     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4119     */
4120    static int compareSignatures(Signature[] s1, Signature[] s2) {
4121        if (s1 == null) {
4122            return s2 == null
4123                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4124                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4125        }
4126
4127        if (s2 == null) {
4128            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4129        }
4130
4131        if (s1.length != s2.length) {
4132            return PackageManager.SIGNATURE_NO_MATCH;
4133        }
4134
4135        // Since both signature sets are of size 1, we can compare without HashSets.
4136        if (s1.length == 1) {
4137            return s1[0].equals(s2[0]) ?
4138                    PackageManager.SIGNATURE_MATCH :
4139                    PackageManager.SIGNATURE_NO_MATCH;
4140        }
4141
4142        ArraySet<Signature> set1 = new ArraySet<Signature>();
4143        for (Signature sig : s1) {
4144            set1.add(sig);
4145        }
4146        ArraySet<Signature> set2 = new ArraySet<Signature>();
4147        for (Signature sig : s2) {
4148            set2.add(sig);
4149        }
4150        // Make sure s2 contains all signatures in s1.
4151        if (set1.equals(set2)) {
4152            return PackageManager.SIGNATURE_MATCH;
4153        }
4154        return PackageManager.SIGNATURE_NO_MATCH;
4155    }
4156
4157    /**
4158     * If the database version for this type of package (internal storage or
4159     * external storage) is less than the version where package signatures
4160     * were updated, return true.
4161     */
4162    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4163        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4164        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4165    }
4166
4167    /**
4168     * Used for backward compatibility to make sure any packages with
4169     * certificate chains get upgraded to the new style. {@code existingSigs}
4170     * will be in the old format (since they were stored on disk from before the
4171     * system upgrade) and {@code scannedSigs} will be in the newer format.
4172     */
4173    private int compareSignaturesCompat(PackageSignatures existingSigs,
4174            PackageParser.Package scannedPkg) {
4175        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4176            return PackageManager.SIGNATURE_NO_MATCH;
4177        }
4178
4179        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4180        for (Signature sig : existingSigs.mSignatures) {
4181            existingSet.add(sig);
4182        }
4183        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4184        for (Signature sig : scannedPkg.mSignatures) {
4185            try {
4186                Signature[] chainSignatures = sig.getChainSignatures();
4187                for (Signature chainSig : chainSignatures) {
4188                    scannedCompatSet.add(chainSig);
4189                }
4190            } catch (CertificateEncodingException e) {
4191                scannedCompatSet.add(sig);
4192            }
4193        }
4194        /*
4195         * Make sure the expanded scanned set contains all signatures in the
4196         * existing one.
4197         */
4198        if (scannedCompatSet.equals(existingSet)) {
4199            // Migrate the old signatures to the new scheme.
4200            existingSigs.assignSignatures(scannedPkg.mSignatures);
4201            // The new KeySets will be re-added later in the scanning process.
4202            synchronized (mPackages) {
4203                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4204            }
4205            return PackageManager.SIGNATURE_MATCH;
4206        }
4207        return PackageManager.SIGNATURE_NO_MATCH;
4208    }
4209
4210    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4211        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4212        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4213    }
4214
4215    private int compareSignaturesRecover(PackageSignatures existingSigs,
4216            PackageParser.Package scannedPkg) {
4217        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4218            return PackageManager.SIGNATURE_NO_MATCH;
4219        }
4220
4221        String msg = null;
4222        try {
4223            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4224                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4225                        + scannedPkg.packageName);
4226                return PackageManager.SIGNATURE_MATCH;
4227            }
4228        } catch (CertificateException e) {
4229            msg = e.getMessage();
4230        }
4231
4232        logCriticalInfo(Log.INFO,
4233                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4234        return PackageManager.SIGNATURE_NO_MATCH;
4235    }
4236
4237    @Override
4238    public String[] getPackagesForUid(int uid) {
4239        uid = UserHandle.getAppId(uid);
4240        // reader
4241        synchronized (mPackages) {
4242            Object obj = mSettings.getUserIdLPr(uid);
4243            if (obj instanceof SharedUserSetting) {
4244                final SharedUserSetting sus = (SharedUserSetting) obj;
4245                final int N = sus.packages.size();
4246                final String[] res = new String[N];
4247                final Iterator<PackageSetting> it = sus.packages.iterator();
4248                int i = 0;
4249                while (it.hasNext()) {
4250                    res[i++] = it.next().name;
4251                }
4252                return res;
4253            } else if (obj instanceof PackageSetting) {
4254                final PackageSetting ps = (PackageSetting) obj;
4255                return new String[] { ps.name };
4256            }
4257        }
4258        return null;
4259    }
4260
4261    @Override
4262    public String getNameForUid(int uid) {
4263        // reader
4264        synchronized (mPackages) {
4265            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4266            if (obj instanceof SharedUserSetting) {
4267                final SharedUserSetting sus = (SharedUserSetting) obj;
4268                return sus.name + ":" + sus.userId;
4269            } else if (obj instanceof PackageSetting) {
4270                final PackageSetting ps = (PackageSetting) obj;
4271                return ps.name;
4272            }
4273        }
4274        return null;
4275    }
4276
4277    @Override
4278    public int getUidForSharedUser(String sharedUserName) {
4279        if(sharedUserName == null) {
4280            return -1;
4281        }
4282        // reader
4283        synchronized (mPackages) {
4284            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4285            if (suid == null) {
4286                return -1;
4287            }
4288            return suid.userId;
4289        }
4290    }
4291
4292    @Override
4293    public int getFlagsForUid(int uid) {
4294        synchronized (mPackages) {
4295            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4296            if (obj instanceof SharedUserSetting) {
4297                final SharedUserSetting sus = (SharedUserSetting) obj;
4298                return sus.pkgFlags;
4299            } else if (obj instanceof PackageSetting) {
4300                final PackageSetting ps = (PackageSetting) obj;
4301                return ps.pkgFlags;
4302            }
4303        }
4304        return 0;
4305    }
4306
4307    @Override
4308    public int getPrivateFlagsForUid(int uid) {
4309        synchronized (mPackages) {
4310            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4311            if (obj instanceof SharedUserSetting) {
4312                final SharedUserSetting sus = (SharedUserSetting) obj;
4313                return sus.pkgPrivateFlags;
4314            } else if (obj instanceof PackageSetting) {
4315                final PackageSetting ps = (PackageSetting) obj;
4316                return ps.pkgPrivateFlags;
4317            }
4318        }
4319        return 0;
4320    }
4321
4322    @Override
4323    public boolean isUidPrivileged(int uid) {
4324        uid = UserHandle.getAppId(uid);
4325        // reader
4326        synchronized (mPackages) {
4327            Object obj = mSettings.getUserIdLPr(uid);
4328            if (obj instanceof SharedUserSetting) {
4329                final SharedUserSetting sus = (SharedUserSetting) obj;
4330                final Iterator<PackageSetting> it = sus.packages.iterator();
4331                while (it.hasNext()) {
4332                    if (it.next().isPrivileged()) {
4333                        return true;
4334                    }
4335                }
4336            } else if (obj instanceof PackageSetting) {
4337                final PackageSetting ps = (PackageSetting) obj;
4338                return ps.isPrivileged();
4339            }
4340        }
4341        return false;
4342    }
4343
4344    @Override
4345    public String[] getAppOpPermissionPackages(String permissionName) {
4346        synchronized (mPackages) {
4347            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4348            if (pkgs == null) {
4349                return null;
4350            }
4351            return pkgs.toArray(new String[pkgs.size()]);
4352        }
4353    }
4354
4355    @Override
4356    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4357            int flags, int userId) {
4358        if (!sUserManager.exists(userId)) return null;
4359        flags = augmentFlagsForUser(flags, userId);
4360        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4361        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4362        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4363    }
4364
4365    @Override
4366    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4367            IntentFilter filter, int match, ComponentName activity) {
4368        final int userId = UserHandle.getCallingUserId();
4369        if (DEBUG_PREFERRED) {
4370            Log.v(TAG, "setLastChosenActivity intent=" + intent
4371                + " resolvedType=" + resolvedType
4372                + " flags=" + flags
4373                + " filter=" + filter
4374                + " match=" + match
4375                + " activity=" + activity);
4376            filter.dump(new PrintStreamPrinter(System.out), "    ");
4377        }
4378        intent.setComponent(null);
4379        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4380        // Find any earlier preferred or last chosen entries and nuke them
4381        findPreferredActivity(intent, resolvedType,
4382                flags, query, 0, false, true, false, userId);
4383        // Add the new activity as the last chosen for this filter
4384        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4385                "Setting last chosen");
4386    }
4387
4388    @Override
4389    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4390        final int userId = UserHandle.getCallingUserId();
4391        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4392        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4393        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4394                false, false, false, userId);
4395    }
4396
4397    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4398        MessageDigest digest = null;
4399        try {
4400            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4401        } catch (NoSuchAlgorithmException e) {
4402            // If we can't create a digest, ignore ephemeral apps.
4403            return false;
4404        }
4405
4406        final byte[] hostBytes = intent.getData().getHost().getBytes();
4407        final byte[] digestBytes = digest.digest(hostBytes);
4408        int shaPrefix =
4409                digestBytes[0] << 24
4410                | digestBytes[1] << 16
4411                | digestBytes[2] << 8
4412                | digestBytes[3] << 0;
4413        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4414                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4415        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4416            // No hash prefix match; there are no ephemeral apps for this domain.
4417            return false;
4418        }
4419        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4420            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4421            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4422                continue;
4423            }
4424            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4425            // No filters; this should never happen.
4426            if (filters.isEmpty()) {
4427                continue;
4428            }
4429            // We have a domain match; resolve the filters to see if anything matches.
4430            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4431            for (int j = filters.size() - 1; j >= 0; --j) {
4432                ephemeralResolver.addFilter(filters.get(j));
4433            }
4434            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4435                    intent, resolvedType, false /*defaultOnly*/, userId);
4436            return !ephemeralResolveList.isEmpty();
4437        }
4438        // Hash or filter mis-match; no ephemeral apps for this domain.
4439        return false;
4440    }
4441
4442    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4443            int flags, List<ResolveInfo> query, int userId) {
4444        final boolean isWebUri = hasWebURI(intent);
4445        // Check whether or not an ephemeral app exists to handle the URI.
4446        if (isWebUri && mEphemeralResolverConnection != null) {
4447            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4448            boolean hasAlwaysHandler = false;
4449            synchronized (mPackages) {
4450                final int count = query.size();
4451                for (int n=0; n<count; n++) {
4452                    ResolveInfo info = query.get(n);
4453                    String packageName = info.activityInfo.packageName;
4454                    PackageSetting ps = mSettings.mPackages.get(packageName);
4455                    if (ps != null) {
4456                        // Try to get the status from User settings first
4457                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4458                        int status = (int) (packedStatus >> 32);
4459                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4460                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4461                            hasAlwaysHandler = true;
4462                            break;
4463                        }
4464                    }
4465                }
4466            }
4467
4468            // Only consider installing an ephemeral app if there isn't already a verified handler.
4469            // We've determined that there's an ephemeral app available for the URI, ignore any
4470            // ResolveInfo's and just return the ephemeral installer
4471            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4472                if (DEBUG_EPHEMERAL) {
4473                    Slog.v(TAG, "Resolving to the ephemeral installer");
4474                }
4475                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4476                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4477                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4478                // make a deep copy of the applicationInfo
4479                ri.activityInfo.applicationInfo = new ApplicationInfo(
4480                        ri.activityInfo.applicationInfo);
4481                if (userId != 0) {
4482                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4483                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4484                }
4485                return ri;
4486            }
4487        }
4488        if (query != null) {
4489            final int N = query.size();
4490            if (N == 1) {
4491                return query.get(0);
4492            } else if (N > 1) {
4493                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4494                // If there is more than one activity with the same priority,
4495                // then let the user decide between them.
4496                ResolveInfo r0 = query.get(0);
4497                ResolveInfo r1 = query.get(1);
4498                if (DEBUG_INTENT_MATCHING || debug) {
4499                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4500                            + r1.activityInfo.name + "=" + r1.priority);
4501                }
4502                // If the first activity has a higher priority, or a different
4503                // default, then it is always desireable to pick it.
4504                if (r0.priority != r1.priority
4505                        || r0.preferredOrder != r1.preferredOrder
4506                        || r0.isDefault != r1.isDefault) {
4507                    return query.get(0);
4508                }
4509                // If we have saved a preference for a preferred activity for
4510                // this Intent, use that.
4511                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4512                        flags, query, r0.priority, true, false, debug, userId);
4513                if (ri != null) {
4514                    return ri;
4515                }
4516                ri = new ResolveInfo(mResolveInfo);
4517                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4518                ri.activityInfo.applicationInfo = new ApplicationInfo(
4519                        ri.activityInfo.applicationInfo);
4520                if (userId != 0) {
4521                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4522                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4523                }
4524                // Make sure that the resolver is displayable in car mode
4525                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4526                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4527                return ri;
4528            }
4529        }
4530        return null;
4531    }
4532
4533    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4534            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4535        final int N = query.size();
4536        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4537                .get(userId);
4538        // Get the list of persistent preferred activities that handle the intent
4539        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4540        List<PersistentPreferredActivity> pprefs = ppir != null
4541                ? ppir.queryIntent(intent, resolvedType,
4542                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4543                : null;
4544        if (pprefs != null && pprefs.size() > 0) {
4545            final int M = pprefs.size();
4546            for (int i=0; i<M; i++) {
4547                final PersistentPreferredActivity ppa = pprefs.get(i);
4548                if (DEBUG_PREFERRED || debug) {
4549                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4550                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4551                            + "\n  component=" + ppa.mComponent);
4552                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4553                }
4554                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4555                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4556                if (DEBUG_PREFERRED || debug) {
4557                    Slog.v(TAG, "Found persistent preferred activity:");
4558                    if (ai != null) {
4559                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4560                    } else {
4561                        Slog.v(TAG, "  null");
4562                    }
4563                }
4564                if (ai == null) {
4565                    // This previously registered persistent preferred activity
4566                    // component is no longer known. Ignore it and do NOT remove it.
4567                    continue;
4568                }
4569                for (int j=0; j<N; j++) {
4570                    final ResolveInfo ri = query.get(j);
4571                    if (!ri.activityInfo.applicationInfo.packageName
4572                            .equals(ai.applicationInfo.packageName)) {
4573                        continue;
4574                    }
4575                    if (!ri.activityInfo.name.equals(ai.name)) {
4576                        continue;
4577                    }
4578                    //  Found a persistent preference that can handle the intent.
4579                    if (DEBUG_PREFERRED || debug) {
4580                        Slog.v(TAG, "Returning persistent preferred activity: " +
4581                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4582                    }
4583                    return ri;
4584                }
4585            }
4586        }
4587        return null;
4588    }
4589
4590    // TODO: handle preferred activities missing while user has amnesia
4591    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4592            List<ResolveInfo> query, int priority, boolean always,
4593            boolean removeMatches, boolean debug, int userId) {
4594        if (!sUserManager.exists(userId)) return null;
4595        flags = augmentFlagsForUser(flags, userId);
4596        // writer
4597        synchronized (mPackages) {
4598            if (intent.getSelector() != null) {
4599                intent = intent.getSelector();
4600            }
4601            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4602
4603            // Try to find a matching persistent preferred activity.
4604            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4605                    debug, userId);
4606
4607            // If a persistent preferred activity matched, use it.
4608            if (pri != null) {
4609                return pri;
4610            }
4611
4612            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4613            // Get the list of preferred activities that handle the intent
4614            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4615            List<PreferredActivity> prefs = pir != null
4616                    ? pir.queryIntent(intent, resolvedType,
4617                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4618                    : null;
4619            if (prefs != null && prefs.size() > 0) {
4620                boolean changed = false;
4621                try {
4622                    // First figure out how good the original match set is.
4623                    // We will only allow preferred activities that came
4624                    // from the same match quality.
4625                    int match = 0;
4626
4627                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4628
4629                    final int N = query.size();
4630                    for (int j=0; j<N; j++) {
4631                        final ResolveInfo ri = query.get(j);
4632                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4633                                + ": 0x" + Integer.toHexString(match));
4634                        if (ri.match > match) {
4635                            match = ri.match;
4636                        }
4637                    }
4638
4639                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4640                            + Integer.toHexString(match));
4641
4642                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4643                    final int M = prefs.size();
4644                    for (int i=0; i<M; i++) {
4645                        final PreferredActivity pa = prefs.get(i);
4646                        if (DEBUG_PREFERRED || debug) {
4647                            Slog.v(TAG, "Checking PreferredActivity ds="
4648                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4649                                    + "\n  component=" + pa.mPref.mComponent);
4650                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4651                        }
4652                        if (pa.mPref.mMatch != match) {
4653                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4654                                    + Integer.toHexString(pa.mPref.mMatch));
4655                            continue;
4656                        }
4657                        // If it's not an "always" type preferred activity and that's what we're
4658                        // looking for, skip it.
4659                        if (always && !pa.mPref.mAlways) {
4660                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4661                            continue;
4662                        }
4663                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4664                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4665                        if (DEBUG_PREFERRED || debug) {
4666                            Slog.v(TAG, "Found preferred activity:");
4667                            if (ai != null) {
4668                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4669                            } else {
4670                                Slog.v(TAG, "  null");
4671                            }
4672                        }
4673                        if (ai == null) {
4674                            // This previously registered preferred activity
4675                            // component is no longer known.  Most likely an update
4676                            // to the app was installed and in the new version this
4677                            // component no longer exists.  Clean it up by removing
4678                            // it from the preferred activities list, and skip it.
4679                            Slog.w(TAG, "Removing dangling preferred activity: "
4680                                    + pa.mPref.mComponent);
4681                            pir.removeFilter(pa);
4682                            changed = true;
4683                            continue;
4684                        }
4685                        for (int j=0; j<N; j++) {
4686                            final ResolveInfo ri = query.get(j);
4687                            if (!ri.activityInfo.applicationInfo.packageName
4688                                    .equals(ai.applicationInfo.packageName)) {
4689                                continue;
4690                            }
4691                            if (!ri.activityInfo.name.equals(ai.name)) {
4692                                continue;
4693                            }
4694
4695                            if (removeMatches) {
4696                                pir.removeFilter(pa);
4697                                changed = true;
4698                                if (DEBUG_PREFERRED) {
4699                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4700                                }
4701                                break;
4702                            }
4703
4704                            // Okay we found a previously set preferred or last chosen app.
4705                            // If the result set is different from when this
4706                            // was created, we need to clear it and re-ask the
4707                            // user their preference, if we're looking for an "always" type entry.
4708                            if (always && !pa.mPref.sameSet(query)) {
4709                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4710                                        + intent + " type " + resolvedType);
4711                                if (DEBUG_PREFERRED) {
4712                                    Slog.v(TAG, "Removing preferred activity since set changed "
4713                                            + pa.mPref.mComponent);
4714                                }
4715                                pir.removeFilter(pa);
4716                                // Re-add the filter as a "last chosen" entry (!always)
4717                                PreferredActivity lastChosen = new PreferredActivity(
4718                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4719                                pir.addFilter(lastChosen);
4720                                changed = true;
4721                                return null;
4722                            }
4723
4724                            // Yay! Either the set matched or we're looking for the last chosen
4725                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4726                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4727                            return ri;
4728                        }
4729                    }
4730                } finally {
4731                    if (changed) {
4732                        if (DEBUG_PREFERRED) {
4733                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4734                        }
4735                        scheduleWritePackageRestrictionsLocked(userId);
4736                    }
4737                }
4738            }
4739        }
4740        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4741        return null;
4742    }
4743
4744    /*
4745     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4746     */
4747    @Override
4748    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4749            int targetUserId) {
4750        mContext.enforceCallingOrSelfPermission(
4751                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4752        List<CrossProfileIntentFilter> matches =
4753                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4754        if (matches != null) {
4755            int size = matches.size();
4756            for (int i = 0; i < size; i++) {
4757                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4758            }
4759        }
4760        if (hasWebURI(intent)) {
4761            // cross-profile app linking works only towards the parent.
4762            final UserInfo parent = getProfileParent(sourceUserId);
4763            synchronized(mPackages) {
4764                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4765                        intent, resolvedType, 0, sourceUserId, parent.id);
4766                return xpDomainInfo != null;
4767            }
4768        }
4769        return false;
4770    }
4771
4772    private UserInfo getProfileParent(int userId) {
4773        final long identity = Binder.clearCallingIdentity();
4774        try {
4775            return sUserManager.getProfileParent(userId);
4776        } finally {
4777            Binder.restoreCallingIdentity(identity);
4778        }
4779    }
4780
4781    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4782            String resolvedType, int userId) {
4783        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4784        if (resolver != null) {
4785            return resolver.queryIntent(intent, resolvedType, false, userId);
4786        }
4787        return null;
4788    }
4789
4790    @Override
4791    public List<ResolveInfo> queryIntentActivities(Intent intent,
4792            String resolvedType, int flags, int userId) {
4793        if (!sUserManager.exists(userId)) return Collections.emptyList();
4794        flags = augmentFlagsForUser(flags, userId);
4795        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4796        ComponentName comp = intent.getComponent();
4797        if (comp == null) {
4798            if (intent.getSelector() != null) {
4799                intent = intent.getSelector();
4800                comp = intent.getComponent();
4801            }
4802        }
4803
4804        if (comp != null) {
4805            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4806            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4807            if (ai != null) {
4808                final ResolveInfo ri = new ResolveInfo();
4809                ri.activityInfo = ai;
4810                list.add(ri);
4811            }
4812            return list;
4813        }
4814
4815        // reader
4816        synchronized (mPackages) {
4817            final String pkgName = intent.getPackage();
4818            if (pkgName == null) {
4819                List<CrossProfileIntentFilter> matchingFilters =
4820                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4821                // Check for results that need to skip the current profile.
4822                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4823                        resolvedType, flags, userId);
4824                if (xpResolveInfo != null) {
4825                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4826                    result.add(xpResolveInfo);
4827                    return filterIfNotSystemUser(result, userId);
4828                }
4829
4830                // Check for results in the current profile.
4831                List<ResolveInfo> result = mActivities.queryIntent(
4832                        intent, resolvedType, flags, userId);
4833
4834                // Check for cross profile results.
4835                xpResolveInfo = queryCrossProfileIntents(
4836                        matchingFilters, intent, resolvedType, flags, userId);
4837                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4838                    result.add(xpResolveInfo);
4839                    Collections.sort(result, mResolvePrioritySorter);
4840                }
4841                result = filterIfNotSystemUser(result, userId);
4842                if (hasWebURI(intent)) {
4843                    CrossProfileDomainInfo xpDomainInfo = null;
4844                    final UserInfo parent = getProfileParent(userId);
4845                    if (parent != null) {
4846                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4847                                flags, userId, parent.id);
4848                    }
4849                    if (xpDomainInfo != null) {
4850                        if (xpResolveInfo != null) {
4851                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4852                            // in the result.
4853                            result.remove(xpResolveInfo);
4854                        }
4855                        if (result.size() == 0) {
4856                            result.add(xpDomainInfo.resolveInfo);
4857                            return result;
4858                        }
4859                    } else if (result.size() <= 1) {
4860                        return result;
4861                    }
4862                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4863                            xpDomainInfo, userId);
4864                    Collections.sort(result, mResolvePrioritySorter);
4865                }
4866                return result;
4867            }
4868            final PackageParser.Package pkg = mPackages.get(pkgName);
4869            if (pkg != null) {
4870                return filterIfNotSystemUser(
4871                        mActivities.queryIntentForPackage(
4872                                intent, resolvedType, flags, pkg.activities, userId),
4873                        userId);
4874            }
4875            return new ArrayList<ResolveInfo>();
4876        }
4877    }
4878
4879    private static class CrossProfileDomainInfo {
4880        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4881        ResolveInfo resolveInfo;
4882        /* Best domain verification status of the activities found in the other profile */
4883        int bestDomainVerificationStatus;
4884    }
4885
4886    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4887            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4888        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4889                sourceUserId)) {
4890            return null;
4891        }
4892        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4893                resolvedType, flags, parentUserId);
4894
4895        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4896            return null;
4897        }
4898        CrossProfileDomainInfo result = null;
4899        int size = resultTargetUser.size();
4900        for (int i = 0; i < size; i++) {
4901            ResolveInfo riTargetUser = resultTargetUser.get(i);
4902            // Intent filter verification is only for filters that specify a host. So don't return
4903            // those that handle all web uris.
4904            if (riTargetUser.handleAllWebDataURI) {
4905                continue;
4906            }
4907            String packageName = riTargetUser.activityInfo.packageName;
4908            PackageSetting ps = mSettings.mPackages.get(packageName);
4909            if (ps == null) {
4910                continue;
4911            }
4912            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4913            int status = (int)(verificationState >> 32);
4914            if (result == null) {
4915                result = new CrossProfileDomainInfo();
4916                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4917                        sourceUserId, parentUserId);
4918                result.bestDomainVerificationStatus = status;
4919            } else {
4920                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4921                        result.bestDomainVerificationStatus);
4922            }
4923        }
4924        // Don't consider matches with status NEVER across profiles.
4925        if (result != null && result.bestDomainVerificationStatus
4926                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4927            return null;
4928        }
4929        return result;
4930    }
4931
4932    /**
4933     * Verification statuses are ordered from the worse to the best, except for
4934     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4935     */
4936    private int bestDomainVerificationStatus(int status1, int status2) {
4937        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4938            return status2;
4939        }
4940        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4941            return status1;
4942        }
4943        return (int) MathUtils.max(status1, status2);
4944    }
4945
4946    private boolean isUserEnabled(int userId) {
4947        long callingId = Binder.clearCallingIdentity();
4948        try {
4949            UserInfo userInfo = sUserManager.getUserInfo(userId);
4950            return userInfo != null && userInfo.isEnabled();
4951        } finally {
4952            Binder.restoreCallingIdentity(callingId);
4953        }
4954    }
4955
4956    /**
4957     * Filter out activities with systemUserOnly flag set, when current user is not System.
4958     *
4959     * @return filtered list
4960     */
4961    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4962        if (userId == UserHandle.USER_SYSTEM) {
4963            return resolveInfos;
4964        }
4965        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4966            ResolveInfo info = resolveInfos.get(i);
4967            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4968                resolveInfos.remove(i);
4969            }
4970        }
4971        return resolveInfos;
4972    }
4973
4974    private static boolean hasWebURI(Intent intent) {
4975        if (intent.getData() == null) {
4976            return false;
4977        }
4978        final String scheme = intent.getScheme();
4979        if (TextUtils.isEmpty(scheme)) {
4980            return false;
4981        }
4982        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4983    }
4984
4985    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4986            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4987            int userId) {
4988        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4989
4990        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4991            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4992                    candidates.size());
4993        }
4994
4995        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4996        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4997        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4998        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4999        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5000        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5001
5002        synchronized (mPackages) {
5003            final int count = candidates.size();
5004            // First, try to use linked apps. Partition the candidates into four lists:
5005            // one for the final results, one for the "do not use ever", one for "undefined status"
5006            // and finally one for "browser app type".
5007            for (int n=0; n<count; n++) {
5008                ResolveInfo info = candidates.get(n);
5009                String packageName = info.activityInfo.packageName;
5010                PackageSetting ps = mSettings.mPackages.get(packageName);
5011                if (ps != null) {
5012                    // Add to the special match all list (Browser use case)
5013                    if (info.handleAllWebDataURI) {
5014                        matchAllList.add(info);
5015                        continue;
5016                    }
5017                    // Try to get the status from User settings first
5018                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5019                    int status = (int)(packedStatus >> 32);
5020                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5021                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5022                        if (DEBUG_DOMAIN_VERIFICATION) {
5023                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5024                                    + " : linkgen=" + linkGeneration);
5025                        }
5026                        // Use link-enabled generation as preferredOrder, i.e.
5027                        // prefer newly-enabled over earlier-enabled.
5028                        info.preferredOrder = linkGeneration;
5029                        alwaysList.add(info);
5030                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5031                        if (DEBUG_DOMAIN_VERIFICATION) {
5032                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5033                        }
5034                        neverList.add(info);
5035                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5036                        if (DEBUG_DOMAIN_VERIFICATION) {
5037                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5038                        }
5039                        alwaysAskList.add(info);
5040                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5041                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5042                        if (DEBUG_DOMAIN_VERIFICATION) {
5043                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5044                        }
5045                        undefinedList.add(info);
5046                    }
5047                }
5048            }
5049
5050            // We'll want to include browser possibilities in a few cases
5051            boolean includeBrowser = false;
5052
5053            // First try to add the "always" resolution(s) for the current user, if any
5054            if (alwaysList.size() > 0) {
5055                result.addAll(alwaysList);
5056            } else {
5057                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5058                result.addAll(undefinedList);
5059                // Maybe add one for the other profile.
5060                if (xpDomainInfo != null && (
5061                        xpDomainInfo.bestDomainVerificationStatus
5062                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5063                    result.add(xpDomainInfo.resolveInfo);
5064                }
5065                includeBrowser = true;
5066            }
5067
5068            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5069            // If there were 'always' entries their preferred order has been set, so we also
5070            // back that off to make the alternatives equivalent
5071            if (alwaysAskList.size() > 0) {
5072                for (ResolveInfo i : result) {
5073                    i.preferredOrder = 0;
5074                }
5075                result.addAll(alwaysAskList);
5076                includeBrowser = true;
5077            }
5078
5079            if (includeBrowser) {
5080                // Also add browsers (all of them or only the default one)
5081                if (DEBUG_DOMAIN_VERIFICATION) {
5082                    Slog.v(TAG, "   ...including browsers in candidate set");
5083                }
5084                if ((matchFlags & MATCH_ALL) != 0) {
5085                    result.addAll(matchAllList);
5086                } else {
5087                    // Browser/generic handling case.  If there's a default browser, go straight
5088                    // to that (but only if there is no other higher-priority match).
5089                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5090                    int maxMatchPrio = 0;
5091                    ResolveInfo defaultBrowserMatch = null;
5092                    final int numCandidates = matchAllList.size();
5093                    for (int n = 0; n < numCandidates; n++) {
5094                        ResolveInfo info = matchAllList.get(n);
5095                        // track the highest overall match priority...
5096                        if (info.priority > maxMatchPrio) {
5097                            maxMatchPrio = info.priority;
5098                        }
5099                        // ...and the highest-priority default browser match
5100                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5101                            if (defaultBrowserMatch == null
5102                                    || (defaultBrowserMatch.priority < info.priority)) {
5103                                if (debug) {
5104                                    Slog.v(TAG, "Considering default browser match " + info);
5105                                }
5106                                defaultBrowserMatch = info;
5107                            }
5108                        }
5109                    }
5110                    if (defaultBrowserMatch != null
5111                            && defaultBrowserMatch.priority >= maxMatchPrio
5112                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5113                    {
5114                        if (debug) {
5115                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5116                        }
5117                        result.add(defaultBrowserMatch);
5118                    } else {
5119                        result.addAll(matchAllList);
5120                    }
5121                }
5122
5123                // If there is nothing selected, add all candidates and remove the ones that the user
5124                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5125                if (result.size() == 0) {
5126                    result.addAll(candidates);
5127                    result.removeAll(neverList);
5128                }
5129            }
5130        }
5131        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5132            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5133                    result.size());
5134            for (ResolveInfo info : result) {
5135                Slog.v(TAG, "  + " + info.activityInfo);
5136            }
5137        }
5138        return result;
5139    }
5140
5141    // Returns a packed value as a long:
5142    //
5143    // high 'int'-sized word: link status: undefined/ask/never/always.
5144    // low 'int'-sized word: relative priority among 'always' results.
5145    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5146        long result = ps.getDomainVerificationStatusForUser(userId);
5147        // if none available, get the master status
5148        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5149            if (ps.getIntentFilterVerificationInfo() != null) {
5150                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5151            }
5152        }
5153        return result;
5154    }
5155
5156    private ResolveInfo querySkipCurrentProfileIntents(
5157            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5158            int flags, int sourceUserId) {
5159        if (matchingFilters != null) {
5160            int size = matchingFilters.size();
5161            for (int i = 0; i < size; i ++) {
5162                CrossProfileIntentFilter filter = matchingFilters.get(i);
5163                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5164                    // Checking if there are activities in the target user that can handle the
5165                    // intent.
5166                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5167                            resolvedType, flags, sourceUserId);
5168                    if (resolveInfo != null) {
5169                        return resolveInfo;
5170                    }
5171                }
5172            }
5173        }
5174        return null;
5175    }
5176
5177    // Return matching ResolveInfo if any for skip current profile intent filters.
5178    private ResolveInfo queryCrossProfileIntents(
5179            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5180            int flags, int sourceUserId) {
5181        if (matchingFilters != null) {
5182            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5183            // match the same intent. For performance reasons, it is better not to
5184            // run queryIntent twice for the same userId
5185            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5186            int size = matchingFilters.size();
5187            for (int i = 0; i < size; i++) {
5188                CrossProfileIntentFilter filter = matchingFilters.get(i);
5189                int targetUserId = filter.getTargetUserId();
5190                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
5191                        && !alreadyTriedUserIds.get(targetUserId)) {
5192                    // Checking if there are activities in the target user that can handle the
5193                    // intent.
5194                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5195                            resolvedType, flags, sourceUserId);
5196                    if (resolveInfo != null) return resolveInfo;
5197                    alreadyTriedUserIds.put(targetUserId, true);
5198                }
5199            }
5200        }
5201        return null;
5202    }
5203
5204    /**
5205     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5206     * will forward the intent to the filter's target user.
5207     * Otherwise, returns null.
5208     */
5209    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5210            String resolvedType, int flags, int sourceUserId) {
5211        int targetUserId = filter.getTargetUserId();
5212        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5213                resolvedType, flags, targetUserId);
5214        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5215                && isUserEnabled(targetUserId)) {
5216            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5217        }
5218        return null;
5219    }
5220
5221    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5222            int sourceUserId, int targetUserId) {
5223        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5224        long ident = Binder.clearCallingIdentity();
5225        boolean targetIsProfile;
5226        try {
5227            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5228        } finally {
5229            Binder.restoreCallingIdentity(ident);
5230        }
5231        String className;
5232        if (targetIsProfile) {
5233            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5234        } else {
5235            className = FORWARD_INTENT_TO_PARENT;
5236        }
5237        ComponentName forwardingActivityComponentName = new ComponentName(
5238                mAndroidApplication.packageName, className);
5239        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5240                sourceUserId);
5241        if (!targetIsProfile) {
5242            forwardingActivityInfo.showUserIcon = targetUserId;
5243            forwardingResolveInfo.noResourceId = true;
5244        }
5245        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5246        forwardingResolveInfo.priority = 0;
5247        forwardingResolveInfo.preferredOrder = 0;
5248        forwardingResolveInfo.match = 0;
5249        forwardingResolveInfo.isDefault = true;
5250        forwardingResolveInfo.filter = filter;
5251        forwardingResolveInfo.targetUserId = targetUserId;
5252        return forwardingResolveInfo;
5253    }
5254
5255    @Override
5256    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5257            Intent[] specifics, String[] specificTypes, Intent intent,
5258            String resolvedType, int flags, int userId) {
5259        if (!sUserManager.exists(userId)) return Collections.emptyList();
5260        flags = augmentFlagsForUser(flags, userId);
5261        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5262                false, "query intent activity options");
5263        final String resultsAction = intent.getAction();
5264
5265        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5266                | PackageManager.GET_RESOLVED_FILTER, userId);
5267
5268        if (DEBUG_INTENT_MATCHING) {
5269            Log.v(TAG, "Query " + intent + ": " + results);
5270        }
5271
5272        int specificsPos = 0;
5273        int N;
5274
5275        // todo: note that the algorithm used here is O(N^2).  This
5276        // isn't a problem in our current environment, but if we start running
5277        // into situations where we have more than 5 or 10 matches then this
5278        // should probably be changed to something smarter...
5279
5280        // First we go through and resolve each of the specific items
5281        // that were supplied, taking care of removing any corresponding
5282        // duplicate items in the generic resolve list.
5283        if (specifics != null) {
5284            for (int i=0; i<specifics.length; i++) {
5285                final Intent sintent = specifics[i];
5286                if (sintent == null) {
5287                    continue;
5288                }
5289
5290                if (DEBUG_INTENT_MATCHING) {
5291                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5292                }
5293
5294                String action = sintent.getAction();
5295                if (resultsAction != null && resultsAction.equals(action)) {
5296                    // If this action was explicitly requested, then don't
5297                    // remove things that have it.
5298                    action = null;
5299                }
5300
5301                ResolveInfo ri = null;
5302                ActivityInfo ai = null;
5303
5304                ComponentName comp = sintent.getComponent();
5305                if (comp == null) {
5306                    ri = resolveIntent(
5307                        sintent,
5308                        specificTypes != null ? specificTypes[i] : null,
5309                            flags, userId);
5310                    if (ri == null) {
5311                        continue;
5312                    }
5313                    if (ri == mResolveInfo) {
5314                        // ACK!  Must do something better with this.
5315                    }
5316                    ai = ri.activityInfo;
5317                    comp = new ComponentName(ai.applicationInfo.packageName,
5318                            ai.name);
5319                } else {
5320                    ai = getActivityInfo(comp, flags, userId);
5321                    if (ai == null) {
5322                        continue;
5323                    }
5324                }
5325
5326                // Look for any generic query activities that are duplicates
5327                // of this specific one, and remove them from the results.
5328                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5329                N = results.size();
5330                int j;
5331                for (j=specificsPos; j<N; j++) {
5332                    ResolveInfo sri = results.get(j);
5333                    if ((sri.activityInfo.name.equals(comp.getClassName())
5334                            && sri.activityInfo.applicationInfo.packageName.equals(
5335                                    comp.getPackageName()))
5336                        || (action != null && sri.filter.matchAction(action))) {
5337                        results.remove(j);
5338                        if (DEBUG_INTENT_MATCHING) Log.v(
5339                            TAG, "Removing duplicate item from " + j
5340                            + " due to specific " + specificsPos);
5341                        if (ri == null) {
5342                            ri = sri;
5343                        }
5344                        j--;
5345                        N--;
5346                    }
5347                }
5348
5349                // Add this specific item to its proper place.
5350                if (ri == null) {
5351                    ri = new ResolveInfo();
5352                    ri.activityInfo = ai;
5353                }
5354                results.add(specificsPos, ri);
5355                ri.specificIndex = i;
5356                specificsPos++;
5357            }
5358        }
5359
5360        // Now we go through the remaining generic results and remove any
5361        // duplicate actions that are found here.
5362        N = results.size();
5363        for (int i=specificsPos; i<N-1; i++) {
5364            final ResolveInfo rii = results.get(i);
5365            if (rii.filter == null) {
5366                continue;
5367            }
5368
5369            // Iterate over all of the actions of this result's intent
5370            // filter...  typically this should be just one.
5371            final Iterator<String> it = rii.filter.actionsIterator();
5372            if (it == null) {
5373                continue;
5374            }
5375            while (it.hasNext()) {
5376                final String action = it.next();
5377                if (resultsAction != null && resultsAction.equals(action)) {
5378                    // If this action was explicitly requested, then don't
5379                    // remove things that have it.
5380                    continue;
5381                }
5382                for (int j=i+1; j<N; j++) {
5383                    final ResolveInfo rij = results.get(j);
5384                    if (rij.filter != null && rij.filter.hasAction(action)) {
5385                        results.remove(j);
5386                        if (DEBUG_INTENT_MATCHING) Log.v(
5387                            TAG, "Removing duplicate item from " + j
5388                            + " due to action " + action + " at " + i);
5389                        j--;
5390                        N--;
5391                    }
5392                }
5393            }
5394
5395            // If the caller didn't request filter information, drop it now
5396            // so we don't have to marshall/unmarshall it.
5397            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5398                rii.filter = null;
5399            }
5400        }
5401
5402        // Filter out the caller activity if so requested.
5403        if (caller != null) {
5404            N = results.size();
5405            for (int i=0; i<N; i++) {
5406                ActivityInfo ainfo = results.get(i).activityInfo;
5407                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5408                        && caller.getClassName().equals(ainfo.name)) {
5409                    results.remove(i);
5410                    break;
5411                }
5412            }
5413        }
5414
5415        // If the caller didn't request filter information,
5416        // drop them now so we don't have to
5417        // marshall/unmarshall it.
5418        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5419            N = results.size();
5420            for (int i=0; i<N; i++) {
5421                results.get(i).filter = null;
5422            }
5423        }
5424
5425        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5426        return results;
5427    }
5428
5429    @Override
5430    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5431            int userId) {
5432        if (!sUserManager.exists(userId)) return Collections.emptyList();
5433        flags = augmentFlagsForUser(flags, userId);
5434        ComponentName comp = intent.getComponent();
5435        if (comp == null) {
5436            if (intent.getSelector() != null) {
5437                intent = intent.getSelector();
5438                comp = intent.getComponent();
5439            }
5440        }
5441        if (comp != null) {
5442            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5443            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5444            if (ai != null) {
5445                ResolveInfo ri = new ResolveInfo();
5446                ri.activityInfo = ai;
5447                list.add(ri);
5448            }
5449            return list;
5450        }
5451
5452        // reader
5453        synchronized (mPackages) {
5454            String pkgName = intent.getPackage();
5455            if (pkgName == null) {
5456                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5457            }
5458            final PackageParser.Package pkg = mPackages.get(pkgName);
5459            if (pkg != null) {
5460                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5461                        userId);
5462            }
5463            return null;
5464        }
5465    }
5466
5467    @Override
5468    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5469        if (!sUserManager.exists(userId)) return null;
5470        flags = augmentFlagsForUser(flags, userId);
5471        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5472        if (query != null) {
5473            if (query.size() >= 1) {
5474                // If there is more than one service with the same priority,
5475                // just arbitrarily pick the first one.
5476                return query.get(0);
5477            }
5478        }
5479        return null;
5480    }
5481
5482    @Override
5483    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5484            int userId) {
5485        if (!sUserManager.exists(userId)) return Collections.emptyList();
5486        flags = augmentFlagsForUser(flags, userId);
5487        ComponentName comp = intent.getComponent();
5488        if (comp == null) {
5489            if (intent.getSelector() != null) {
5490                intent = intent.getSelector();
5491                comp = intent.getComponent();
5492            }
5493        }
5494        if (comp != null) {
5495            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5496            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5497            if (si != null) {
5498                final ResolveInfo ri = new ResolveInfo();
5499                ri.serviceInfo = si;
5500                list.add(ri);
5501            }
5502            return list;
5503        }
5504
5505        // reader
5506        synchronized (mPackages) {
5507            String pkgName = intent.getPackage();
5508            if (pkgName == null) {
5509                return mServices.queryIntent(intent, resolvedType, flags, userId);
5510            }
5511            final PackageParser.Package pkg = mPackages.get(pkgName);
5512            if (pkg != null) {
5513                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5514                        userId);
5515            }
5516            return null;
5517        }
5518    }
5519
5520    @Override
5521    public List<ResolveInfo> queryIntentContentProviders(
5522            Intent intent, String resolvedType, int flags, int userId) {
5523        if (!sUserManager.exists(userId)) return Collections.emptyList();
5524        flags = augmentFlagsForUser(flags, userId);
5525        ComponentName comp = intent.getComponent();
5526        if (comp == null) {
5527            if (intent.getSelector() != null) {
5528                intent = intent.getSelector();
5529                comp = intent.getComponent();
5530            }
5531        }
5532        if (comp != null) {
5533            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5534            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5535            if (pi != null) {
5536                final ResolveInfo ri = new ResolveInfo();
5537                ri.providerInfo = pi;
5538                list.add(ri);
5539            }
5540            return list;
5541        }
5542
5543        // reader
5544        synchronized (mPackages) {
5545            String pkgName = intent.getPackage();
5546            if (pkgName == null) {
5547                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5548            }
5549            final PackageParser.Package pkg = mPackages.get(pkgName);
5550            if (pkg != null) {
5551                return mProviders.queryIntentForPackage(
5552                        intent, resolvedType, flags, pkg.providers, userId);
5553            }
5554            return null;
5555        }
5556    }
5557
5558    @Override
5559    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5560        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5561
5562        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5563
5564        // writer
5565        synchronized (mPackages) {
5566            ArrayList<PackageInfo> list;
5567            if (listUninstalled) {
5568                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5569                for (PackageSetting ps : mSettings.mPackages.values()) {
5570                    PackageInfo pi;
5571                    if (ps.pkg != null) {
5572                        pi = generatePackageInfo(ps.pkg, flags, userId);
5573                    } else {
5574                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5575                    }
5576                    if (pi != null) {
5577                        list.add(pi);
5578                    }
5579                }
5580            } else {
5581                list = new ArrayList<PackageInfo>(mPackages.size());
5582                for (PackageParser.Package p : mPackages.values()) {
5583                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5584                    if (pi != null) {
5585                        list.add(pi);
5586                    }
5587                }
5588            }
5589
5590            return new ParceledListSlice<PackageInfo>(list);
5591        }
5592    }
5593
5594    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5595            String[] permissions, boolean[] tmp, int flags, int userId) {
5596        int numMatch = 0;
5597        final PermissionsState permissionsState = ps.getPermissionsState();
5598        for (int i=0; i<permissions.length; i++) {
5599            final String permission = permissions[i];
5600            if (permissionsState.hasPermission(permission, userId)) {
5601                tmp[i] = true;
5602                numMatch++;
5603            } else {
5604                tmp[i] = false;
5605            }
5606        }
5607        if (numMatch == 0) {
5608            return;
5609        }
5610        PackageInfo pi;
5611        if (ps.pkg != null) {
5612            pi = generatePackageInfo(ps.pkg, flags, userId);
5613        } else {
5614            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5615        }
5616        // The above might return null in cases of uninstalled apps or install-state
5617        // skew across users/profiles.
5618        if (pi != null) {
5619            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5620                if (numMatch == permissions.length) {
5621                    pi.requestedPermissions = permissions;
5622                } else {
5623                    pi.requestedPermissions = new String[numMatch];
5624                    numMatch = 0;
5625                    for (int i=0; i<permissions.length; i++) {
5626                        if (tmp[i]) {
5627                            pi.requestedPermissions[numMatch] = permissions[i];
5628                            numMatch++;
5629                        }
5630                    }
5631                }
5632            }
5633            list.add(pi);
5634        }
5635    }
5636
5637    @Override
5638    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5639            String[] permissions, int flags, int userId) {
5640        if (!sUserManager.exists(userId)) return null;
5641        flags = augmentFlagsForUser(flags, userId);
5642        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5643
5644        // writer
5645        synchronized (mPackages) {
5646            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5647            boolean[] tmpBools = new boolean[permissions.length];
5648            if (listUninstalled) {
5649                for (PackageSetting ps : mSettings.mPackages.values()) {
5650                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5651                }
5652            } else {
5653                for (PackageParser.Package pkg : mPackages.values()) {
5654                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5655                    if (ps != null) {
5656                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5657                                userId);
5658                    }
5659                }
5660            }
5661
5662            return new ParceledListSlice<PackageInfo>(list);
5663        }
5664    }
5665
5666    @Override
5667    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5668        if (!sUserManager.exists(userId)) return null;
5669        flags = augmentFlagsForUser(flags, userId);
5670        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5671
5672        // writer
5673        synchronized (mPackages) {
5674            ArrayList<ApplicationInfo> list;
5675            if (listUninstalled) {
5676                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5677                for (PackageSetting ps : mSettings.mPackages.values()) {
5678                    ApplicationInfo ai;
5679                    if (ps.pkg != null) {
5680                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5681                                ps.readUserState(userId), userId);
5682                    } else {
5683                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5684                    }
5685                    if (ai != null) {
5686                        list.add(ai);
5687                    }
5688                }
5689            } else {
5690                list = new ArrayList<ApplicationInfo>(mPackages.size());
5691                for (PackageParser.Package p : mPackages.values()) {
5692                    if (p.mExtras != null) {
5693                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5694                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5695                        if (ai != null) {
5696                            list.add(ai);
5697                        }
5698                    }
5699                }
5700            }
5701
5702            return new ParceledListSlice<ApplicationInfo>(list);
5703        }
5704    }
5705
5706    public List<ApplicationInfo> getPersistentApplications(int flags) {
5707        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5708
5709        // reader
5710        synchronized (mPackages) {
5711            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5712            final int userId = UserHandle.getCallingUserId();
5713            while (i.hasNext()) {
5714                final PackageParser.Package p = i.next();
5715                if (p.applicationInfo != null
5716                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5717                        && (!mSafeMode || isSystemApp(p))) {
5718                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5719                    if (ps != null) {
5720                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5721                                ps.readUserState(userId), userId);
5722                        if (ai != null) {
5723                            finalList.add(ai);
5724                        }
5725                    }
5726                }
5727            }
5728        }
5729
5730        return finalList;
5731    }
5732
5733    @Override
5734    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5735        if (!sUserManager.exists(userId)) return null;
5736        flags = augmentFlagsForUser(flags, userId);
5737        // reader
5738        synchronized (mPackages) {
5739            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5740            PackageSetting ps = provider != null
5741                    ? mSettings.mPackages.get(provider.owner.packageName)
5742                    : null;
5743            return ps != null
5744                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5745                    && (!mSafeMode || (provider.info.applicationInfo.flags
5746                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5747                    ? PackageParser.generateProviderInfo(provider, flags,
5748                            ps.readUserState(userId), userId)
5749                    : null;
5750        }
5751    }
5752
5753    /**
5754     * @deprecated
5755     */
5756    @Deprecated
5757    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5758        // reader
5759        synchronized (mPackages) {
5760            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5761                    .entrySet().iterator();
5762            final int userId = UserHandle.getCallingUserId();
5763            while (i.hasNext()) {
5764                Map.Entry<String, PackageParser.Provider> entry = i.next();
5765                PackageParser.Provider p = entry.getValue();
5766                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5767
5768                if (ps != null && p.syncable
5769                        && (!mSafeMode || (p.info.applicationInfo.flags
5770                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5771                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5772                            ps.readUserState(userId), userId);
5773                    if (info != null) {
5774                        outNames.add(entry.getKey());
5775                        outInfo.add(info);
5776                    }
5777                }
5778            }
5779        }
5780    }
5781
5782    @Override
5783    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5784            int uid, int flags) {
5785        final int userId = processName != null ? UserHandle.getUserId(uid)
5786                : UserHandle.getCallingUserId();
5787        if (!sUserManager.exists(userId)) return null;
5788        flags = augmentFlagsForUser(flags, userId);
5789
5790        ArrayList<ProviderInfo> finalList = null;
5791        // reader
5792        synchronized (mPackages) {
5793            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5794            while (i.hasNext()) {
5795                final PackageParser.Provider p = i.next();
5796                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5797                if (ps != null && p.info.authority != null
5798                        && (processName == null
5799                                || (p.info.processName.equals(processName)
5800                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5801                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5802                        && (!mSafeMode
5803                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5804                    if (finalList == null) {
5805                        finalList = new ArrayList<ProviderInfo>(3);
5806                    }
5807                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5808                            ps.readUserState(userId), userId);
5809                    if (info != null) {
5810                        finalList.add(info);
5811                    }
5812                }
5813            }
5814        }
5815
5816        if (finalList != null) {
5817            Collections.sort(finalList, mProviderInitOrderSorter);
5818            return new ParceledListSlice<ProviderInfo>(finalList);
5819        }
5820
5821        return null;
5822    }
5823
5824    @Override
5825    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5826            int flags) {
5827        // reader
5828        synchronized (mPackages) {
5829            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5830            return PackageParser.generateInstrumentationInfo(i, flags);
5831        }
5832    }
5833
5834    @Override
5835    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5836            int flags) {
5837        ArrayList<InstrumentationInfo> finalList =
5838            new ArrayList<InstrumentationInfo>();
5839
5840        // reader
5841        synchronized (mPackages) {
5842            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5843            while (i.hasNext()) {
5844                final PackageParser.Instrumentation p = i.next();
5845                if (targetPackage == null
5846                        || targetPackage.equals(p.info.targetPackage)) {
5847                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5848                            flags);
5849                    if (ii != null) {
5850                        finalList.add(ii);
5851                    }
5852                }
5853            }
5854        }
5855
5856        return finalList;
5857    }
5858
5859    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5860        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5861        if (overlays == null) {
5862            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5863            return;
5864        }
5865        for (PackageParser.Package opkg : overlays.values()) {
5866            // Not much to do if idmap fails: we already logged the error
5867            // and we certainly don't want to abort installation of pkg simply
5868            // because an overlay didn't fit properly. For these reasons,
5869            // ignore the return value of createIdmapForPackagePairLI.
5870            createIdmapForPackagePairLI(pkg, opkg);
5871        }
5872    }
5873
5874    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5875            PackageParser.Package opkg) {
5876        if (!opkg.mTrustedOverlay) {
5877            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5878                    opkg.baseCodePath + ": overlay not trusted");
5879            return false;
5880        }
5881        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5882        if (overlaySet == null) {
5883            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5884                    opkg.baseCodePath + " but target package has no known overlays");
5885            return false;
5886        }
5887        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5888        // TODO: generate idmap for split APKs
5889        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5890            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5891                    + opkg.baseCodePath);
5892            return false;
5893        }
5894        PackageParser.Package[] overlayArray =
5895            overlaySet.values().toArray(new PackageParser.Package[0]);
5896        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5897            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5898                return p1.mOverlayPriority - p2.mOverlayPriority;
5899            }
5900        };
5901        Arrays.sort(overlayArray, cmp);
5902
5903        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5904        int i = 0;
5905        for (PackageParser.Package p : overlayArray) {
5906            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5907        }
5908        return true;
5909    }
5910
5911    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5912        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5913        try {
5914            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5915        } finally {
5916            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5917        }
5918    }
5919
5920    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5921        final File[] files = dir.listFiles();
5922        if (ArrayUtils.isEmpty(files)) {
5923            Log.d(TAG, "No files in app dir " + dir);
5924            return;
5925        }
5926
5927        if (DEBUG_PACKAGE_SCANNING) {
5928            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5929                    + " flags=0x" + Integer.toHexString(parseFlags));
5930        }
5931
5932        for (File file : files) {
5933            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5934                    && !PackageInstallerService.isStageName(file.getName());
5935            if (!isPackage) {
5936                // Ignore entries which are not packages
5937                continue;
5938            }
5939            try {
5940                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5941                        scanFlags, currentTime, null);
5942            } catch (PackageManagerException e) {
5943                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5944
5945                // Delete invalid userdata apps
5946                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5947                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5948                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5949                    if (file.isDirectory()) {
5950                        mInstaller.rmPackageDir(file.getAbsolutePath());
5951                    } else {
5952                        file.delete();
5953                    }
5954                }
5955            }
5956        }
5957    }
5958
5959    private static File getSettingsProblemFile() {
5960        File dataDir = Environment.getDataDirectory();
5961        File systemDir = new File(dataDir, "system");
5962        File fname = new File(systemDir, "uiderrors.txt");
5963        return fname;
5964    }
5965
5966    static void reportSettingsProblem(int priority, String msg) {
5967        logCriticalInfo(priority, msg);
5968    }
5969
5970    static void logCriticalInfo(int priority, String msg) {
5971        Slog.println(priority, TAG, msg);
5972        EventLogTags.writePmCriticalInfo(msg);
5973        try {
5974            File fname = getSettingsProblemFile();
5975            FileOutputStream out = new FileOutputStream(fname, true);
5976            PrintWriter pw = new FastPrintWriter(out);
5977            SimpleDateFormat formatter = new SimpleDateFormat();
5978            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5979            pw.println(dateString + ": " + msg);
5980            pw.close();
5981            FileUtils.setPermissions(
5982                    fname.toString(),
5983                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5984                    -1, -1);
5985        } catch (java.io.IOException e) {
5986        }
5987    }
5988
5989    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5990            PackageParser.Package pkg, File srcFile, int parseFlags)
5991            throws PackageManagerException {
5992        if (ps != null
5993                && ps.codePath.equals(srcFile)
5994                && ps.timeStamp == srcFile.lastModified()
5995                && !isCompatSignatureUpdateNeeded(pkg)
5996                && !isRecoverSignatureUpdateNeeded(pkg)) {
5997            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5998            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5999            ArraySet<PublicKey> signingKs;
6000            synchronized (mPackages) {
6001                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6002            }
6003            if (ps.signatures.mSignatures != null
6004                    && ps.signatures.mSignatures.length != 0
6005                    && signingKs != null) {
6006                // Optimization: reuse the existing cached certificates
6007                // if the package appears to be unchanged.
6008                pkg.mSignatures = ps.signatures.mSignatures;
6009                pkg.mSigningKeys = signingKs;
6010                return;
6011            }
6012
6013            Slog.w(TAG, "PackageSetting for " + ps.name
6014                    + " is missing signatures.  Collecting certs again to recover them.");
6015        } else {
6016            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6017        }
6018
6019        try {
6020            pp.collectCertificates(pkg, parseFlags);
6021            pp.collectManifestDigest(pkg);
6022        } catch (PackageParserException e) {
6023            throw PackageManagerException.from(e);
6024        }
6025    }
6026
6027    /**
6028     *  Traces a package scan.
6029     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6030     */
6031    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6032            long currentTime, UserHandle user) throws PackageManagerException {
6033        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6034        try {
6035            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6036        } finally {
6037            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6038        }
6039    }
6040
6041    /**
6042     *  Scans a package and returns the newly parsed package.
6043     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6044     */
6045    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6046            long currentTime, UserHandle user) throws PackageManagerException {
6047        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6048        parseFlags |= mDefParseFlags;
6049        PackageParser pp = new PackageParser();
6050        pp.setSeparateProcesses(mSeparateProcesses);
6051        pp.setOnlyCoreApps(mOnlyCore);
6052        pp.setDisplayMetrics(mMetrics);
6053
6054        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6055            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6056        }
6057
6058        final PackageParser.Package pkg;
6059        try {
6060            pkg = pp.parsePackage(scanFile, parseFlags);
6061        } catch (PackageParserException e) {
6062            throw PackageManagerException.from(e);
6063        }
6064
6065        PackageSetting ps = null;
6066        PackageSetting updatedPkg;
6067        // reader
6068        synchronized (mPackages) {
6069            // Look to see if we already know about this package.
6070            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6071            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6072                // This package has been renamed to its original name.  Let's
6073                // use that.
6074                ps = mSettings.peekPackageLPr(oldName);
6075            }
6076            // If there was no original package, see one for the real package name.
6077            if (ps == null) {
6078                ps = mSettings.peekPackageLPr(pkg.packageName);
6079            }
6080            // Check to see if this package could be hiding/updating a system
6081            // package.  Must look for it either under the original or real
6082            // package name depending on our state.
6083            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6084            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6085        }
6086        boolean updatedPkgBetter = false;
6087        // First check if this is a system package that may involve an update
6088        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6089            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6090            // it needs to drop FLAG_PRIVILEGED.
6091            if (locationIsPrivileged(scanFile)) {
6092                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6093            } else {
6094                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6095            }
6096
6097            if (ps != null && !ps.codePath.equals(scanFile)) {
6098                // The path has changed from what was last scanned...  check the
6099                // version of the new path against what we have stored to determine
6100                // what to do.
6101                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6102                if (pkg.mVersionCode <= ps.versionCode) {
6103                    // The system package has been updated and the code path does not match
6104                    // Ignore entry. Skip it.
6105                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6106                            + " ignored: updated version " + ps.versionCode
6107                            + " better than this " + pkg.mVersionCode);
6108                    if (!updatedPkg.codePath.equals(scanFile)) {
6109                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6110                                + ps.name + " changing from " + updatedPkg.codePathString
6111                                + " to " + scanFile);
6112                        updatedPkg.codePath = scanFile;
6113                        updatedPkg.codePathString = scanFile.toString();
6114                        updatedPkg.resourcePath = scanFile;
6115                        updatedPkg.resourcePathString = scanFile.toString();
6116                    }
6117                    updatedPkg.pkg = pkg;
6118                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6119                            "Package " + ps.name + " at " + scanFile
6120                                    + " ignored: updated version " + ps.versionCode
6121                                    + " better than this " + pkg.mVersionCode);
6122                } else {
6123                    // The current app on the system partition is better than
6124                    // what we have updated to on the data partition; switch
6125                    // back to the system partition version.
6126                    // At this point, its safely assumed that package installation for
6127                    // apps in system partition will go through. If not there won't be a working
6128                    // version of the app
6129                    // writer
6130                    synchronized (mPackages) {
6131                        // Just remove the loaded entries from package lists.
6132                        mPackages.remove(ps.name);
6133                    }
6134
6135                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6136                            + " reverting from " + ps.codePathString
6137                            + ": new version " + pkg.mVersionCode
6138                            + " better than installed " + ps.versionCode);
6139
6140                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6141                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6142                    synchronized (mInstallLock) {
6143                        args.cleanUpResourcesLI();
6144                    }
6145                    synchronized (mPackages) {
6146                        mSettings.enableSystemPackageLPw(ps.name);
6147                    }
6148                    updatedPkgBetter = true;
6149                }
6150            }
6151        }
6152
6153        if (updatedPkg != null) {
6154            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6155            // initially
6156            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6157
6158            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6159            // flag set initially
6160            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6161                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6162            }
6163        }
6164
6165        // Verify certificates against what was last scanned
6166        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6167
6168        /*
6169         * A new system app appeared, but we already had a non-system one of the
6170         * same name installed earlier.
6171         */
6172        boolean shouldHideSystemApp = false;
6173        if (updatedPkg == null && ps != null
6174                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6175            /*
6176             * Check to make sure the signatures match first. If they don't,
6177             * wipe the installed application and its data.
6178             */
6179            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6180                    != PackageManager.SIGNATURE_MATCH) {
6181                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6182                        + " signatures don't match existing userdata copy; removing");
6183                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6184                ps = null;
6185            } else {
6186                /*
6187                 * If the newly-added system app is an older version than the
6188                 * already installed version, hide it. It will be scanned later
6189                 * and re-added like an update.
6190                 */
6191                if (pkg.mVersionCode <= ps.versionCode) {
6192                    shouldHideSystemApp = true;
6193                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6194                            + " but new version " + pkg.mVersionCode + " better than installed "
6195                            + ps.versionCode + "; hiding system");
6196                } else {
6197                    /*
6198                     * The newly found system app is a newer version that the
6199                     * one previously installed. Simply remove the
6200                     * already-installed application and replace it with our own
6201                     * while keeping the application data.
6202                     */
6203                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6204                            + " reverting from " + ps.codePathString + ": new version "
6205                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6206                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6207                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6208                    synchronized (mInstallLock) {
6209                        args.cleanUpResourcesLI();
6210                    }
6211                }
6212            }
6213        }
6214
6215        // The apk is forward locked (not public) if its code and resources
6216        // are kept in different files. (except for app in either system or
6217        // vendor path).
6218        // TODO grab this value from PackageSettings
6219        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6220            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6221                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6222            }
6223        }
6224
6225        // TODO: extend to support forward-locked splits
6226        String resourcePath = null;
6227        String baseResourcePath = null;
6228        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6229            if (ps != null && ps.resourcePathString != null) {
6230                resourcePath = ps.resourcePathString;
6231                baseResourcePath = ps.resourcePathString;
6232            } else {
6233                // Should not happen at all. Just log an error.
6234                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6235            }
6236        } else {
6237            resourcePath = pkg.codePath;
6238            baseResourcePath = pkg.baseCodePath;
6239        }
6240
6241        // Set application objects path explicitly.
6242        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6243        pkg.applicationInfo.setCodePath(pkg.codePath);
6244        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6245        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6246        pkg.applicationInfo.setResourcePath(resourcePath);
6247        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6248        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6249
6250        // Note that we invoke the following method only if we are about to unpack an application
6251        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6252                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6253
6254        /*
6255         * If the system app should be overridden by a previously installed
6256         * data, hide the system app now and let the /data/app scan pick it up
6257         * again.
6258         */
6259        if (shouldHideSystemApp) {
6260            synchronized (mPackages) {
6261                mSettings.disableSystemPackageLPw(pkg.packageName);
6262            }
6263        }
6264
6265        return scannedPkg;
6266    }
6267
6268    private static String fixProcessName(String defProcessName,
6269            String processName, int uid) {
6270        if (processName == null) {
6271            return defProcessName;
6272        }
6273        return processName;
6274    }
6275
6276    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6277            throws PackageManagerException {
6278        if (pkgSetting.signatures.mSignatures != null) {
6279            // Already existing package. Make sure signatures match
6280            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6281                    == PackageManager.SIGNATURE_MATCH;
6282            if (!match) {
6283                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6284                        == PackageManager.SIGNATURE_MATCH;
6285            }
6286            if (!match) {
6287                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6288                        == PackageManager.SIGNATURE_MATCH;
6289            }
6290            if (!match) {
6291                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6292                        + pkg.packageName + " signatures do not match the "
6293                        + "previously installed version; ignoring!");
6294            }
6295        }
6296
6297        // Check for shared user signatures
6298        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6299            // Already existing package. Make sure signatures match
6300            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6301                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6302            if (!match) {
6303                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6304                        == PackageManager.SIGNATURE_MATCH;
6305            }
6306            if (!match) {
6307                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6308                        == PackageManager.SIGNATURE_MATCH;
6309            }
6310            if (!match) {
6311                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6312                        "Package " + pkg.packageName
6313                        + " has no signatures that match those in shared user "
6314                        + pkgSetting.sharedUser.name + "; ignoring!");
6315            }
6316        }
6317    }
6318
6319    /**
6320     * Enforces that only the system UID or root's UID can call a method exposed
6321     * via Binder.
6322     *
6323     * @param message used as message if SecurityException is thrown
6324     * @throws SecurityException if the caller is not system or root
6325     */
6326    private static final void enforceSystemOrRoot(String message) {
6327        final int uid = Binder.getCallingUid();
6328        if (uid != Process.SYSTEM_UID && uid != 0) {
6329            throw new SecurityException(message);
6330        }
6331    }
6332
6333    @Override
6334    public void performFstrimIfNeeded() {
6335        enforceSystemOrRoot("Only the system can request fstrim");
6336
6337        // Before everything else, see whether we need to fstrim.
6338        try {
6339            IMountService ms = PackageHelper.getMountService();
6340            if (ms != null) {
6341                final boolean isUpgrade = isUpgrade();
6342                boolean doTrim = isUpgrade;
6343                if (doTrim) {
6344                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6345                } else {
6346                    final long interval = android.provider.Settings.Global.getLong(
6347                            mContext.getContentResolver(),
6348                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6349                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6350                    if (interval > 0) {
6351                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6352                        if (timeSinceLast > interval) {
6353                            doTrim = true;
6354                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6355                                    + "; running immediately");
6356                        }
6357                    }
6358                }
6359                if (doTrim) {
6360                    if (!isFirstBoot()) {
6361                        try {
6362                            ActivityManagerNative.getDefault().showBootMessage(
6363                                    mContext.getResources().getString(
6364                                            R.string.android_upgrading_fstrim), true);
6365                        } catch (RemoteException e) {
6366                        }
6367                    }
6368                    ms.runMaintenance();
6369                }
6370            } else {
6371                Slog.e(TAG, "Mount service unavailable!");
6372            }
6373        } catch (RemoteException e) {
6374            // Can't happen; MountService is local
6375        }
6376    }
6377
6378    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6379        List<ResolveInfo> ris = null;
6380        try {
6381            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6382                    intent, null, 0, userId);
6383        } catch (RemoteException e) {
6384        }
6385        ArraySet<String> pkgNames = new ArraySet<String>();
6386        if (ris != null) {
6387            for (ResolveInfo ri : ris) {
6388                pkgNames.add(ri.activityInfo.packageName);
6389            }
6390        }
6391        return pkgNames;
6392    }
6393
6394    @Override
6395    public void notifyPackageUse(String packageName) {
6396        synchronized (mPackages) {
6397            PackageParser.Package p = mPackages.get(packageName);
6398            if (p == null) {
6399                return;
6400            }
6401            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6402        }
6403    }
6404
6405    @Override
6406    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6407        return performDexOptTraced(packageName, instructionSet);
6408    }
6409
6410    public boolean performDexOpt(String packageName, String instructionSet) {
6411        return performDexOptTraced(packageName, instructionSet);
6412    }
6413
6414    private boolean performDexOptTraced(String packageName, String instructionSet) {
6415        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6416        try {
6417            return performDexOptInternal(packageName, instructionSet);
6418        } finally {
6419            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6420        }
6421    }
6422
6423    private boolean performDexOptInternal(String packageName, String instructionSet) {
6424        PackageParser.Package p;
6425        final String targetInstructionSet;
6426        synchronized (mPackages) {
6427            p = mPackages.get(packageName);
6428            if (p == null) {
6429                return false;
6430            }
6431            mPackageUsage.write(false);
6432
6433            targetInstructionSet = instructionSet != null ? instructionSet :
6434                    getPrimaryInstructionSet(p.applicationInfo);
6435            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6436                return false;
6437            }
6438        }
6439        long callingId = Binder.clearCallingIdentity();
6440        try {
6441            synchronized (mInstallLock) {
6442                final String[] instructionSets = new String[] { targetInstructionSet };
6443                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6444                        true /* inclDependencies */);
6445                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6446            }
6447        } finally {
6448            Binder.restoreCallingIdentity(callingId);
6449        }
6450    }
6451
6452    public ArraySet<String> getPackagesThatNeedDexOpt() {
6453        ArraySet<String> pkgs = null;
6454        synchronized (mPackages) {
6455            for (PackageParser.Package p : mPackages.values()) {
6456                if (DEBUG_DEXOPT) {
6457                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6458                }
6459                if (!p.mDexOptPerformed.isEmpty()) {
6460                    continue;
6461                }
6462                if (pkgs == null) {
6463                    pkgs = new ArraySet<String>();
6464                }
6465                pkgs.add(p.packageName);
6466            }
6467        }
6468        return pkgs;
6469    }
6470
6471    public void shutdown() {
6472        mPackageUsage.write(true);
6473    }
6474
6475    @Override
6476    public void forceDexOpt(String packageName) {
6477        enforceSystemOrRoot("forceDexOpt");
6478
6479        PackageParser.Package pkg;
6480        synchronized (mPackages) {
6481            pkg = mPackages.get(packageName);
6482            if (pkg == null) {
6483                throw new IllegalArgumentException("Missing package: " + packageName);
6484            }
6485        }
6486
6487        synchronized (mInstallLock) {
6488            final String[] instructionSets = new String[] {
6489                    getPrimaryInstructionSet(pkg.applicationInfo) };
6490
6491            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6492
6493            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6494                    true /* inclDependencies */);
6495
6496            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6497            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6498                throw new IllegalStateException("Failed to dexopt: " + res);
6499            }
6500        }
6501    }
6502
6503    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6504        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6505            Slog.w(TAG, "Unable to update from " + oldPkg.name
6506                    + " to " + newPkg.packageName
6507                    + ": old package not in system partition");
6508            return false;
6509        } else if (mPackages.get(oldPkg.name) != null) {
6510            Slog.w(TAG, "Unable to update from " + oldPkg.name
6511                    + " to " + newPkg.packageName
6512                    + ": old package still exists");
6513            return false;
6514        }
6515        return true;
6516    }
6517
6518    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6519            throws PackageManagerException {
6520        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6521        if (res != 0) {
6522            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6523                    "Failed to install " + packageName + ": " + res);
6524        }
6525
6526        final int[] users = sUserManager.getUserIds();
6527        for (int user : users) {
6528            if (user != 0) {
6529                res = mInstaller.createUserData(volumeUuid, packageName,
6530                        UserHandle.getUid(user, uid), user, seinfo);
6531                if (res != 0) {
6532                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6533                            "Failed to createUserData " + packageName + ": " + res);
6534                }
6535            }
6536        }
6537    }
6538
6539    private int removeDataDirsLI(String volumeUuid, String packageName) {
6540        int[] users = sUserManager.getUserIds();
6541        int res = 0;
6542        for (int user : users) {
6543            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6544            if (resInner < 0) {
6545                res = resInner;
6546            }
6547        }
6548
6549        return res;
6550    }
6551
6552    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6553        int[] users = sUserManager.getUserIds();
6554        int res = 0;
6555        for (int user : users) {
6556            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6557            if (resInner < 0) {
6558                res = resInner;
6559            }
6560        }
6561        return res;
6562    }
6563
6564    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6565            PackageParser.Package changingLib) {
6566        if (file.path != null) {
6567            usesLibraryFiles.add(file.path);
6568            return;
6569        }
6570        PackageParser.Package p = mPackages.get(file.apk);
6571        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6572            // If we are doing this while in the middle of updating a library apk,
6573            // then we need to make sure to use that new apk for determining the
6574            // dependencies here.  (We haven't yet finished committing the new apk
6575            // to the package manager state.)
6576            if (p == null || p.packageName.equals(changingLib.packageName)) {
6577                p = changingLib;
6578            }
6579        }
6580        if (p != null) {
6581            usesLibraryFiles.addAll(p.getAllCodePaths());
6582        }
6583    }
6584
6585    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6586            PackageParser.Package changingLib) throws PackageManagerException {
6587        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6588            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6589            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6590            for (int i=0; i<N; i++) {
6591                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6592                if (file == null) {
6593                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6594                            "Package " + pkg.packageName + " requires unavailable shared library "
6595                            + pkg.usesLibraries.get(i) + "; failing!");
6596                }
6597                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6598            }
6599            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6600            for (int i=0; i<N; i++) {
6601                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6602                if (file == null) {
6603                    Slog.w(TAG, "Package " + pkg.packageName
6604                            + " desires unavailable shared library "
6605                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6606                } else {
6607                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6608                }
6609            }
6610            N = usesLibraryFiles.size();
6611            if (N > 0) {
6612                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6613            } else {
6614                pkg.usesLibraryFiles = null;
6615            }
6616        }
6617    }
6618
6619    private static boolean hasString(List<String> list, List<String> which) {
6620        if (list == null) {
6621            return false;
6622        }
6623        for (int i=list.size()-1; i>=0; i--) {
6624            for (int j=which.size()-1; j>=0; j--) {
6625                if (which.get(j).equals(list.get(i))) {
6626                    return true;
6627                }
6628            }
6629        }
6630        return false;
6631    }
6632
6633    private void updateAllSharedLibrariesLPw() {
6634        for (PackageParser.Package pkg : mPackages.values()) {
6635            try {
6636                updateSharedLibrariesLPw(pkg, null);
6637            } catch (PackageManagerException e) {
6638                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6639            }
6640        }
6641    }
6642
6643    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6644            PackageParser.Package changingPkg) {
6645        ArrayList<PackageParser.Package> res = null;
6646        for (PackageParser.Package pkg : mPackages.values()) {
6647            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6648                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6649                if (res == null) {
6650                    res = new ArrayList<PackageParser.Package>();
6651                }
6652                res.add(pkg);
6653                try {
6654                    updateSharedLibrariesLPw(pkg, changingPkg);
6655                } catch (PackageManagerException e) {
6656                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6657                }
6658            }
6659        }
6660        return res;
6661    }
6662
6663    /**
6664     * Derive the value of the {@code cpuAbiOverride} based on the provided
6665     * value and an optional stored value from the package settings.
6666     */
6667    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6668        String cpuAbiOverride = null;
6669
6670        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6671            cpuAbiOverride = null;
6672        } else if (abiOverride != null) {
6673            cpuAbiOverride = abiOverride;
6674        } else if (settings != null) {
6675            cpuAbiOverride = settings.cpuAbiOverrideString;
6676        }
6677
6678        return cpuAbiOverride;
6679    }
6680
6681    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6682            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6684        try {
6685            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689    }
6690
6691    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6692            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6693        boolean success = false;
6694        try {
6695            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6696                    currentTime, user);
6697            success = true;
6698            return res;
6699        } finally {
6700            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6701                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6702            }
6703        }
6704    }
6705
6706    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6707            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6708        final File scanFile = new File(pkg.codePath);
6709        if (pkg.applicationInfo.getCodePath() == null ||
6710                pkg.applicationInfo.getResourcePath() == null) {
6711            // Bail out. The resource and code paths haven't been set.
6712            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6713                    "Code and resource paths haven't been set correctly");
6714        }
6715
6716        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6717            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6718        } else {
6719            // Only allow system apps to be flagged as core apps.
6720            pkg.coreApp = false;
6721        }
6722
6723        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6724            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6725        }
6726
6727        if (mCustomResolverComponentName != null &&
6728                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6729            setUpCustomResolverActivity(pkg);
6730        }
6731
6732        if (pkg.packageName.equals("android")) {
6733            synchronized (mPackages) {
6734                if (mAndroidApplication != null) {
6735                    Slog.w(TAG, "*************************************************");
6736                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6737                    Slog.w(TAG, " file=" + scanFile);
6738                    Slog.w(TAG, "*************************************************");
6739                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6740                            "Core android package being redefined.  Skipping.");
6741                }
6742
6743                // Set up information for our fall-back user intent resolution activity.
6744                mPlatformPackage = pkg;
6745                pkg.mVersionCode = mSdkVersion;
6746                mAndroidApplication = pkg.applicationInfo;
6747
6748                if (!mResolverReplaced) {
6749                    mResolveActivity.applicationInfo = mAndroidApplication;
6750                    mResolveActivity.name = ResolverActivity.class.getName();
6751                    mResolveActivity.packageName = mAndroidApplication.packageName;
6752                    mResolveActivity.processName = "system:ui";
6753                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6754                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6755                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6756                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6757                    mResolveActivity.exported = true;
6758                    mResolveActivity.enabled = true;
6759                    mResolveInfo.activityInfo = mResolveActivity;
6760                    mResolveInfo.priority = 0;
6761                    mResolveInfo.preferredOrder = 0;
6762                    mResolveInfo.match = 0;
6763                    mResolveComponentName = new ComponentName(
6764                            mAndroidApplication.packageName, mResolveActivity.name);
6765                }
6766            }
6767        }
6768
6769        if (DEBUG_PACKAGE_SCANNING) {
6770            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6771                Log.d(TAG, "Scanning package " + pkg.packageName);
6772        }
6773
6774        if (mPackages.containsKey(pkg.packageName)
6775                || mSharedLibraries.containsKey(pkg.packageName)) {
6776            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6777                    "Application package " + pkg.packageName
6778                    + " already installed.  Skipping duplicate.");
6779        }
6780
6781        // If we're only installing presumed-existing packages, require that the
6782        // scanned APK is both already known and at the path previously established
6783        // for it.  Previously unknown packages we pick up normally, but if we have an
6784        // a priori expectation about this package's install presence, enforce it.
6785        // With a singular exception for new system packages. When an OTA contains
6786        // a new system package, we allow the codepath to change from a system location
6787        // to the user-installed location. If we don't allow this change, any newer,
6788        // user-installed version of the application will be ignored.
6789        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6790            if (mExpectingBetter.containsKey(pkg.packageName)) {
6791                logCriticalInfo(Log.WARN,
6792                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6793            } else {
6794                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6795                if (known != null) {
6796                    if (DEBUG_PACKAGE_SCANNING) {
6797                        Log.d(TAG, "Examining " + pkg.codePath
6798                                + " and requiring known paths " + known.codePathString
6799                                + " & " + known.resourcePathString);
6800                    }
6801                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6802                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6803                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6804                                "Application package " + pkg.packageName
6805                                + " found at " + pkg.applicationInfo.getCodePath()
6806                                + " but expected at " + known.codePathString + "; ignoring.");
6807                    }
6808                }
6809            }
6810        }
6811
6812        // Initialize package source and resource directories
6813        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6814        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6815
6816        SharedUserSetting suid = null;
6817        PackageSetting pkgSetting = null;
6818
6819        if (!isSystemApp(pkg)) {
6820            // Only system apps can use these features.
6821            pkg.mOriginalPackages = null;
6822            pkg.mRealPackage = null;
6823            pkg.mAdoptPermissions = null;
6824        }
6825
6826        // writer
6827        synchronized (mPackages) {
6828            if (pkg.mSharedUserId != null) {
6829                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6830                if (suid == null) {
6831                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6832                            "Creating application package " + pkg.packageName
6833                            + " for shared user failed");
6834                }
6835                if (DEBUG_PACKAGE_SCANNING) {
6836                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6837                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6838                                + "): packages=" + suid.packages);
6839                }
6840            }
6841
6842            // Check if we are renaming from an original package name.
6843            PackageSetting origPackage = null;
6844            String realName = null;
6845            if (pkg.mOriginalPackages != null) {
6846                // This package may need to be renamed to a previously
6847                // installed name.  Let's check on that...
6848                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6849                if (pkg.mOriginalPackages.contains(renamed)) {
6850                    // This package had originally been installed as the
6851                    // original name, and we have already taken care of
6852                    // transitioning to the new one.  Just update the new
6853                    // one to continue using the old name.
6854                    realName = pkg.mRealPackage;
6855                    if (!pkg.packageName.equals(renamed)) {
6856                        // Callers into this function may have already taken
6857                        // care of renaming the package; only do it here if
6858                        // it is not already done.
6859                        pkg.setPackageName(renamed);
6860                    }
6861
6862                } else {
6863                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6864                        if ((origPackage = mSettings.peekPackageLPr(
6865                                pkg.mOriginalPackages.get(i))) != null) {
6866                            // We do have the package already installed under its
6867                            // original name...  should we use it?
6868                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6869                                // New package is not compatible with original.
6870                                origPackage = null;
6871                                continue;
6872                            } else if (origPackage.sharedUser != null) {
6873                                // Make sure uid is compatible between packages.
6874                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6875                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6876                                            + " to " + pkg.packageName + ": old uid "
6877                                            + origPackage.sharedUser.name
6878                                            + " differs from " + pkg.mSharedUserId);
6879                                    origPackage = null;
6880                                    continue;
6881                                }
6882                            } else {
6883                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6884                                        + pkg.packageName + " to old name " + origPackage.name);
6885                            }
6886                            break;
6887                        }
6888                    }
6889                }
6890            }
6891
6892            if (mTransferedPackages.contains(pkg.packageName)) {
6893                Slog.w(TAG, "Package " + pkg.packageName
6894                        + " was transferred to another, but its .apk remains");
6895            }
6896
6897            // Just create the setting, don't add it yet. For already existing packages
6898            // the PkgSetting exists already and doesn't have to be created.
6899            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6900                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6901                    pkg.applicationInfo.primaryCpuAbi,
6902                    pkg.applicationInfo.secondaryCpuAbi,
6903                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6904                    user, false);
6905            if (pkgSetting == null) {
6906                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6907                        "Creating application package " + pkg.packageName + " failed");
6908            }
6909
6910            if (pkgSetting.origPackage != null) {
6911                // If we are first transitioning from an original package,
6912                // fix up the new package's name now.  We need to do this after
6913                // looking up the package under its new name, so getPackageLP
6914                // can take care of fiddling things correctly.
6915                pkg.setPackageName(origPackage.name);
6916
6917                // File a report about this.
6918                String msg = "New package " + pkgSetting.realName
6919                        + " renamed to replace old package " + pkgSetting.name;
6920                reportSettingsProblem(Log.WARN, msg);
6921
6922                // Make a note of it.
6923                mTransferedPackages.add(origPackage.name);
6924
6925                // No longer need to retain this.
6926                pkgSetting.origPackage = null;
6927            }
6928
6929            if (realName != null) {
6930                // Make a note of it.
6931                mTransferedPackages.add(pkg.packageName);
6932            }
6933
6934            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6935                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6936            }
6937
6938            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6939                // Check all shared libraries and map to their actual file path.
6940                // We only do this here for apps not on a system dir, because those
6941                // are the only ones that can fail an install due to this.  We
6942                // will take care of the system apps by updating all of their
6943                // library paths after the scan is done.
6944                updateSharedLibrariesLPw(pkg, null);
6945            }
6946
6947            if (mFoundPolicyFile) {
6948                SELinuxMMAC.assignSeinfoValue(pkg);
6949            }
6950
6951            pkg.applicationInfo.uid = pkgSetting.appId;
6952            pkg.mExtras = pkgSetting;
6953            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6954                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6955                    // We just determined the app is signed correctly, so bring
6956                    // over the latest parsed certs.
6957                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6958                } else {
6959                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6960                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6961                                "Package " + pkg.packageName + " upgrade keys do not match the "
6962                                + "previously installed version");
6963                    } else {
6964                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6965                        String msg = "System package " + pkg.packageName
6966                            + " signature changed; retaining data.";
6967                        reportSettingsProblem(Log.WARN, msg);
6968                    }
6969                }
6970            } else {
6971                try {
6972                    verifySignaturesLP(pkgSetting, pkg);
6973                    // We just determined the app is signed correctly, so bring
6974                    // over the latest parsed certs.
6975                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6976                } catch (PackageManagerException e) {
6977                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6978                        throw e;
6979                    }
6980                    // The signature has changed, but this package is in the system
6981                    // image...  let's recover!
6982                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6983                    // However...  if this package is part of a shared user, but it
6984                    // doesn't match the signature of the shared user, let's fail.
6985                    // What this means is that you can't change the signatures
6986                    // associated with an overall shared user, which doesn't seem all
6987                    // that unreasonable.
6988                    if (pkgSetting.sharedUser != null) {
6989                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6990                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6991                            throw new PackageManagerException(
6992                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6993                                            "Signature mismatch for shared user : "
6994                                            + pkgSetting.sharedUser);
6995                        }
6996                    }
6997                    // File a report about this.
6998                    String msg = "System package " + pkg.packageName
6999                        + " signature changed; retaining data.";
7000                    reportSettingsProblem(Log.WARN, msg);
7001                }
7002            }
7003            // Verify that this new package doesn't have any content providers
7004            // that conflict with existing packages.  Only do this if the
7005            // package isn't already installed, since we don't want to break
7006            // things that are installed.
7007            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7008                final int N = pkg.providers.size();
7009                int i;
7010                for (i=0; i<N; i++) {
7011                    PackageParser.Provider p = pkg.providers.get(i);
7012                    if (p.info.authority != null) {
7013                        String names[] = p.info.authority.split(";");
7014                        for (int j = 0; j < names.length; j++) {
7015                            if (mProvidersByAuthority.containsKey(names[j])) {
7016                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7017                                final String otherPackageName =
7018                                        ((other != null && other.getComponentName() != null) ?
7019                                                other.getComponentName().getPackageName() : "?");
7020                                throw new PackageManagerException(
7021                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7022                                                "Can't install because provider name " + names[j]
7023                                                + " (in package " + pkg.applicationInfo.packageName
7024                                                + ") is already used by " + otherPackageName);
7025                            }
7026                        }
7027                    }
7028                }
7029            }
7030
7031            if (pkg.mAdoptPermissions != null) {
7032                // This package wants to adopt ownership of permissions from
7033                // another package.
7034                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7035                    final String origName = pkg.mAdoptPermissions.get(i);
7036                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7037                    if (orig != null) {
7038                        if (verifyPackageUpdateLPr(orig, pkg)) {
7039                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7040                                    + pkg.packageName);
7041                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7042                        }
7043                    }
7044                }
7045            }
7046        }
7047
7048        final String pkgName = pkg.packageName;
7049
7050        final long scanFileTime = scanFile.lastModified();
7051        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7052        pkg.applicationInfo.processName = fixProcessName(
7053                pkg.applicationInfo.packageName,
7054                pkg.applicationInfo.processName,
7055                pkg.applicationInfo.uid);
7056
7057        if (pkg != mPlatformPackage) {
7058            // This is a normal package, need to make its data directory.
7059            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7060                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7061
7062            boolean uidError = false;
7063            if (dataPath.exists()) {
7064                int currentUid = 0;
7065                try {
7066                    StructStat stat = Os.stat(dataPath.getPath());
7067                    currentUid = stat.st_uid;
7068                } catch (ErrnoException e) {
7069                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7070                }
7071
7072                // If we have mismatched owners for the data path, we have a problem.
7073                if (currentUid != pkg.applicationInfo.uid) {
7074                    boolean recovered = false;
7075                    if (currentUid == 0) {
7076                        // The directory somehow became owned by root.  Wow.
7077                        // This is probably because the system was stopped while
7078                        // installd was in the middle of messing with its libs
7079                        // directory.  Ask installd to fix that.
7080                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7081                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7082                        if (ret >= 0) {
7083                            recovered = true;
7084                            String msg = "Package " + pkg.packageName
7085                                    + " unexpectedly changed to uid 0; recovered to " +
7086                                    + pkg.applicationInfo.uid;
7087                            reportSettingsProblem(Log.WARN, msg);
7088                        }
7089                    }
7090                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7091                            || (scanFlags&SCAN_BOOTING) != 0)) {
7092                        // If this is a system app, we can at least delete its
7093                        // current data so the application will still work.
7094                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7095                        if (ret >= 0) {
7096                            // TODO: Kill the processes first
7097                            // Old data gone!
7098                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7099                                    ? "System package " : "Third party package ";
7100                            String msg = prefix + pkg.packageName
7101                                    + " has changed from uid: "
7102                                    + currentUid + " to "
7103                                    + pkg.applicationInfo.uid + "; old data erased";
7104                            reportSettingsProblem(Log.WARN, msg);
7105                            recovered = true;
7106                        }
7107                        if (!recovered) {
7108                            mHasSystemUidErrors = true;
7109                        }
7110                    } else if (!recovered) {
7111                        // If we allow this install to proceed, we will be broken.
7112                        // Abort, abort!
7113                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7114                                "scanPackageLI");
7115                    }
7116                    if (!recovered) {
7117                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7118                            + pkg.applicationInfo.uid + "/fs_"
7119                            + currentUid;
7120                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7121                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7122                        String msg = "Package " + pkg.packageName
7123                                + " has mismatched uid: "
7124                                + currentUid + " on disk, "
7125                                + pkg.applicationInfo.uid + " in settings";
7126                        // writer
7127                        synchronized (mPackages) {
7128                            mSettings.mReadMessages.append(msg);
7129                            mSettings.mReadMessages.append('\n');
7130                            uidError = true;
7131                            if (!pkgSetting.uidError) {
7132                                reportSettingsProblem(Log.ERROR, msg);
7133                            }
7134                        }
7135                    }
7136                }
7137
7138                // Ensure that directories are prepared
7139                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7140                        pkg.applicationInfo.seinfo);
7141
7142                if (mShouldRestoreconData) {
7143                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7144                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7145                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7146                }
7147            } else {
7148                if (DEBUG_PACKAGE_SCANNING) {
7149                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7150                        Log.v(TAG, "Want this data dir: " + dataPath);
7151                }
7152                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7153                        pkg.applicationInfo.seinfo);
7154            }
7155
7156            // Get all of our default paths setup
7157            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7158
7159            pkgSetting.uidError = uidError;
7160        }
7161
7162        final String path = scanFile.getPath();
7163        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7164
7165        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7166            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7167
7168            // Some system apps still use directory structure for native libraries
7169            // in which case we might end up not detecting abi solely based on apk
7170            // structure. Try to detect abi based on directory structure.
7171            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7172                    pkg.applicationInfo.primaryCpuAbi == null) {
7173                setBundledAppAbisAndRoots(pkg, pkgSetting);
7174                setNativeLibraryPaths(pkg);
7175            }
7176
7177        } else {
7178            if ((scanFlags & SCAN_MOVE) != 0) {
7179                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7180                // but we already have this packages package info in the PackageSetting. We just
7181                // use that and derive the native library path based on the new codepath.
7182                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7183                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7184            }
7185
7186            // Set native library paths again. For moves, the path will be updated based on the
7187            // ABIs we've determined above. For non-moves, the path will be updated based on the
7188            // ABIs we determined during compilation, but the path will depend on the final
7189            // package path (after the rename away from the stage path).
7190            setNativeLibraryPaths(pkg);
7191        }
7192
7193        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7194        final int[] userIds = sUserManager.getUserIds();
7195        synchronized (mInstallLock) {
7196            // Make sure all user data directories are ready to roll; we're okay
7197            // if they already exist
7198            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7199                for (int userId : userIds) {
7200                    if (userId != UserHandle.USER_SYSTEM) {
7201                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7202                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7203                                pkg.applicationInfo.seinfo);
7204                    }
7205                }
7206            }
7207
7208            // Create a native library symlink only if we have native libraries
7209            // and if the native libraries are 32 bit libraries. We do not provide
7210            // this symlink for 64 bit libraries.
7211            if (pkg.applicationInfo.primaryCpuAbi != null &&
7212                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7213                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7214                try {
7215                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7216                    for (int userId : userIds) {
7217                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7218                                nativeLibPath, userId) < 0) {
7219                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7220                                    "Failed linking native library dir (user=" + userId + ")");
7221                        }
7222                    }
7223                } finally {
7224                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7225                }
7226            }
7227        }
7228
7229        // This is a special case for the "system" package, where the ABI is
7230        // dictated by the zygote configuration (and init.rc). We should keep track
7231        // of this ABI so that we can deal with "normal" applications that run under
7232        // the same UID correctly.
7233        if (mPlatformPackage == pkg) {
7234            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7235                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7236        }
7237
7238        // If there's a mismatch between the abi-override in the package setting
7239        // and the abiOverride specified for the install. Warn about this because we
7240        // would've already compiled the app without taking the package setting into
7241        // account.
7242        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7243            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7244                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7245                        " for package: " + pkg.packageName);
7246            }
7247        }
7248
7249        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7250        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7251        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7252
7253        // Copy the derived override back to the parsed package, so that we can
7254        // update the package settings accordingly.
7255        pkg.cpuAbiOverride = cpuAbiOverride;
7256
7257        if (DEBUG_ABI_SELECTION) {
7258            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7259                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7260                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7261        }
7262
7263        // Push the derived path down into PackageSettings so we know what to
7264        // clean up at uninstall time.
7265        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7266
7267        if (DEBUG_ABI_SELECTION) {
7268            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7269                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7270                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7271        }
7272
7273        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7274            // We don't do this here during boot because we can do it all
7275            // at once after scanning all existing packages.
7276            //
7277            // We also do this *before* we perform dexopt on this package, so that
7278            // we can avoid redundant dexopts, and also to make sure we've got the
7279            // code and package path correct.
7280            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7281                    pkg, true /* boot complete */);
7282        }
7283
7284        if (mFactoryTest && pkg.requestedPermissions.contains(
7285                android.Manifest.permission.FACTORY_TEST)) {
7286            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7287        }
7288
7289        ArrayList<PackageParser.Package> clientLibPkgs = null;
7290
7291        // writer
7292        synchronized (mPackages) {
7293            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7294                // Only system apps can add new shared libraries.
7295                if (pkg.libraryNames != null) {
7296                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7297                        String name = pkg.libraryNames.get(i);
7298                        boolean allowed = false;
7299                        if (pkg.isUpdatedSystemApp()) {
7300                            // New library entries can only be added through the
7301                            // system image.  This is important to get rid of a lot
7302                            // of nasty edge cases: for example if we allowed a non-
7303                            // system update of the app to add a library, then uninstalling
7304                            // the update would make the library go away, and assumptions
7305                            // we made such as through app install filtering would now
7306                            // have allowed apps on the device which aren't compatible
7307                            // with it.  Better to just have the restriction here, be
7308                            // conservative, and create many fewer cases that can negatively
7309                            // impact the user experience.
7310                            final PackageSetting sysPs = mSettings
7311                                    .getDisabledSystemPkgLPr(pkg.packageName);
7312                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7313                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7314                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7315                                        allowed = true;
7316                                        break;
7317                                    }
7318                                }
7319                            }
7320                        } else {
7321                            allowed = true;
7322                        }
7323                        if (allowed) {
7324                            if (!mSharedLibraries.containsKey(name)) {
7325                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7326                            } else if (!name.equals(pkg.packageName)) {
7327                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7328                                        + name + " already exists; skipping");
7329                            }
7330                        } else {
7331                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7332                                    + name + " that is not declared on system image; skipping");
7333                        }
7334                    }
7335                    if ((scanFlags & SCAN_BOOTING) == 0) {
7336                        // If we are not booting, we need to update any applications
7337                        // that are clients of our shared library.  If we are booting,
7338                        // this will all be done once the scan is complete.
7339                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7340                    }
7341                }
7342            }
7343        }
7344
7345        // Request the ActivityManager to kill the process(only for existing packages)
7346        // so that we do not end up in a confused state while the user is still using the older
7347        // version of the application while the new one gets installed.
7348        if ((scanFlags & SCAN_REPLACING) != 0) {
7349            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7350
7351            killApplication(pkg.applicationInfo.packageName,
7352                        pkg.applicationInfo.uid, "replace pkg");
7353
7354            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7355        }
7356
7357        // Also need to kill any apps that are dependent on the library.
7358        if (clientLibPkgs != null) {
7359            for (int i=0; i<clientLibPkgs.size(); i++) {
7360                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7361                killApplication(clientPkg.applicationInfo.packageName,
7362                        clientPkg.applicationInfo.uid, "update lib");
7363            }
7364        }
7365
7366        // Make sure we're not adding any bogus keyset info
7367        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7368        ksms.assertScannedPackageValid(pkg);
7369
7370        // writer
7371        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7372
7373        boolean createIdmapFailed = false;
7374        synchronized (mPackages) {
7375            // We don't expect installation to fail beyond this point
7376
7377            // Add the new setting to mSettings
7378            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7379            // Add the new setting to mPackages
7380            mPackages.put(pkg.applicationInfo.packageName, pkg);
7381            // Make sure we don't accidentally delete its data.
7382            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7383            while (iter.hasNext()) {
7384                PackageCleanItem item = iter.next();
7385                if (pkgName.equals(item.packageName)) {
7386                    iter.remove();
7387                }
7388            }
7389
7390            // Take care of first install / last update times.
7391            if (currentTime != 0) {
7392                if (pkgSetting.firstInstallTime == 0) {
7393                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7394                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7395                    pkgSetting.lastUpdateTime = currentTime;
7396                }
7397            } else if (pkgSetting.firstInstallTime == 0) {
7398                // We need *something*.  Take time time stamp of the file.
7399                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7400            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7401                if (scanFileTime != pkgSetting.timeStamp) {
7402                    // A package on the system image has changed; consider this
7403                    // to be an update.
7404                    pkgSetting.lastUpdateTime = scanFileTime;
7405                }
7406            }
7407
7408            // Add the package's KeySets to the global KeySetManagerService
7409            ksms.addScannedPackageLPw(pkg);
7410
7411            int N = pkg.providers.size();
7412            StringBuilder r = null;
7413            int i;
7414            for (i=0; i<N; i++) {
7415                PackageParser.Provider p = pkg.providers.get(i);
7416                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7417                        p.info.processName, pkg.applicationInfo.uid);
7418                mProviders.addProvider(p);
7419                p.syncable = p.info.isSyncable;
7420                if (p.info.authority != null) {
7421                    String names[] = p.info.authority.split(";");
7422                    p.info.authority = null;
7423                    for (int j = 0; j < names.length; j++) {
7424                        if (j == 1 && p.syncable) {
7425                            // We only want the first authority for a provider to possibly be
7426                            // syncable, so if we already added this provider using a different
7427                            // authority clear the syncable flag. We copy the provider before
7428                            // changing it because the mProviders object contains a reference
7429                            // to a provider that we don't want to change.
7430                            // Only do this for the second authority since the resulting provider
7431                            // object can be the same for all future authorities for this provider.
7432                            p = new PackageParser.Provider(p);
7433                            p.syncable = false;
7434                        }
7435                        if (!mProvidersByAuthority.containsKey(names[j])) {
7436                            mProvidersByAuthority.put(names[j], p);
7437                            if (p.info.authority == null) {
7438                                p.info.authority = names[j];
7439                            } else {
7440                                p.info.authority = p.info.authority + ";" + names[j];
7441                            }
7442                            if (DEBUG_PACKAGE_SCANNING) {
7443                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7444                                    Log.d(TAG, "Registered content provider: " + names[j]
7445                                            + ", className = " + p.info.name + ", isSyncable = "
7446                                            + p.info.isSyncable);
7447                            }
7448                        } else {
7449                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7450                            Slog.w(TAG, "Skipping provider name " + names[j] +
7451                                    " (in package " + pkg.applicationInfo.packageName +
7452                                    "): name already used by "
7453                                    + ((other != null && other.getComponentName() != null)
7454                                            ? other.getComponentName().getPackageName() : "?"));
7455                        }
7456                    }
7457                }
7458                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7459                    if (r == null) {
7460                        r = new StringBuilder(256);
7461                    } else {
7462                        r.append(' ');
7463                    }
7464                    r.append(p.info.name);
7465                }
7466            }
7467            if (r != null) {
7468                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7469            }
7470
7471            N = pkg.services.size();
7472            r = null;
7473            for (i=0; i<N; i++) {
7474                PackageParser.Service s = pkg.services.get(i);
7475                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7476                        s.info.processName, pkg.applicationInfo.uid);
7477                mServices.addService(s);
7478                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7479                    if (r == null) {
7480                        r = new StringBuilder(256);
7481                    } else {
7482                        r.append(' ');
7483                    }
7484                    r.append(s.info.name);
7485                }
7486            }
7487            if (r != null) {
7488                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7489            }
7490
7491            N = pkg.receivers.size();
7492            r = null;
7493            for (i=0; i<N; i++) {
7494                PackageParser.Activity a = pkg.receivers.get(i);
7495                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7496                        a.info.processName, pkg.applicationInfo.uid);
7497                mReceivers.addActivity(a, "receiver");
7498                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7499                    if (r == null) {
7500                        r = new StringBuilder(256);
7501                    } else {
7502                        r.append(' ');
7503                    }
7504                    r.append(a.info.name);
7505                }
7506            }
7507            if (r != null) {
7508                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7509            }
7510
7511            N = pkg.activities.size();
7512            r = null;
7513            for (i=0; i<N; i++) {
7514                PackageParser.Activity a = pkg.activities.get(i);
7515                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7516                        a.info.processName, pkg.applicationInfo.uid);
7517                mActivities.addActivity(a, "activity");
7518                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7519                    if (r == null) {
7520                        r = new StringBuilder(256);
7521                    } else {
7522                        r.append(' ');
7523                    }
7524                    r.append(a.info.name);
7525                }
7526            }
7527            if (r != null) {
7528                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7529            }
7530
7531            N = pkg.permissionGroups.size();
7532            r = null;
7533            for (i=0; i<N; i++) {
7534                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7535                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7536                if (cur == null) {
7537                    mPermissionGroups.put(pg.info.name, pg);
7538                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7539                        if (r == null) {
7540                            r = new StringBuilder(256);
7541                        } else {
7542                            r.append(' ');
7543                        }
7544                        r.append(pg.info.name);
7545                    }
7546                } else {
7547                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7548                            + pg.info.packageName + " ignored: original from "
7549                            + cur.info.packageName);
7550                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7551                        if (r == null) {
7552                            r = new StringBuilder(256);
7553                        } else {
7554                            r.append(' ');
7555                        }
7556                        r.append("DUP:");
7557                        r.append(pg.info.name);
7558                    }
7559                }
7560            }
7561            if (r != null) {
7562                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7563            }
7564
7565            N = pkg.permissions.size();
7566            r = null;
7567            for (i=0; i<N; i++) {
7568                PackageParser.Permission p = pkg.permissions.get(i);
7569
7570                // Assume by default that we did not install this permission into the system.
7571                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7572
7573                // Now that permission groups have a special meaning, we ignore permission
7574                // groups for legacy apps to prevent unexpected behavior. In particular,
7575                // permissions for one app being granted to someone just becuase they happen
7576                // to be in a group defined by another app (before this had no implications).
7577                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7578                    p.group = mPermissionGroups.get(p.info.group);
7579                    // Warn for a permission in an unknown group.
7580                    if (p.info.group != null && p.group == null) {
7581                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7582                                + p.info.packageName + " in an unknown group " + p.info.group);
7583                    }
7584                }
7585
7586                ArrayMap<String, BasePermission> permissionMap =
7587                        p.tree ? mSettings.mPermissionTrees
7588                                : mSettings.mPermissions;
7589                BasePermission bp = permissionMap.get(p.info.name);
7590
7591                // Allow system apps to redefine non-system permissions
7592                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7593                    final boolean currentOwnerIsSystem = (bp.perm != null
7594                            && isSystemApp(bp.perm.owner));
7595                    if (isSystemApp(p.owner)) {
7596                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7597                            // It's a built-in permission and no owner, take ownership now
7598                            bp.packageSetting = pkgSetting;
7599                            bp.perm = p;
7600                            bp.uid = pkg.applicationInfo.uid;
7601                            bp.sourcePackage = p.info.packageName;
7602                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7603                        } else if (!currentOwnerIsSystem) {
7604                            String msg = "New decl " + p.owner + " of permission  "
7605                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7606                            reportSettingsProblem(Log.WARN, msg);
7607                            bp = null;
7608                        }
7609                    }
7610                }
7611
7612                if (bp == null) {
7613                    bp = new BasePermission(p.info.name, p.info.packageName,
7614                            BasePermission.TYPE_NORMAL);
7615                    permissionMap.put(p.info.name, bp);
7616                }
7617
7618                if (bp.perm == null) {
7619                    if (bp.sourcePackage == null
7620                            || bp.sourcePackage.equals(p.info.packageName)) {
7621                        BasePermission tree = findPermissionTreeLP(p.info.name);
7622                        if (tree == null
7623                                || tree.sourcePackage.equals(p.info.packageName)) {
7624                            bp.packageSetting = pkgSetting;
7625                            bp.perm = p;
7626                            bp.uid = pkg.applicationInfo.uid;
7627                            bp.sourcePackage = p.info.packageName;
7628                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7629                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7630                                if (r == null) {
7631                                    r = new StringBuilder(256);
7632                                } else {
7633                                    r.append(' ');
7634                                }
7635                                r.append(p.info.name);
7636                            }
7637                        } else {
7638                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7639                                    + p.info.packageName + " ignored: base tree "
7640                                    + tree.name + " is from package "
7641                                    + tree.sourcePackage);
7642                        }
7643                    } else {
7644                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7645                                + p.info.packageName + " ignored: original from "
7646                                + bp.sourcePackage);
7647                    }
7648                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7649                    if (r == null) {
7650                        r = new StringBuilder(256);
7651                    } else {
7652                        r.append(' ');
7653                    }
7654                    r.append("DUP:");
7655                    r.append(p.info.name);
7656                }
7657                if (bp.perm == p) {
7658                    bp.protectionLevel = p.info.protectionLevel;
7659                }
7660            }
7661
7662            if (r != null) {
7663                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7664            }
7665
7666            N = pkg.instrumentation.size();
7667            r = null;
7668            for (i=0; i<N; i++) {
7669                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7670                a.info.packageName = pkg.applicationInfo.packageName;
7671                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7672                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7673                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7674                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7675                a.info.dataDir = pkg.applicationInfo.dataDir;
7676                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7677                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7678
7679                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7680                // need other information about the application, like the ABI and what not ?
7681                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7682                mInstrumentation.put(a.getComponentName(), a);
7683                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7684                    if (r == null) {
7685                        r = new StringBuilder(256);
7686                    } else {
7687                        r.append(' ');
7688                    }
7689                    r.append(a.info.name);
7690                }
7691            }
7692            if (r != null) {
7693                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7694            }
7695
7696            if (pkg.protectedBroadcasts != null) {
7697                N = pkg.protectedBroadcasts.size();
7698                for (i=0; i<N; i++) {
7699                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7700                }
7701            }
7702
7703            pkgSetting.setTimeStamp(scanFileTime);
7704
7705            // Create idmap files for pairs of (packages, overlay packages).
7706            // Note: "android", ie framework-res.apk, is handled by native layers.
7707            if (pkg.mOverlayTarget != null) {
7708                // This is an overlay package.
7709                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7710                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7711                        mOverlays.put(pkg.mOverlayTarget,
7712                                new ArrayMap<String, PackageParser.Package>());
7713                    }
7714                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7715                    map.put(pkg.packageName, pkg);
7716                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7717                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7718                        createIdmapFailed = true;
7719                    }
7720                }
7721            } else if (mOverlays.containsKey(pkg.packageName) &&
7722                    !pkg.packageName.equals("android")) {
7723                // This is a regular package, with one or more known overlay packages.
7724                createIdmapsForPackageLI(pkg);
7725            }
7726        }
7727
7728        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7729
7730        if (createIdmapFailed) {
7731            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7732                    "scanPackageLI failed to createIdmap");
7733        }
7734        return pkg;
7735    }
7736
7737    /**
7738     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7739     * is derived purely on the basis of the contents of {@code scanFile} and
7740     * {@code cpuAbiOverride}.
7741     *
7742     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7743     */
7744    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7745                                 String cpuAbiOverride, boolean extractLibs)
7746            throws PackageManagerException {
7747        // TODO: We can probably be smarter about this stuff. For installed apps,
7748        // we can calculate this information at install time once and for all. For
7749        // system apps, we can probably assume that this information doesn't change
7750        // after the first boot scan. As things stand, we do lots of unnecessary work.
7751
7752        // Give ourselves some initial paths; we'll come back for another
7753        // pass once we've determined ABI below.
7754        setNativeLibraryPaths(pkg);
7755
7756        // We would never need to extract libs for forward-locked and external packages,
7757        // since the container service will do it for us. We shouldn't attempt to
7758        // extract libs from system app when it was not updated.
7759        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7760                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7761            extractLibs = false;
7762        }
7763
7764        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7765        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7766
7767        NativeLibraryHelper.Handle handle = null;
7768        try {
7769            handle = NativeLibraryHelper.Handle.create(pkg);
7770            // TODO(multiArch): This can be null for apps that didn't go through the
7771            // usual installation process. We can calculate it again, like we
7772            // do during install time.
7773            //
7774            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7775            // unnecessary.
7776            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7777
7778            // Null out the abis so that they can be recalculated.
7779            pkg.applicationInfo.primaryCpuAbi = null;
7780            pkg.applicationInfo.secondaryCpuAbi = null;
7781            if (isMultiArch(pkg.applicationInfo)) {
7782                // Warn if we've set an abiOverride for multi-lib packages..
7783                // By definition, we need to copy both 32 and 64 bit libraries for
7784                // such packages.
7785                if (pkg.cpuAbiOverride != null
7786                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7787                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7788                }
7789
7790                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7791                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7792                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7793                    if (extractLibs) {
7794                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7795                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7796                                useIsaSpecificSubdirs);
7797                    } else {
7798                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7799                    }
7800                }
7801
7802                maybeThrowExceptionForMultiArchCopy(
7803                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7804
7805                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7806                    if (extractLibs) {
7807                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7808                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7809                                useIsaSpecificSubdirs);
7810                    } else {
7811                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7812                    }
7813                }
7814
7815                maybeThrowExceptionForMultiArchCopy(
7816                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7817
7818                if (abi64 >= 0) {
7819                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7820                }
7821
7822                if (abi32 >= 0) {
7823                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7824                    if (abi64 >= 0) {
7825                        pkg.applicationInfo.secondaryCpuAbi = abi;
7826                    } else {
7827                        pkg.applicationInfo.primaryCpuAbi = abi;
7828                    }
7829                }
7830            } else {
7831                String[] abiList = (cpuAbiOverride != null) ?
7832                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7833
7834                // Enable gross and lame hacks for apps that are built with old
7835                // SDK tools. We must scan their APKs for renderscript bitcode and
7836                // not launch them if it's present. Don't bother checking on devices
7837                // that don't have 64 bit support.
7838                boolean needsRenderScriptOverride = false;
7839                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7840                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7841                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7842                    needsRenderScriptOverride = true;
7843                }
7844
7845                final int copyRet;
7846                if (extractLibs) {
7847                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7848                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7849                } else {
7850                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7851                }
7852
7853                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7854                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7855                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7856                }
7857
7858                if (copyRet >= 0) {
7859                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7860                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7861                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7862                } else if (needsRenderScriptOverride) {
7863                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7864                }
7865            }
7866        } catch (IOException ioe) {
7867            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7868        } finally {
7869            IoUtils.closeQuietly(handle);
7870        }
7871
7872        // Now that we've calculated the ABIs and determined if it's an internal app,
7873        // we will go ahead and populate the nativeLibraryPath.
7874        setNativeLibraryPaths(pkg);
7875    }
7876
7877    /**
7878     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7879     * i.e, so that all packages can be run inside a single process if required.
7880     *
7881     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7882     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7883     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7884     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7885     * updating a package that belongs to a shared user.
7886     *
7887     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7888     * adds unnecessary complexity.
7889     */
7890    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7891            PackageParser.Package scannedPackage, boolean bootComplete) {
7892        String requiredInstructionSet = null;
7893        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7894            requiredInstructionSet = VMRuntime.getInstructionSet(
7895                     scannedPackage.applicationInfo.primaryCpuAbi);
7896        }
7897
7898        PackageSetting requirer = null;
7899        for (PackageSetting ps : packagesForUser) {
7900            // If packagesForUser contains scannedPackage, we skip it. This will happen
7901            // when scannedPackage is an update of an existing package. Without this check,
7902            // we will never be able to change the ABI of any package belonging to a shared
7903            // user, even if it's compatible with other packages.
7904            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7905                if (ps.primaryCpuAbiString == null) {
7906                    continue;
7907                }
7908
7909                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7910                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7911                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7912                    // this but there's not much we can do.
7913                    String errorMessage = "Instruction set mismatch, "
7914                            + ((requirer == null) ? "[caller]" : requirer)
7915                            + " requires " + requiredInstructionSet + " whereas " + ps
7916                            + " requires " + instructionSet;
7917                    Slog.w(TAG, errorMessage);
7918                }
7919
7920                if (requiredInstructionSet == null) {
7921                    requiredInstructionSet = instructionSet;
7922                    requirer = ps;
7923                }
7924            }
7925        }
7926
7927        if (requiredInstructionSet != null) {
7928            String adjustedAbi;
7929            if (requirer != null) {
7930                // requirer != null implies that either scannedPackage was null or that scannedPackage
7931                // did not require an ABI, in which case we have to adjust scannedPackage to match
7932                // the ABI of the set (which is the same as requirer's ABI)
7933                adjustedAbi = requirer.primaryCpuAbiString;
7934                if (scannedPackage != null) {
7935                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7936                }
7937            } else {
7938                // requirer == null implies that we're updating all ABIs in the set to
7939                // match scannedPackage.
7940                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7941            }
7942
7943            for (PackageSetting ps : packagesForUser) {
7944                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7945                    if (ps.primaryCpuAbiString != null) {
7946                        continue;
7947                    }
7948
7949                    ps.primaryCpuAbiString = adjustedAbi;
7950                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7951                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7952                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7953                        mInstaller.rmdex(ps.codePathString,
7954                                getDexCodeInstructionSet(getPreferredInstructionSet()));
7955                    }
7956                }
7957            }
7958        }
7959    }
7960
7961    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7962        synchronized (mPackages) {
7963            mResolverReplaced = true;
7964            // Set up information for custom user intent resolution activity.
7965            mResolveActivity.applicationInfo = pkg.applicationInfo;
7966            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7967            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7968            mResolveActivity.processName = pkg.applicationInfo.packageName;
7969            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7970            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7971                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7972            mResolveActivity.theme = 0;
7973            mResolveActivity.exported = true;
7974            mResolveActivity.enabled = true;
7975            mResolveInfo.activityInfo = mResolveActivity;
7976            mResolveInfo.priority = 0;
7977            mResolveInfo.preferredOrder = 0;
7978            mResolveInfo.match = 0;
7979            mResolveComponentName = mCustomResolverComponentName;
7980            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7981                    mResolveComponentName);
7982        }
7983    }
7984
7985    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
7986        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
7987
7988        // Set up information for ephemeral installer activity
7989        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
7990        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
7991        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
7992        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
7993        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7994        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7995                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7996        mEphemeralInstallerActivity.theme = 0;
7997        mEphemeralInstallerActivity.exported = true;
7998        mEphemeralInstallerActivity.enabled = true;
7999        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8000        mEphemeralInstallerInfo.priority = 0;
8001        mEphemeralInstallerInfo.preferredOrder = 0;
8002        mEphemeralInstallerInfo.match = 0;
8003
8004        if (DEBUG_EPHEMERAL) {
8005            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8006        }
8007    }
8008
8009    private static String calculateBundledApkRoot(final String codePathString) {
8010        final File codePath = new File(codePathString);
8011        final File codeRoot;
8012        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8013            codeRoot = Environment.getRootDirectory();
8014        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8015            codeRoot = Environment.getOemDirectory();
8016        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8017            codeRoot = Environment.getVendorDirectory();
8018        } else {
8019            // Unrecognized code path; take its top real segment as the apk root:
8020            // e.g. /something/app/blah.apk => /something
8021            try {
8022                File f = codePath.getCanonicalFile();
8023                File parent = f.getParentFile();    // non-null because codePath is a file
8024                File tmp;
8025                while ((tmp = parent.getParentFile()) != null) {
8026                    f = parent;
8027                    parent = tmp;
8028                }
8029                codeRoot = f;
8030                Slog.w(TAG, "Unrecognized code path "
8031                        + codePath + " - using " + codeRoot);
8032            } catch (IOException e) {
8033                // Can't canonicalize the code path -- shenanigans?
8034                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8035                return Environment.getRootDirectory().getPath();
8036            }
8037        }
8038        return codeRoot.getPath();
8039    }
8040
8041    /**
8042     * Derive and set the location of native libraries for the given package,
8043     * which varies depending on where and how the package was installed.
8044     */
8045    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8046        final ApplicationInfo info = pkg.applicationInfo;
8047        final String codePath = pkg.codePath;
8048        final File codeFile = new File(codePath);
8049        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8050        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8051
8052        info.nativeLibraryRootDir = null;
8053        info.nativeLibraryRootRequiresIsa = false;
8054        info.nativeLibraryDir = null;
8055        info.secondaryNativeLibraryDir = null;
8056
8057        if (isApkFile(codeFile)) {
8058            // Monolithic install
8059            if (bundledApp) {
8060                // If "/system/lib64/apkname" exists, assume that is the per-package
8061                // native library directory to use; otherwise use "/system/lib/apkname".
8062                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8063                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8064                        getPrimaryInstructionSet(info));
8065
8066                // This is a bundled system app so choose the path based on the ABI.
8067                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8068                // is just the default path.
8069                final String apkName = deriveCodePathName(codePath);
8070                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8071                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8072                        apkName).getAbsolutePath();
8073
8074                if (info.secondaryCpuAbi != null) {
8075                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8076                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8077                            secondaryLibDir, apkName).getAbsolutePath();
8078                }
8079            } else if (asecApp) {
8080                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8081                        .getAbsolutePath();
8082            } else {
8083                final String apkName = deriveCodePathName(codePath);
8084                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8085                        .getAbsolutePath();
8086            }
8087
8088            info.nativeLibraryRootRequiresIsa = false;
8089            info.nativeLibraryDir = info.nativeLibraryRootDir;
8090        } else {
8091            // Cluster install
8092            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8093            info.nativeLibraryRootRequiresIsa = true;
8094
8095            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8096                    getPrimaryInstructionSet(info)).getAbsolutePath();
8097
8098            if (info.secondaryCpuAbi != null) {
8099                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8100                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8101            }
8102        }
8103    }
8104
8105    /**
8106     * Calculate the abis and roots for a bundled app. These can uniquely
8107     * be determined from the contents of the system partition, i.e whether
8108     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8109     * of this information, and instead assume that the system was built
8110     * sensibly.
8111     */
8112    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8113                                           PackageSetting pkgSetting) {
8114        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8115
8116        // If "/system/lib64/apkname" exists, assume that is the per-package
8117        // native library directory to use; otherwise use "/system/lib/apkname".
8118        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8119        setBundledAppAbi(pkg, apkRoot, apkName);
8120        // pkgSetting might be null during rescan following uninstall of updates
8121        // to a bundled app, so accommodate that possibility.  The settings in
8122        // that case will be established later from the parsed package.
8123        //
8124        // If the settings aren't null, sync them up with what we've just derived.
8125        // note that apkRoot isn't stored in the package settings.
8126        if (pkgSetting != null) {
8127            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8128            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8129        }
8130    }
8131
8132    /**
8133     * Deduces the ABI of a bundled app and sets the relevant fields on the
8134     * parsed pkg object.
8135     *
8136     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8137     *        under which system libraries are installed.
8138     * @param apkName the name of the installed package.
8139     */
8140    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8141        final File codeFile = new File(pkg.codePath);
8142
8143        final boolean has64BitLibs;
8144        final boolean has32BitLibs;
8145        if (isApkFile(codeFile)) {
8146            // Monolithic install
8147            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8148            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8149        } else {
8150            // Cluster install
8151            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8152            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8153                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8154                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8155                has64BitLibs = (new File(rootDir, isa)).exists();
8156            } else {
8157                has64BitLibs = false;
8158            }
8159            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8160                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8161                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8162                has32BitLibs = (new File(rootDir, isa)).exists();
8163            } else {
8164                has32BitLibs = false;
8165            }
8166        }
8167
8168        if (has64BitLibs && !has32BitLibs) {
8169            // The package has 64 bit libs, but not 32 bit libs. Its primary
8170            // ABI should be 64 bit. We can safely assume here that the bundled
8171            // native libraries correspond to the most preferred ABI in the list.
8172
8173            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8174            pkg.applicationInfo.secondaryCpuAbi = null;
8175        } else if (has32BitLibs && !has64BitLibs) {
8176            // The package has 32 bit libs but not 64 bit libs. Its primary
8177            // ABI should be 32 bit.
8178
8179            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8180            pkg.applicationInfo.secondaryCpuAbi = null;
8181        } else if (has32BitLibs && has64BitLibs) {
8182            // The application has both 64 and 32 bit bundled libraries. We check
8183            // here that the app declares multiArch support, and warn if it doesn't.
8184            //
8185            // We will be lenient here and record both ABIs. The primary will be the
8186            // ABI that's higher on the list, i.e, a device that's configured to prefer
8187            // 64 bit apps will see a 64 bit primary ABI,
8188
8189            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8190                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8191            }
8192
8193            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8194                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8195                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8196            } else {
8197                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8198                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8199            }
8200        } else {
8201            pkg.applicationInfo.primaryCpuAbi = null;
8202            pkg.applicationInfo.secondaryCpuAbi = null;
8203        }
8204    }
8205
8206    private void killApplication(String pkgName, int appId, String reason) {
8207        // Request the ActivityManager to kill the process(only for existing packages)
8208        // so that we do not end up in a confused state while the user is still using the older
8209        // version of the application while the new one gets installed.
8210        IActivityManager am = ActivityManagerNative.getDefault();
8211        if (am != null) {
8212            try {
8213                am.killApplicationWithAppId(pkgName, appId, reason);
8214            } catch (RemoteException e) {
8215            }
8216        }
8217    }
8218
8219    void removePackageLI(PackageSetting ps, boolean chatty) {
8220        if (DEBUG_INSTALL) {
8221            if (chatty)
8222                Log.d(TAG, "Removing package " + ps.name);
8223        }
8224
8225        // writer
8226        synchronized (mPackages) {
8227            mPackages.remove(ps.name);
8228            final PackageParser.Package pkg = ps.pkg;
8229            if (pkg != null) {
8230                cleanPackageDataStructuresLILPw(pkg, chatty);
8231            }
8232        }
8233    }
8234
8235    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8236        if (DEBUG_INSTALL) {
8237            if (chatty)
8238                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8239        }
8240
8241        // writer
8242        synchronized (mPackages) {
8243            mPackages.remove(pkg.applicationInfo.packageName);
8244            cleanPackageDataStructuresLILPw(pkg, chatty);
8245        }
8246    }
8247
8248    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8249        int N = pkg.providers.size();
8250        StringBuilder r = null;
8251        int i;
8252        for (i=0; i<N; i++) {
8253            PackageParser.Provider p = pkg.providers.get(i);
8254            mProviders.removeProvider(p);
8255            if (p.info.authority == null) {
8256
8257                /* There was another ContentProvider with this authority when
8258                 * this app was installed so this authority is null,
8259                 * Ignore it as we don't have to unregister the provider.
8260                 */
8261                continue;
8262            }
8263            String names[] = p.info.authority.split(";");
8264            for (int j = 0; j < names.length; j++) {
8265                if (mProvidersByAuthority.get(names[j]) == p) {
8266                    mProvidersByAuthority.remove(names[j]);
8267                    if (DEBUG_REMOVE) {
8268                        if (chatty)
8269                            Log.d(TAG, "Unregistered content provider: " + names[j]
8270                                    + ", className = " + p.info.name + ", isSyncable = "
8271                                    + p.info.isSyncable);
8272                    }
8273                }
8274            }
8275            if (DEBUG_REMOVE && chatty) {
8276                if (r == null) {
8277                    r = new StringBuilder(256);
8278                } else {
8279                    r.append(' ');
8280                }
8281                r.append(p.info.name);
8282            }
8283        }
8284        if (r != null) {
8285            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8286        }
8287
8288        N = pkg.services.size();
8289        r = null;
8290        for (i=0; i<N; i++) {
8291            PackageParser.Service s = pkg.services.get(i);
8292            mServices.removeService(s);
8293            if (chatty) {
8294                if (r == null) {
8295                    r = new StringBuilder(256);
8296                } else {
8297                    r.append(' ');
8298                }
8299                r.append(s.info.name);
8300            }
8301        }
8302        if (r != null) {
8303            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8304        }
8305
8306        N = pkg.receivers.size();
8307        r = null;
8308        for (i=0; i<N; i++) {
8309            PackageParser.Activity a = pkg.receivers.get(i);
8310            mReceivers.removeActivity(a, "receiver");
8311            if (DEBUG_REMOVE && chatty) {
8312                if (r == null) {
8313                    r = new StringBuilder(256);
8314                } else {
8315                    r.append(' ');
8316                }
8317                r.append(a.info.name);
8318            }
8319        }
8320        if (r != null) {
8321            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8322        }
8323
8324        N = pkg.activities.size();
8325        r = null;
8326        for (i=0; i<N; i++) {
8327            PackageParser.Activity a = pkg.activities.get(i);
8328            mActivities.removeActivity(a, "activity");
8329            if (DEBUG_REMOVE && chatty) {
8330                if (r == null) {
8331                    r = new StringBuilder(256);
8332                } else {
8333                    r.append(' ');
8334                }
8335                r.append(a.info.name);
8336            }
8337        }
8338        if (r != null) {
8339            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8340        }
8341
8342        N = pkg.permissions.size();
8343        r = null;
8344        for (i=0; i<N; i++) {
8345            PackageParser.Permission p = pkg.permissions.get(i);
8346            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8347            if (bp == null) {
8348                bp = mSettings.mPermissionTrees.get(p.info.name);
8349            }
8350            if (bp != null && bp.perm == p) {
8351                bp.perm = null;
8352                if (DEBUG_REMOVE && chatty) {
8353                    if (r == null) {
8354                        r = new StringBuilder(256);
8355                    } else {
8356                        r.append(' ');
8357                    }
8358                    r.append(p.info.name);
8359                }
8360            }
8361            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8362                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8363                if (appOpPerms != null) {
8364                    appOpPerms.remove(pkg.packageName);
8365                }
8366            }
8367        }
8368        if (r != null) {
8369            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8370        }
8371
8372        N = pkg.requestedPermissions.size();
8373        r = null;
8374        for (i=0; i<N; i++) {
8375            String perm = pkg.requestedPermissions.get(i);
8376            BasePermission bp = mSettings.mPermissions.get(perm);
8377            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8378                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8379                if (appOpPerms != null) {
8380                    appOpPerms.remove(pkg.packageName);
8381                    if (appOpPerms.isEmpty()) {
8382                        mAppOpPermissionPackages.remove(perm);
8383                    }
8384                }
8385            }
8386        }
8387        if (r != null) {
8388            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8389        }
8390
8391        N = pkg.instrumentation.size();
8392        r = null;
8393        for (i=0; i<N; i++) {
8394            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8395            mInstrumentation.remove(a.getComponentName());
8396            if (DEBUG_REMOVE && chatty) {
8397                if (r == null) {
8398                    r = new StringBuilder(256);
8399                } else {
8400                    r.append(' ');
8401                }
8402                r.append(a.info.name);
8403            }
8404        }
8405        if (r != null) {
8406            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8407        }
8408
8409        r = null;
8410        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8411            // Only system apps can hold shared libraries.
8412            if (pkg.libraryNames != null) {
8413                for (i=0; i<pkg.libraryNames.size(); i++) {
8414                    String name = pkg.libraryNames.get(i);
8415                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8416                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8417                        mSharedLibraries.remove(name);
8418                        if (DEBUG_REMOVE && chatty) {
8419                            if (r == null) {
8420                                r = new StringBuilder(256);
8421                            } else {
8422                                r.append(' ');
8423                            }
8424                            r.append(name);
8425                        }
8426                    }
8427                }
8428            }
8429        }
8430        if (r != null) {
8431            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8432        }
8433    }
8434
8435    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8436        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8437            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8438                return true;
8439            }
8440        }
8441        return false;
8442    }
8443
8444    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8445    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8446    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8447
8448    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8449            int flags) {
8450        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8451        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8452    }
8453
8454    private void updatePermissionsLPw(String changingPkg,
8455            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8456        // Make sure there are no dangling permission trees.
8457        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8458        while (it.hasNext()) {
8459            final BasePermission bp = it.next();
8460            if (bp.packageSetting == null) {
8461                // We may not yet have parsed the package, so just see if
8462                // we still know about its settings.
8463                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8464            }
8465            if (bp.packageSetting == null) {
8466                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8467                        + " from package " + bp.sourcePackage);
8468                it.remove();
8469            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8470                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8471                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8472                            + " from package " + bp.sourcePackage);
8473                    flags |= UPDATE_PERMISSIONS_ALL;
8474                    it.remove();
8475                }
8476            }
8477        }
8478
8479        // Make sure all dynamic permissions have been assigned to a package,
8480        // and make sure there are no dangling permissions.
8481        it = mSettings.mPermissions.values().iterator();
8482        while (it.hasNext()) {
8483            final BasePermission bp = it.next();
8484            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8485                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8486                        + bp.name + " pkg=" + bp.sourcePackage
8487                        + " info=" + bp.pendingInfo);
8488                if (bp.packageSetting == null && bp.pendingInfo != null) {
8489                    final BasePermission tree = findPermissionTreeLP(bp.name);
8490                    if (tree != null && tree.perm != null) {
8491                        bp.packageSetting = tree.packageSetting;
8492                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8493                                new PermissionInfo(bp.pendingInfo));
8494                        bp.perm.info.packageName = tree.perm.info.packageName;
8495                        bp.perm.info.name = bp.name;
8496                        bp.uid = tree.uid;
8497                    }
8498                }
8499            }
8500            if (bp.packageSetting == null) {
8501                // We may not yet have parsed the package, so just see if
8502                // we still know about its settings.
8503                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8504            }
8505            if (bp.packageSetting == null) {
8506                Slog.w(TAG, "Removing dangling permission: " + bp.name
8507                        + " from package " + bp.sourcePackage);
8508                it.remove();
8509            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8510                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8511                    Slog.i(TAG, "Removing old permission: " + bp.name
8512                            + " from package " + bp.sourcePackage);
8513                    flags |= UPDATE_PERMISSIONS_ALL;
8514                    it.remove();
8515                }
8516            }
8517        }
8518
8519        // Now update the permissions for all packages, in particular
8520        // replace the granted permissions of the system packages.
8521        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8522            for (PackageParser.Package pkg : mPackages.values()) {
8523                if (pkg != pkgInfo) {
8524                    // Only replace for packages on requested volume
8525                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8526                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8527                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8528                    grantPermissionsLPw(pkg, replace, changingPkg);
8529                }
8530            }
8531        }
8532
8533        if (pkgInfo != null) {
8534            // Only replace for packages on requested volume
8535            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8536            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8537                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8538            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8539        }
8540    }
8541
8542    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8543            String packageOfInterest) {
8544        // IMPORTANT: There are two types of permissions: install and runtime.
8545        // Install time permissions are granted when the app is installed to
8546        // all device users and users added in the future. Runtime permissions
8547        // are granted at runtime explicitly to specific users. Normal and signature
8548        // protected permissions are install time permissions. Dangerous permissions
8549        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8550        // otherwise they are runtime permissions. This function does not manage
8551        // runtime permissions except for the case an app targeting Lollipop MR1
8552        // being upgraded to target a newer SDK, in which case dangerous permissions
8553        // are transformed from install time to runtime ones.
8554
8555        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8556        if (ps == null) {
8557            return;
8558        }
8559
8560        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8561
8562        PermissionsState permissionsState = ps.getPermissionsState();
8563        PermissionsState origPermissions = permissionsState;
8564
8565        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8566
8567        boolean runtimePermissionsRevoked = false;
8568        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8569
8570        boolean changedInstallPermission = false;
8571
8572        if (replace) {
8573            ps.installPermissionsFixed = false;
8574            if (!ps.isSharedUser()) {
8575                origPermissions = new PermissionsState(permissionsState);
8576                permissionsState.reset();
8577            } else {
8578                // We need to know only about runtime permission changes since the
8579                // calling code always writes the install permissions state but
8580                // the runtime ones are written only if changed. The only cases of
8581                // changed runtime permissions here are promotion of an install to
8582                // runtime and revocation of a runtime from a shared user.
8583                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8584                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8585                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8586                    runtimePermissionsRevoked = true;
8587                }
8588            }
8589        }
8590
8591        permissionsState.setGlobalGids(mGlobalGids);
8592
8593        final int N = pkg.requestedPermissions.size();
8594        for (int i=0; i<N; i++) {
8595            final String name = pkg.requestedPermissions.get(i);
8596            final BasePermission bp = mSettings.mPermissions.get(name);
8597
8598            if (DEBUG_INSTALL) {
8599                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8600            }
8601
8602            if (bp == null || bp.packageSetting == null) {
8603                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8604                    Slog.w(TAG, "Unknown permission " + name
8605                            + " in package " + pkg.packageName);
8606                }
8607                continue;
8608            }
8609
8610            final String perm = bp.name;
8611            boolean allowedSig = false;
8612            int grant = GRANT_DENIED;
8613
8614            // Keep track of app op permissions.
8615            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8616                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8617                if (pkgs == null) {
8618                    pkgs = new ArraySet<>();
8619                    mAppOpPermissionPackages.put(bp.name, pkgs);
8620                }
8621                pkgs.add(pkg.packageName);
8622            }
8623
8624            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8625            switch (level) {
8626                case PermissionInfo.PROTECTION_NORMAL: {
8627                    // For all apps normal permissions are install time ones.
8628                    grant = GRANT_INSTALL;
8629                } break;
8630
8631                case PermissionInfo.PROTECTION_DANGEROUS: {
8632                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8633                        // For legacy apps dangerous permissions are install time ones.
8634                        grant = GRANT_INSTALL_LEGACY;
8635                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8636                        // For legacy apps that became modern, install becomes runtime.
8637                        grant = GRANT_UPGRADE;
8638                    } else if (mPromoteSystemApps
8639                            && isSystemApp(ps)
8640                            && mExistingSystemPackages.contains(ps.name)) {
8641                        // For legacy system apps, install becomes runtime.
8642                        // We cannot check hasInstallPermission() for system apps since those
8643                        // permissions were granted implicitly and not persisted pre-M.
8644                        grant = GRANT_UPGRADE;
8645                    } else {
8646                        // For modern apps keep runtime permissions unchanged.
8647                        grant = GRANT_RUNTIME;
8648                    }
8649                } break;
8650
8651                case PermissionInfo.PROTECTION_SIGNATURE: {
8652                    // For all apps signature permissions are install time ones.
8653                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8654                    if (allowedSig) {
8655                        grant = GRANT_INSTALL;
8656                    }
8657                } break;
8658            }
8659
8660            if (DEBUG_INSTALL) {
8661                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8662            }
8663
8664            if (grant != GRANT_DENIED) {
8665                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8666                    // If this is an existing, non-system package, then
8667                    // we can't add any new permissions to it.
8668                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8669                        // Except...  if this is a permission that was added
8670                        // to the platform (note: need to only do this when
8671                        // updating the platform).
8672                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8673                            grant = GRANT_DENIED;
8674                        }
8675                    }
8676                }
8677
8678                switch (grant) {
8679                    case GRANT_INSTALL: {
8680                        // Revoke this as runtime permission to handle the case of
8681                        // a runtime permission being downgraded to an install one.
8682                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8683                            if (origPermissions.getRuntimePermissionState(
8684                                    bp.name, userId) != null) {
8685                                // Revoke the runtime permission and clear the flags.
8686                                origPermissions.revokeRuntimePermission(bp, userId);
8687                                origPermissions.updatePermissionFlags(bp, userId,
8688                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8689                                // If we revoked a permission permission, we have to write.
8690                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8691                                        changedRuntimePermissionUserIds, userId);
8692                            }
8693                        }
8694                        // Grant an install permission.
8695                        if (permissionsState.grantInstallPermission(bp) !=
8696                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8697                            changedInstallPermission = true;
8698                        }
8699                    } break;
8700
8701                    case GRANT_INSTALL_LEGACY: {
8702                        // Grant an install permission.
8703                        if (permissionsState.grantInstallPermission(bp) !=
8704                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8705                            changedInstallPermission = true;
8706                        }
8707                    } break;
8708
8709                    case GRANT_RUNTIME: {
8710                        // Grant previously granted runtime permissions.
8711                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8712                            PermissionState permissionState = origPermissions
8713                                    .getRuntimePermissionState(bp.name, userId);
8714                            final int flags = permissionState != null
8715                                    ? permissionState.getFlags() : 0;
8716                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8717                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8718                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8719                                    // If we cannot put the permission as it was, we have to write.
8720                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8721                                            changedRuntimePermissionUserIds, userId);
8722                                }
8723                            }
8724                            // Propagate the permission flags.
8725                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8726                        }
8727                    } break;
8728
8729                    case GRANT_UPGRADE: {
8730                        // Grant runtime permissions for a previously held install permission.
8731                        PermissionState permissionState = origPermissions
8732                                .getInstallPermissionState(bp.name);
8733                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8734
8735                        if (origPermissions.revokeInstallPermission(bp)
8736                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8737                            // We will be transferring the permission flags, so clear them.
8738                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8739                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8740                            changedInstallPermission = true;
8741                        }
8742
8743                        // If the permission is not to be promoted to runtime we ignore it and
8744                        // also its other flags as they are not applicable to install permissions.
8745                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8746                            for (int userId : currentUserIds) {
8747                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8748                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8749                                    // Transfer the permission flags.
8750                                    permissionsState.updatePermissionFlags(bp, userId,
8751                                            flags, flags);
8752                                    // If we granted the permission, we have to write.
8753                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8754                                            changedRuntimePermissionUserIds, userId);
8755                                }
8756                            }
8757                        }
8758                    } break;
8759
8760                    default: {
8761                        if (packageOfInterest == null
8762                                || packageOfInterest.equals(pkg.packageName)) {
8763                            Slog.w(TAG, "Not granting permission " + perm
8764                                    + " to package " + pkg.packageName
8765                                    + " because it was previously installed without");
8766                        }
8767                    } break;
8768                }
8769            } else {
8770                if (permissionsState.revokeInstallPermission(bp) !=
8771                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8772                    // Also drop the permission flags.
8773                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8774                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8775                    changedInstallPermission = true;
8776                    Slog.i(TAG, "Un-granting permission " + perm
8777                            + " from package " + pkg.packageName
8778                            + " (protectionLevel=" + bp.protectionLevel
8779                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8780                            + ")");
8781                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8782                    // Don't print warning for app op permissions, since it is fine for them
8783                    // not to be granted, there is a UI for the user to decide.
8784                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8785                        Slog.w(TAG, "Not granting permission " + perm
8786                                + " to package " + pkg.packageName
8787                                + " (protectionLevel=" + bp.protectionLevel
8788                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8789                                + ")");
8790                    }
8791                }
8792            }
8793        }
8794
8795        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8796                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8797            // This is the first that we have heard about this package, so the
8798            // permissions we have now selected are fixed until explicitly
8799            // changed.
8800            ps.installPermissionsFixed = true;
8801        }
8802
8803        // Persist the runtime permissions state for users with changes. If permissions
8804        // were revoked because no app in the shared user declares them we have to
8805        // write synchronously to avoid losing runtime permissions state.
8806        for (int userId : changedRuntimePermissionUserIds) {
8807            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8808        }
8809
8810        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8811    }
8812
8813    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8814        boolean allowed = false;
8815        final int NP = PackageParser.NEW_PERMISSIONS.length;
8816        for (int ip=0; ip<NP; ip++) {
8817            final PackageParser.NewPermissionInfo npi
8818                    = PackageParser.NEW_PERMISSIONS[ip];
8819            if (npi.name.equals(perm)
8820                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8821                allowed = true;
8822                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8823                        + pkg.packageName);
8824                break;
8825            }
8826        }
8827        return allowed;
8828    }
8829
8830    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8831            BasePermission bp, PermissionsState origPermissions) {
8832        boolean allowed;
8833        allowed = (compareSignatures(
8834                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8835                        == PackageManager.SIGNATURE_MATCH)
8836                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8837                        == PackageManager.SIGNATURE_MATCH);
8838        if (!allowed && (bp.protectionLevel
8839                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8840            if (isSystemApp(pkg)) {
8841                // For updated system applications, a system permission
8842                // is granted only if it had been defined by the original application.
8843                if (pkg.isUpdatedSystemApp()) {
8844                    final PackageSetting sysPs = mSettings
8845                            .getDisabledSystemPkgLPr(pkg.packageName);
8846                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8847                        // If the original was granted this permission, we take
8848                        // that grant decision as read and propagate it to the
8849                        // update.
8850                        if (sysPs.isPrivileged()) {
8851                            allowed = true;
8852                        }
8853                    } else {
8854                        // The system apk may have been updated with an older
8855                        // version of the one on the data partition, but which
8856                        // granted a new system permission that it didn't have
8857                        // before.  In this case we do want to allow the app to
8858                        // now get the new permission if the ancestral apk is
8859                        // privileged to get it.
8860                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8861                            for (int j=0;
8862                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8863                                if (perm.equals(
8864                                        sysPs.pkg.requestedPermissions.get(j))) {
8865                                    allowed = true;
8866                                    break;
8867                                }
8868                            }
8869                        }
8870                    }
8871                } else {
8872                    allowed = isPrivilegedApp(pkg);
8873                }
8874            }
8875        }
8876        if (!allowed) {
8877            if (!allowed && (bp.protectionLevel
8878                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8879                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8880                // If this was a previously normal/dangerous permission that got moved
8881                // to a system permission as part of the runtime permission redesign, then
8882                // we still want to blindly grant it to old apps.
8883                allowed = true;
8884            }
8885            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8886                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8887                // If this permission is to be granted to the system installer and
8888                // this app is an installer, then it gets the permission.
8889                allowed = true;
8890            }
8891            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8892                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8893                // If this permission is to be granted to the system verifier and
8894                // this app is a verifier, then it gets the permission.
8895                allowed = true;
8896            }
8897            if (!allowed && (bp.protectionLevel
8898                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8899                    && isSystemApp(pkg)) {
8900                // Any pre-installed system app is allowed to get this permission.
8901                allowed = true;
8902            }
8903            if (!allowed && (bp.protectionLevel
8904                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8905                // For development permissions, a development permission
8906                // is granted only if it was already granted.
8907                allowed = origPermissions.hasInstallPermission(perm);
8908            }
8909        }
8910        return allowed;
8911    }
8912
8913    final class ActivityIntentResolver
8914            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8915        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8916                boolean defaultOnly, int userId) {
8917            if (!sUserManager.exists(userId)) return null;
8918            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8919            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8920        }
8921
8922        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8923                int userId) {
8924            if (!sUserManager.exists(userId)) return null;
8925            mFlags = flags;
8926            return super.queryIntent(intent, resolvedType,
8927                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8928        }
8929
8930        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8931                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8932            if (!sUserManager.exists(userId)) return null;
8933            if (packageActivities == null) {
8934                return null;
8935            }
8936            mFlags = flags;
8937            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8938            final int N = packageActivities.size();
8939            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8940                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8941
8942            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8943            for (int i = 0; i < N; ++i) {
8944                intentFilters = packageActivities.get(i).intents;
8945                if (intentFilters != null && intentFilters.size() > 0) {
8946                    PackageParser.ActivityIntentInfo[] array =
8947                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8948                    intentFilters.toArray(array);
8949                    listCut.add(array);
8950                }
8951            }
8952            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8953        }
8954
8955        public final void addActivity(PackageParser.Activity a, String type) {
8956            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8957            mActivities.put(a.getComponentName(), a);
8958            if (DEBUG_SHOW_INFO)
8959                Log.v(
8960                TAG, "  " + type + " " +
8961                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8962            if (DEBUG_SHOW_INFO)
8963                Log.v(TAG, "    Class=" + a.info.name);
8964            final int NI = a.intents.size();
8965            for (int j=0; j<NI; j++) {
8966                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8967                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8968                    intent.setPriority(0);
8969                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8970                            + a.className + " with priority > 0, forcing to 0");
8971                }
8972                if (DEBUG_SHOW_INFO) {
8973                    Log.v(TAG, "    IntentFilter:");
8974                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8975                }
8976                if (!intent.debugCheck()) {
8977                    Log.w(TAG, "==> For Activity " + a.info.name);
8978                }
8979                addFilter(intent);
8980            }
8981        }
8982
8983        public final void removeActivity(PackageParser.Activity a, String type) {
8984            mActivities.remove(a.getComponentName());
8985            if (DEBUG_SHOW_INFO) {
8986                Log.v(TAG, "  " + type + " "
8987                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8988                                : a.info.name) + ":");
8989                Log.v(TAG, "    Class=" + a.info.name);
8990            }
8991            final int NI = a.intents.size();
8992            for (int j=0; j<NI; j++) {
8993                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8994                if (DEBUG_SHOW_INFO) {
8995                    Log.v(TAG, "    IntentFilter:");
8996                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8997                }
8998                removeFilter(intent);
8999            }
9000        }
9001
9002        @Override
9003        protected boolean allowFilterResult(
9004                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9005            ActivityInfo filterAi = filter.activity.info;
9006            for (int i=dest.size()-1; i>=0; i--) {
9007                ActivityInfo destAi = dest.get(i).activityInfo;
9008                if (destAi.name == filterAi.name
9009                        && destAi.packageName == filterAi.packageName) {
9010                    return false;
9011                }
9012            }
9013            return true;
9014        }
9015
9016        @Override
9017        protected ActivityIntentInfo[] newArray(int size) {
9018            return new ActivityIntentInfo[size];
9019        }
9020
9021        @Override
9022        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9023            if (!sUserManager.exists(userId)) return true;
9024            PackageParser.Package p = filter.activity.owner;
9025            if (p != null) {
9026                PackageSetting ps = (PackageSetting)p.mExtras;
9027                if (ps != null) {
9028                    // System apps are never considered stopped for purposes of
9029                    // filtering, because there may be no way for the user to
9030                    // actually re-launch them.
9031                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9032                            && ps.getStopped(userId);
9033                }
9034            }
9035            return false;
9036        }
9037
9038        @Override
9039        protected boolean isPackageForFilter(String packageName,
9040                PackageParser.ActivityIntentInfo info) {
9041            return packageName.equals(info.activity.owner.packageName);
9042        }
9043
9044        @Override
9045        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9046                int match, int userId) {
9047            if (!sUserManager.exists(userId)) return null;
9048            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9049                return null;
9050            }
9051            final PackageParser.Activity activity = info.activity;
9052            if (mSafeMode && (activity.info.applicationInfo.flags
9053                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9054                return null;
9055            }
9056            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9057            if (ps == null) {
9058                return null;
9059            }
9060            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9061                    ps.readUserState(userId), userId);
9062            if (ai == null) {
9063                return null;
9064            }
9065            final ResolveInfo res = new ResolveInfo();
9066            res.activityInfo = ai;
9067            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9068                res.filter = info;
9069            }
9070            if (info != null) {
9071                res.handleAllWebDataURI = info.handleAllWebDataURI();
9072            }
9073            res.priority = info.getPriority();
9074            res.preferredOrder = activity.owner.mPreferredOrder;
9075            //System.out.println("Result: " + res.activityInfo.className +
9076            //                   " = " + res.priority);
9077            res.match = match;
9078            res.isDefault = info.hasDefault;
9079            res.labelRes = info.labelRes;
9080            res.nonLocalizedLabel = info.nonLocalizedLabel;
9081            if (userNeedsBadging(userId)) {
9082                res.noResourceId = true;
9083            } else {
9084                res.icon = info.icon;
9085            }
9086            res.iconResourceId = info.icon;
9087            res.system = res.activityInfo.applicationInfo.isSystemApp();
9088            return res;
9089        }
9090
9091        @Override
9092        protected void sortResults(List<ResolveInfo> results) {
9093            Collections.sort(results, mResolvePrioritySorter);
9094        }
9095
9096        @Override
9097        protected void dumpFilter(PrintWriter out, String prefix,
9098                PackageParser.ActivityIntentInfo filter) {
9099            out.print(prefix); out.print(
9100                    Integer.toHexString(System.identityHashCode(filter.activity)));
9101                    out.print(' ');
9102                    filter.activity.printComponentShortName(out);
9103                    out.print(" filter ");
9104                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9105        }
9106
9107        @Override
9108        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9109            return filter.activity;
9110        }
9111
9112        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9113            PackageParser.Activity activity = (PackageParser.Activity)label;
9114            out.print(prefix); out.print(
9115                    Integer.toHexString(System.identityHashCode(activity)));
9116                    out.print(' ');
9117                    activity.printComponentShortName(out);
9118            if (count > 1) {
9119                out.print(" ("); out.print(count); out.print(" filters)");
9120            }
9121            out.println();
9122        }
9123
9124//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9125//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9126//            final List<ResolveInfo> retList = Lists.newArrayList();
9127//            while (i.hasNext()) {
9128//                final ResolveInfo resolveInfo = i.next();
9129//                if (isEnabledLP(resolveInfo.activityInfo)) {
9130//                    retList.add(resolveInfo);
9131//                }
9132//            }
9133//            return retList;
9134//        }
9135
9136        // Keys are String (activity class name), values are Activity.
9137        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9138                = new ArrayMap<ComponentName, PackageParser.Activity>();
9139        private int mFlags;
9140    }
9141
9142    private final class ServiceIntentResolver
9143            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9144        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9145                boolean defaultOnly, int userId) {
9146            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9147            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9148        }
9149
9150        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9151                int userId) {
9152            if (!sUserManager.exists(userId)) return null;
9153            mFlags = flags;
9154            return super.queryIntent(intent, resolvedType,
9155                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9156        }
9157
9158        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9159                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9160            if (!sUserManager.exists(userId)) return null;
9161            if (packageServices == null) {
9162                return null;
9163            }
9164            mFlags = flags;
9165            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9166            final int N = packageServices.size();
9167            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9168                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9169
9170            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9171            for (int i = 0; i < N; ++i) {
9172                intentFilters = packageServices.get(i).intents;
9173                if (intentFilters != null && intentFilters.size() > 0) {
9174                    PackageParser.ServiceIntentInfo[] array =
9175                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9176                    intentFilters.toArray(array);
9177                    listCut.add(array);
9178                }
9179            }
9180            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9181        }
9182
9183        public final void addService(PackageParser.Service s) {
9184            mServices.put(s.getComponentName(), s);
9185            if (DEBUG_SHOW_INFO) {
9186                Log.v(TAG, "  "
9187                        + (s.info.nonLocalizedLabel != null
9188                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9189                Log.v(TAG, "    Class=" + s.info.name);
9190            }
9191            final int NI = s.intents.size();
9192            int j;
9193            for (j=0; j<NI; j++) {
9194                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9195                if (DEBUG_SHOW_INFO) {
9196                    Log.v(TAG, "    IntentFilter:");
9197                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9198                }
9199                if (!intent.debugCheck()) {
9200                    Log.w(TAG, "==> For Service " + s.info.name);
9201                }
9202                addFilter(intent);
9203            }
9204        }
9205
9206        public final void removeService(PackageParser.Service s) {
9207            mServices.remove(s.getComponentName());
9208            if (DEBUG_SHOW_INFO) {
9209                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9210                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9211                Log.v(TAG, "    Class=" + s.info.name);
9212            }
9213            final int NI = s.intents.size();
9214            int j;
9215            for (j=0; j<NI; j++) {
9216                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9217                if (DEBUG_SHOW_INFO) {
9218                    Log.v(TAG, "    IntentFilter:");
9219                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9220                }
9221                removeFilter(intent);
9222            }
9223        }
9224
9225        @Override
9226        protected boolean allowFilterResult(
9227                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9228            ServiceInfo filterSi = filter.service.info;
9229            for (int i=dest.size()-1; i>=0; i--) {
9230                ServiceInfo destAi = dest.get(i).serviceInfo;
9231                if (destAi.name == filterSi.name
9232                        && destAi.packageName == filterSi.packageName) {
9233                    return false;
9234                }
9235            }
9236            return true;
9237        }
9238
9239        @Override
9240        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9241            return new PackageParser.ServiceIntentInfo[size];
9242        }
9243
9244        @Override
9245        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9246            if (!sUserManager.exists(userId)) return true;
9247            PackageParser.Package p = filter.service.owner;
9248            if (p != null) {
9249                PackageSetting ps = (PackageSetting)p.mExtras;
9250                if (ps != null) {
9251                    // System apps are never considered stopped for purposes of
9252                    // filtering, because there may be no way for the user to
9253                    // actually re-launch them.
9254                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9255                            && ps.getStopped(userId);
9256                }
9257            }
9258            return false;
9259        }
9260
9261        @Override
9262        protected boolean isPackageForFilter(String packageName,
9263                PackageParser.ServiceIntentInfo info) {
9264            return packageName.equals(info.service.owner.packageName);
9265        }
9266
9267        @Override
9268        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9269                int match, int userId) {
9270            if (!sUserManager.exists(userId)) return null;
9271            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9272            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9273                return null;
9274            }
9275            final PackageParser.Service service = info.service;
9276            if (mSafeMode && (service.info.applicationInfo.flags
9277                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9278                return null;
9279            }
9280            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9281            if (ps == null) {
9282                return null;
9283            }
9284            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9285                    ps.readUserState(userId), userId);
9286            if (si == null) {
9287                return null;
9288            }
9289            final ResolveInfo res = new ResolveInfo();
9290            res.serviceInfo = si;
9291            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9292                res.filter = filter;
9293            }
9294            res.priority = info.getPriority();
9295            res.preferredOrder = service.owner.mPreferredOrder;
9296            res.match = match;
9297            res.isDefault = info.hasDefault;
9298            res.labelRes = info.labelRes;
9299            res.nonLocalizedLabel = info.nonLocalizedLabel;
9300            res.icon = info.icon;
9301            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9302            return res;
9303        }
9304
9305        @Override
9306        protected void sortResults(List<ResolveInfo> results) {
9307            Collections.sort(results, mResolvePrioritySorter);
9308        }
9309
9310        @Override
9311        protected void dumpFilter(PrintWriter out, String prefix,
9312                PackageParser.ServiceIntentInfo filter) {
9313            out.print(prefix); out.print(
9314                    Integer.toHexString(System.identityHashCode(filter.service)));
9315                    out.print(' ');
9316                    filter.service.printComponentShortName(out);
9317                    out.print(" filter ");
9318                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9319        }
9320
9321        @Override
9322        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9323            return filter.service;
9324        }
9325
9326        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9327            PackageParser.Service service = (PackageParser.Service)label;
9328            out.print(prefix); out.print(
9329                    Integer.toHexString(System.identityHashCode(service)));
9330                    out.print(' ');
9331                    service.printComponentShortName(out);
9332            if (count > 1) {
9333                out.print(" ("); out.print(count); out.print(" filters)");
9334            }
9335            out.println();
9336        }
9337
9338//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9339//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9340//            final List<ResolveInfo> retList = Lists.newArrayList();
9341//            while (i.hasNext()) {
9342//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9343//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9344//                    retList.add(resolveInfo);
9345//                }
9346//            }
9347//            return retList;
9348//        }
9349
9350        // Keys are String (activity class name), values are Activity.
9351        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9352                = new ArrayMap<ComponentName, PackageParser.Service>();
9353        private int mFlags;
9354    };
9355
9356    private final class ProviderIntentResolver
9357            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9358        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9359                boolean defaultOnly, int userId) {
9360            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9361            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9362        }
9363
9364        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9365                int userId) {
9366            if (!sUserManager.exists(userId))
9367                return null;
9368            mFlags = flags;
9369            return super.queryIntent(intent, resolvedType,
9370                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9371        }
9372
9373        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9374                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9375            if (!sUserManager.exists(userId))
9376                return null;
9377            if (packageProviders == null) {
9378                return null;
9379            }
9380            mFlags = flags;
9381            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9382            final int N = packageProviders.size();
9383            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9384                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9385
9386            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9387            for (int i = 0; i < N; ++i) {
9388                intentFilters = packageProviders.get(i).intents;
9389                if (intentFilters != null && intentFilters.size() > 0) {
9390                    PackageParser.ProviderIntentInfo[] array =
9391                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9392                    intentFilters.toArray(array);
9393                    listCut.add(array);
9394                }
9395            }
9396            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9397        }
9398
9399        public final void addProvider(PackageParser.Provider p) {
9400            if (mProviders.containsKey(p.getComponentName())) {
9401                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9402                return;
9403            }
9404
9405            mProviders.put(p.getComponentName(), p);
9406            if (DEBUG_SHOW_INFO) {
9407                Log.v(TAG, "  "
9408                        + (p.info.nonLocalizedLabel != null
9409                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9410                Log.v(TAG, "    Class=" + p.info.name);
9411            }
9412            final int NI = p.intents.size();
9413            int j;
9414            for (j = 0; j < NI; j++) {
9415                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9416                if (DEBUG_SHOW_INFO) {
9417                    Log.v(TAG, "    IntentFilter:");
9418                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9419                }
9420                if (!intent.debugCheck()) {
9421                    Log.w(TAG, "==> For Provider " + p.info.name);
9422                }
9423                addFilter(intent);
9424            }
9425        }
9426
9427        public final void removeProvider(PackageParser.Provider p) {
9428            mProviders.remove(p.getComponentName());
9429            if (DEBUG_SHOW_INFO) {
9430                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9431                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9432                Log.v(TAG, "    Class=" + p.info.name);
9433            }
9434            final int NI = p.intents.size();
9435            int j;
9436            for (j = 0; j < NI; j++) {
9437                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9438                if (DEBUG_SHOW_INFO) {
9439                    Log.v(TAG, "    IntentFilter:");
9440                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9441                }
9442                removeFilter(intent);
9443            }
9444        }
9445
9446        @Override
9447        protected boolean allowFilterResult(
9448                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9449            ProviderInfo filterPi = filter.provider.info;
9450            for (int i = dest.size() - 1; i >= 0; i--) {
9451                ProviderInfo destPi = dest.get(i).providerInfo;
9452                if (destPi.name == filterPi.name
9453                        && destPi.packageName == filterPi.packageName) {
9454                    return false;
9455                }
9456            }
9457            return true;
9458        }
9459
9460        @Override
9461        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9462            return new PackageParser.ProviderIntentInfo[size];
9463        }
9464
9465        @Override
9466        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9467            if (!sUserManager.exists(userId))
9468                return true;
9469            PackageParser.Package p = filter.provider.owner;
9470            if (p != null) {
9471                PackageSetting ps = (PackageSetting) p.mExtras;
9472                if (ps != null) {
9473                    // System apps are never considered stopped for purposes of
9474                    // filtering, because there may be no way for the user to
9475                    // actually re-launch them.
9476                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9477                            && ps.getStopped(userId);
9478                }
9479            }
9480            return false;
9481        }
9482
9483        @Override
9484        protected boolean isPackageForFilter(String packageName,
9485                PackageParser.ProviderIntentInfo info) {
9486            return packageName.equals(info.provider.owner.packageName);
9487        }
9488
9489        @Override
9490        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9491                int match, int userId) {
9492            if (!sUserManager.exists(userId))
9493                return null;
9494            final PackageParser.ProviderIntentInfo info = filter;
9495            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9496                return null;
9497            }
9498            final PackageParser.Provider provider = info.provider;
9499            if (mSafeMode && (provider.info.applicationInfo.flags
9500                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9501                return null;
9502            }
9503            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9504            if (ps == null) {
9505                return null;
9506            }
9507            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9508                    ps.readUserState(userId), userId);
9509            if (pi == null) {
9510                return null;
9511            }
9512            final ResolveInfo res = new ResolveInfo();
9513            res.providerInfo = pi;
9514            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9515                res.filter = filter;
9516            }
9517            res.priority = info.getPriority();
9518            res.preferredOrder = provider.owner.mPreferredOrder;
9519            res.match = match;
9520            res.isDefault = info.hasDefault;
9521            res.labelRes = info.labelRes;
9522            res.nonLocalizedLabel = info.nonLocalizedLabel;
9523            res.icon = info.icon;
9524            res.system = res.providerInfo.applicationInfo.isSystemApp();
9525            return res;
9526        }
9527
9528        @Override
9529        protected void sortResults(List<ResolveInfo> results) {
9530            Collections.sort(results, mResolvePrioritySorter);
9531        }
9532
9533        @Override
9534        protected void dumpFilter(PrintWriter out, String prefix,
9535                PackageParser.ProviderIntentInfo filter) {
9536            out.print(prefix);
9537            out.print(
9538                    Integer.toHexString(System.identityHashCode(filter.provider)));
9539            out.print(' ');
9540            filter.provider.printComponentShortName(out);
9541            out.print(" filter ");
9542            out.println(Integer.toHexString(System.identityHashCode(filter)));
9543        }
9544
9545        @Override
9546        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9547            return filter.provider;
9548        }
9549
9550        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9551            PackageParser.Provider provider = (PackageParser.Provider)label;
9552            out.print(prefix); out.print(
9553                    Integer.toHexString(System.identityHashCode(provider)));
9554                    out.print(' ');
9555                    provider.printComponentShortName(out);
9556            if (count > 1) {
9557                out.print(" ("); out.print(count); out.print(" filters)");
9558            }
9559            out.println();
9560        }
9561
9562        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9563                = new ArrayMap<ComponentName, PackageParser.Provider>();
9564        private int mFlags;
9565    }
9566
9567    private static final class EphemeralIntentResolver
9568            extends IntentResolver<IntentFilter, ResolveInfo> {
9569        @Override
9570        protected IntentFilter[] newArray(int size) {
9571            return new IntentFilter[size];
9572        }
9573
9574        @Override
9575        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9576            return true;
9577        }
9578
9579        @Override
9580        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9581            if (!sUserManager.exists(userId)) return null;
9582            final ResolveInfo res = new ResolveInfo();
9583            res.filter = info;
9584            return res;
9585        }
9586    }
9587
9588    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9589            new Comparator<ResolveInfo>() {
9590        public int compare(ResolveInfo r1, ResolveInfo r2) {
9591            int v1 = r1.priority;
9592            int v2 = r2.priority;
9593            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9594            if (v1 != v2) {
9595                return (v1 > v2) ? -1 : 1;
9596            }
9597            v1 = r1.preferredOrder;
9598            v2 = r2.preferredOrder;
9599            if (v1 != v2) {
9600                return (v1 > v2) ? -1 : 1;
9601            }
9602            if (r1.isDefault != r2.isDefault) {
9603                return r1.isDefault ? -1 : 1;
9604            }
9605            v1 = r1.match;
9606            v2 = r2.match;
9607            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9608            if (v1 != v2) {
9609                return (v1 > v2) ? -1 : 1;
9610            }
9611            if (r1.system != r2.system) {
9612                return r1.system ? -1 : 1;
9613            }
9614            return 0;
9615        }
9616    };
9617
9618    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9619            new Comparator<ProviderInfo>() {
9620        public int compare(ProviderInfo p1, ProviderInfo p2) {
9621            final int v1 = p1.initOrder;
9622            final int v2 = p2.initOrder;
9623            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9624        }
9625    };
9626
9627    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9628            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9629            final int[] userIds) {
9630        mHandler.post(new Runnable() {
9631            @Override
9632            public void run() {
9633                try {
9634                    final IActivityManager am = ActivityManagerNative.getDefault();
9635                    if (am == null) return;
9636                    final int[] resolvedUserIds;
9637                    if (userIds == null) {
9638                        resolvedUserIds = am.getRunningUserIds();
9639                    } else {
9640                        resolvedUserIds = userIds;
9641                    }
9642                    for (int id : resolvedUserIds) {
9643                        final Intent intent = new Intent(action,
9644                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9645                        if (extras != null) {
9646                            intent.putExtras(extras);
9647                        }
9648                        if (targetPkg != null) {
9649                            intent.setPackage(targetPkg);
9650                        }
9651                        // Modify the UID when posting to other users
9652                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9653                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9654                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9655                            intent.putExtra(Intent.EXTRA_UID, uid);
9656                        }
9657                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9658                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9659                        if (DEBUG_BROADCASTS) {
9660                            RuntimeException here = new RuntimeException("here");
9661                            here.fillInStackTrace();
9662                            Slog.d(TAG, "Sending to user " + id + ": "
9663                                    + intent.toShortString(false, true, false, false)
9664                                    + " " + intent.getExtras(), here);
9665                        }
9666                        am.broadcastIntent(null, intent, null, finishedReceiver,
9667                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9668                                null, finishedReceiver != null, false, id);
9669                    }
9670                } catch (RemoteException ex) {
9671                }
9672            }
9673        });
9674    }
9675
9676    /**
9677     * Check if the external storage media is available. This is true if there
9678     * is a mounted external storage medium or if the external storage is
9679     * emulated.
9680     */
9681    private boolean isExternalMediaAvailable() {
9682        return mMediaMounted || Environment.isExternalStorageEmulated();
9683    }
9684
9685    @Override
9686    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9687        // writer
9688        synchronized (mPackages) {
9689            if (!isExternalMediaAvailable()) {
9690                // If the external storage is no longer mounted at this point,
9691                // the caller may not have been able to delete all of this
9692                // packages files and can not delete any more.  Bail.
9693                return null;
9694            }
9695            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9696            if (lastPackage != null) {
9697                pkgs.remove(lastPackage);
9698            }
9699            if (pkgs.size() > 0) {
9700                return pkgs.get(0);
9701            }
9702        }
9703        return null;
9704    }
9705
9706    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9707        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9708                userId, andCode ? 1 : 0, packageName);
9709        if (mSystemReady) {
9710            msg.sendToTarget();
9711        } else {
9712            if (mPostSystemReadyMessages == null) {
9713                mPostSystemReadyMessages = new ArrayList<>();
9714            }
9715            mPostSystemReadyMessages.add(msg);
9716        }
9717    }
9718
9719    void startCleaningPackages() {
9720        // reader
9721        synchronized (mPackages) {
9722            if (!isExternalMediaAvailable()) {
9723                return;
9724            }
9725            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9726                return;
9727            }
9728        }
9729        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9730        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9731        IActivityManager am = ActivityManagerNative.getDefault();
9732        if (am != null) {
9733            try {
9734                am.startService(null, intent, null, mContext.getOpPackageName(),
9735                        UserHandle.USER_SYSTEM);
9736            } catch (RemoteException e) {
9737            }
9738        }
9739    }
9740
9741    @Override
9742    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9743            int installFlags, String installerPackageName, VerificationParams verificationParams,
9744            String packageAbiOverride) {
9745        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9746                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9747    }
9748
9749    @Override
9750    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9751            int installFlags, String installerPackageName, VerificationParams verificationParams,
9752            String packageAbiOverride, int userId) {
9753        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9754
9755        final int callingUid = Binder.getCallingUid();
9756        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9757
9758        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9759            try {
9760                if (observer != null) {
9761                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9762                }
9763            } catch (RemoteException re) {
9764            }
9765            return;
9766        }
9767
9768        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9769            installFlags |= PackageManager.INSTALL_FROM_ADB;
9770
9771        } else {
9772            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9773            // about installerPackageName.
9774
9775            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9776            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9777        }
9778
9779        UserHandle user;
9780        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9781            user = UserHandle.ALL;
9782        } else {
9783            user = new UserHandle(userId);
9784        }
9785
9786        // Only system components can circumvent runtime permissions when installing.
9787        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9788                && mContext.checkCallingOrSelfPermission(Manifest.permission
9789                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9790            throw new SecurityException("You need the "
9791                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9792                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9793        }
9794
9795        verificationParams.setInstallerUid(callingUid);
9796
9797        final File originFile = new File(originPath);
9798        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9799
9800        final Message msg = mHandler.obtainMessage(INIT_COPY);
9801        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9802                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9803        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9804        msg.obj = params;
9805
9806        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9807                System.identityHashCode(msg.obj));
9808        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9809                System.identityHashCode(msg.obj));
9810
9811        mHandler.sendMessage(msg);
9812    }
9813
9814    void installStage(String packageName, File stagedDir, String stagedCid,
9815            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9816            String installerPackageName, int installerUid, UserHandle user) {
9817        final VerificationParams verifParams = new VerificationParams(
9818                null, sessionParams.originatingUri, sessionParams.referrerUri,
9819                sessionParams.originatingUid, null);
9820        verifParams.setInstallerUid(installerUid);
9821
9822        final OriginInfo origin;
9823        if (stagedDir != null) {
9824            origin = OriginInfo.fromStagedFile(stagedDir);
9825        } else {
9826            origin = OriginInfo.fromStagedContainer(stagedCid);
9827        }
9828
9829        final Message msg = mHandler.obtainMessage(INIT_COPY);
9830        final InstallParams params = new InstallParams(origin, null, observer,
9831                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9832                verifParams, user, sessionParams.abiOverride,
9833                sessionParams.grantedRuntimePermissions);
9834        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9835        msg.obj = params;
9836
9837        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9838                System.identityHashCode(msg.obj));
9839        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9840                System.identityHashCode(msg.obj));
9841
9842        mHandler.sendMessage(msg);
9843    }
9844
9845    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9846        Bundle extras = new Bundle(1);
9847        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9848
9849        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9850                packageName, extras, 0, null, null, new int[] {userId});
9851        try {
9852            IActivityManager am = ActivityManagerNative.getDefault();
9853            final boolean isSystem =
9854                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9855            if (isSystem && am.isUserRunning(userId, 0)) {
9856                // The just-installed/enabled app is bundled on the system, so presumed
9857                // to be able to run automatically without needing an explicit launch.
9858                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9859                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9860                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9861                        .setPackage(packageName);
9862                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9863                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9864            }
9865        } catch (RemoteException e) {
9866            // shouldn't happen
9867            Slog.w(TAG, "Unable to bootstrap installed package", e);
9868        }
9869    }
9870
9871    @Override
9872    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9873            int userId) {
9874        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9875        PackageSetting pkgSetting;
9876        final int uid = Binder.getCallingUid();
9877        enforceCrossUserPermission(uid, userId, true, true,
9878                "setApplicationHiddenSetting for user " + userId);
9879
9880        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9881            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9882            return false;
9883        }
9884
9885        long callingId = Binder.clearCallingIdentity();
9886        try {
9887            boolean sendAdded = false;
9888            boolean sendRemoved = false;
9889            // writer
9890            synchronized (mPackages) {
9891                pkgSetting = mSettings.mPackages.get(packageName);
9892                if (pkgSetting == null) {
9893                    return false;
9894                }
9895                if (pkgSetting.getHidden(userId) != hidden) {
9896                    pkgSetting.setHidden(hidden, userId);
9897                    mSettings.writePackageRestrictionsLPr(userId);
9898                    if (hidden) {
9899                        sendRemoved = true;
9900                    } else {
9901                        sendAdded = true;
9902                    }
9903                }
9904            }
9905            if (sendAdded) {
9906                sendPackageAddedForUser(packageName, pkgSetting, userId);
9907                return true;
9908            }
9909            if (sendRemoved) {
9910                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9911                        "hiding pkg");
9912                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9913                return true;
9914            }
9915        } finally {
9916            Binder.restoreCallingIdentity(callingId);
9917        }
9918        return false;
9919    }
9920
9921    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9922            int userId) {
9923        final PackageRemovedInfo info = new PackageRemovedInfo();
9924        info.removedPackage = packageName;
9925        info.removedUsers = new int[] {userId};
9926        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9927        info.sendBroadcast(false, false, false);
9928    }
9929
9930    /**
9931     * Returns true if application is not found or there was an error. Otherwise it returns
9932     * the hidden state of the package for the given user.
9933     */
9934    @Override
9935    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9937        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9938                false, "getApplicationHidden for user " + userId);
9939        PackageSetting pkgSetting;
9940        long callingId = Binder.clearCallingIdentity();
9941        try {
9942            // writer
9943            synchronized (mPackages) {
9944                pkgSetting = mSettings.mPackages.get(packageName);
9945                if (pkgSetting == null) {
9946                    return true;
9947                }
9948                return pkgSetting.getHidden(userId);
9949            }
9950        } finally {
9951            Binder.restoreCallingIdentity(callingId);
9952        }
9953    }
9954
9955    /**
9956     * @hide
9957     */
9958    @Override
9959    public int installExistingPackageAsUser(String packageName, int userId) {
9960        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9961                null);
9962        PackageSetting pkgSetting;
9963        final int uid = Binder.getCallingUid();
9964        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9965                + userId);
9966        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9967            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9968        }
9969
9970        long callingId = Binder.clearCallingIdentity();
9971        try {
9972            boolean sendAdded = false;
9973
9974            // writer
9975            synchronized (mPackages) {
9976                pkgSetting = mSettings.mPackages.get(packageName);
9977                if (pkgSetting == null) {
9978                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9979                }
9980                if (!pkgSetting.getInstalled(userId)) {
9981                    pkgSetting.setInstalled(true, userId);
9982                    pkgSetting.setHidden(false, userId);
9983                    mSettings.writePackageRestrictionsLPr(userId);
9984                    sendAdded = true;
9985                }
9986            }
9987
9988            if (sendAdded) {
9989                sendPackageAddedForUser(packageName, pkgSetting, userId);
9990            }
9991        } finally {
9992            Binder.restoreCallingIdentity(callingId);
9993        }
9994
9995        return PackageManager.INSTALL_SUCCEEDED;
9996    }
9997
9998    boolean isUserRestricted(int userId, String restrictionKey) {
9999        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10000        if (restrictions.getBoolean(restrictionKey, false)) {
10001            Log.w(TAG, "User is restricted: " + restrictionKey);
10002            return true;
10003        }
10004        return false;
10005    }
10006
10007    @Override
10008    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10009        mContext.enforceCallingOrSelfPermission(
10010                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10011                "Only package verification agents can verify applications");
10012
10013        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10014        final PackageVerificationResponse response = new PackageVerificationResponse(
10015                verificationCode, Binder.getCallingUid());
10016        msg.arg1 = id;
10017        msg.obj = response;
10018        mHandler.sendMessage(msg);
10019    }
10020
10021    @Override
10022    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10023            long millisecondsToDelay) {
10024        mContext.enforceCallingOrSelfPermission(
10025                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10026                "Only package verification agents can extend verification timeouts");
10027
10028        final PackageVerificationState state = mPendingVerification.get(id);
10029        final PackageVerificationResponse response = new PackageVerificationResponse(
10030                verificationCodeAtTimeout, Binder.getCallingUid());
10031
10032        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10033            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10034        }
10035        if (millisecondsToDelay < 0) {
10036            millisecondsToDelay = 0;
10037        }
10038        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10039                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10040            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10041        }
10042
10043        if ((state != null) && !state.timeoutExtended()) {
10044            state.extendTimeout();
10045
10046            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10047            msg.arg1 = id;
10048            msg.obj = response;
10049            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10050        }
10051    }
10052
10053    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10054            int verificationCode, UserHandle user) {
10055        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10056        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10057        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10058        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10059        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10060
10061        mContext.sendBroadcastAsUser(intent, user,
10062                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10063    }
10064
10065    private ComponentName matchComponentForVerifier(String packageName,
10066            List<ResolveInfo> receivers) {
10067        ActivityInfo targetReceiver = null;
10068
10069        final int NR = receivers.size();
10070        for (int i = 0; i < NR; i++) {
10071            final ResolveInfo info = receivers.get(i);
10072            if (info.activityInfo == null) {
10073                continue;
10074            }
10075
10076            if (packageName.equals(info.activityInfo.packageName)) {
10077                targetReceiver = info.activityInfo;
10078                break;
10079            }
10080        }
10081
10082        if (targetReceiver == null) {
10083            return null;
10084        }
10085
10086        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10087    }
10088
10089    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10090            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10091        if (pkgInfo.verifiers.length == 0) {
10092            return null;
10093        }
10094
10095        final int N = pkgInfo.verifiers.length;
10096        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10097        for (int i = 0; i < N; i++) {
10098            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10099
10100            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10101                    receivers);
10102            if (comp == null) {
10103                continue;
10104            }
10105
10106            final int verifierUid = getUidForVerifier(verifierInfo);
10107            if (verifierUid == -1) {
10108                continue;
10109            }
10110
10111            if (DEBUG_VERIFY) {
10112                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10113                        + " with the correct signature");
10114            }
10115            sufficientVerifiers.add(comp);
10116            verificationState.addSufficientVerifier(verifierUid);
10117        }
10118
10119        return sufficientVerifiers;
10120    }
10121
10122    private int getUidForVerifier(VerifierInfo verifierInfo) {
10123        synchronized (mPackages) {
10124            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10125            if (pkg == null) {
10126                return -1;
10127            } else if (pkg.mSignatures.length != 1) {
10128                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10129                        + " has more than one signature; ignoring");
10130                return -1;
10131            }
10132
10133            /*
10134             * If the public key of the package's signature does not match
10135             * our expected public key, then this is a different package and
10136             * we should skip.
10137             */
10138
10139            final byte[] expectedPublicKey;
10140            try {
10141                final Signature verifierSig = pkg.mSignatures[0];
10142                final PublicKey publicKey = verifierSig.getPublicKey();
10143                expectedPublicKey = publicKey.getEncoded();
10144            } catch (CertificateException e) {
10145                return -1;
10146            }
10147
10148            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10149
10150            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10151                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10152                        + " does not have the expected public key; ignoring");
10153                return -1;
10154            }
10155
10156            return pkg.applicationInfo.uid;
10157        }
10158    }
10159
10160    @Override
10161    public void finishPackageInstall(int token) {
10162        enforceSystemOrRoot("Only the system is allowed to finish installs");
10163
10164        if (DEBUG_INSTALL) {
10165            Slog.v(TAG, "BM finishing package install for " + token);
10166        }
10167        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10168
10169        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10170        mHandler.sendMessage(msg);
10171    }
10172
10173    /**
10174     * Get the verification agent timeout.
10175     *
10176     * @return verification timeout in milliseconds
10177     */
10178    private long getVerificationTimeout() {
10179        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10180                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10181                DEFAULT_VERIFICATION_TIMEOUT);
10182    }
10183
10184    /**
10185     * Get the default verification agent response code.
10186     *
10187     * @return default verification response code
10188     */
10189    private int getDefaultVerificationResponse() {
10190        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10191                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10192                DEFAULT_VERIFICATION_RESPONSE);
10193    }
10194
10195    /**
10196     * Check whether or not package verification has been enabled.
10197     *
10198     * @return true if verification should be performed
10199     */
10200    private boolean isVerificationEnabled(int userId, int installFlags) {
10201        if (!DEFAULT_VERIFY_ENABLE) {
10202            return false;
10203        }
10204        // TODO: fix b/25118622; don't bypass verification
10205        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10206            return false;
10207        }
10208
10209        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10210
10211        // Check if installing from ADB
10212        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10213            // Do not run verification in a test harness environment
10214            if (ActivityManager.isRunningInTestHarness()) {
10215                return false;
10216            }
10217            if (ensureVerifyAppsEnabled) {
10218                return true;
10219            }
10220            // Check if the developer does not want package verification for ADB installs
10221            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10222                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10223                return false;
10224            }
10225        }
10226
10227        if (ensureVerifyAppsEnabled) {
10228            return true;
10229        }
10230
10231        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10232                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10233    }
10234
10235    @Override
10236    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10237            throws RemoteException {
10238        mContext.enforceCallingOrSelfPermission(
10239                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10240                "Only intentfilter verification agents can verify applications");
10241
10242        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10243        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10244                Binder.getCallingUid(), verificationCode, failedDomains);
10245        msg.arg1 = id;
10246        msg.obj = response;
10247        mHandler.sendMessage(msg);
10248    }
10249
10250    @Override
10251    public int getIntentVerificationStatus(String packageName, int userId) {
10252        synchronized (mPackages) {
10253            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10254        }
10255    }
10256
10257    @Override
10258    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10259        mContext.enforceCallingOrSelfPermission(
10260                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10261
10262        boolean result = false;
10263        synchronized (mPackages) {
10264            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10265        }
10266        if (result) {
10267            scheduleWritePackageRestrictionsLocked(userId);
10268        }
10269        return result;
10270    }
10271
10272    @Override
10273    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10274        synchronized (mPackages) {
10275            return mSettings.getIntentFilterVerificationsLPr(packageName);
10276        }
10277    }
10278
10279    @Override
10280    public List<IntentFilter> getAllIntentFilters(String packageName) {
10281        if (TextUtils.isEmpty(packageName)) {
10282            return Collections.<IntentFilter>emptyList();
10283        }
10284        synchronized (mPackages) {
10285            PackageParser.Package pkg = mPackages.get(packageName);
10286            if (pkg == null || pkg.activities == null) {
10287                return Collections.<IntentFilter>emptyList();
10288            }
10289            final int count = pkg.activities.size();
10290            ArrayList<IntentFilter> result = new ArrayList<>();
10291            for (int n=0; n<count; n++) {
10292                PackageParser.Activity activity = pkg.activities.get(n);
10293                if (activity.intents != null || activity.intents.size() > 0) {
10294                    result.addAll(activity.intents);
10295                }
10296            }
10297            return result;
10298        }
10299    }
10300
10301    @Override
10302    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10303        mContext.enforceCallingOrSelfPermission(
10304                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10305
10306        synchronized (mPackages) {
10307            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10308            if (packageName != null) {
10309                result |= updateIntentVerificationStatus(packageName,
10310                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10311                        userId);
10312                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10313                        packageName, userId);
10314            }
10315            return result;
10316        }
10317    }
10318
10319    @Override
10320    public String getDefaultBrowserPackageName(int userId) {
10321        synchronized (mPackages) {
10322            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10323        }
10324    }
10325
10326    /**
10327     * Get the "allow unknown sources" setting.
10328     *
10329     * @return the current "allow unknown sources" setting
10330     */
10331    private int getUnknownSourcesSettings() {
10332        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10333                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10334                -1);
10335    }
10336
10337    @Override
10338    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10339        final int uid = Binder.getCallingUid();
10340        // writer
10341        synchronized (mPackages) {
10342            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10343            if (targetPackageSetting == null) {
10344                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10345            }
10346
10347            PackageSetting installerPackageSetting;
10348            if (installerPackageName != null) {
10349                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10350                if (installerPackageSetting == null) {
10351                    throw new IllegalArgumentException("Unknown installer package: "
10352                            + installerPackageName);
10353                }
10354            } else {
10355                installerPackageSetting = null;
10356            }
10357
10358            Signature[] callerSignature;
10359            Object obj = mSettings.getUserIdLPr(uid);
10360            if (obj != null) {
10361                if (obj instanceof SharedUserSetting) {
10362                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10363                } else if (obj instanceof PackageSetting) {
10364                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10365                } else {
10366                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10367                }
10368            } else {
10369                throw new SecurityException("Unknown calling uid " + uid);
10370            }
10371
10372            // Verify: can't set installerPackageName to a package that is
10373            // not signed with the same cert as the caller.
10374            if (installerPackageSetting != null) {
10375                if (compareSignatures(callerSignature,
10376                        installerPackageSetting.signatures.mSignatures)
10377                        != PackageManager.SIGNATURE_MATCH) {
10378                    throw new SecurityException(
10379                            "Caller does not have same cert as new installer package "
10380                            + installerPackageName);
10381                }
10382            }
10383
10384            // Verify: if target already has an installer package, it must
10385            // be signed with the same cert as the caller.
10386            if (targetPackageSetting.installerPackageName != null) {
10387                PackageSetting setting = mSettings.mPackages.get(
10388                        targetPackageSetting.installerPackageName);
10389                // If the currently set package isn't valid, then it's always
10390                // okay to change it.
10391                if (setting != null) {
10392                    if (compareSignatures(callerSignature,
10393                            setting.signatures.mSignatures)
10394                            != PackageManager.SIGNATURE_MATCH) {
10395                        throw new SecurityException(
10396                                "Caller does not have same cert as old installer package "
10397                                + targetPackageSetting.installerPackageName);
10398                    }
10399                }
10400            }
10401
10402            // Okay!
10403            targetPackageSetting.installerPackageName = installerPackageName;
10404            scheduleWriteSettingsLocked();
10405        }
10406    }
10407
10408    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10409        // Queue up an async operation since the package installation may take a little while.
10410        mHandler.post(new Runnable() {
10411            public void run() {
10412                mHandler.removeCallbacks(this);
10413                 // Result object to be returned
10414                PackageInstalledInfo res = new PackageInstalledInfo();
10415                res.returnCode = currentStatus;
10416                res.uid = -1;
10417                res.pkg = null;
10418                res.removedInfo = new PackageRemovedInfo();
10419                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10420                    args.doPreInstall(res.returnCode);
10421                    synchronized (mInstallLock) {
10422                        installPackageTracedLI(args, res);
10423                    }
10424                    args.doPostInstall(res.returnCode, res.uid);
10425                }
10426
10427                // A restore should be performed at this point if (a) the install
10428                // succeeded, (b) the operation is not an update, and (c) the new
10429                // package has not opted out of backup participation.
10430                final boolean update = res.removedInfo.removedPackage != null;
10431                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10432                boolean doRestore = !update
10433                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10434
10435                // Set up the post-install work request bookkeeping.  This will be used
10436                // and cleaned up by the post-install event handling regardless of whether
10437                // there's a restore pass performed.  Token values are >= 1.
10438                int token;
10439                if (mNextInstallToken < 0) mNextInstallToken = 1;
10440                token = mNextInstallToken++;
10441
10442                PostInstallData data = new PostInstallData(args, res);
10443                mRunningInstalls.put(token, data);
10444                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10445
10446                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10447                    // Pass responsibility to the Backup Manager.  It will perform a
10448                    // restore if appropriate, then pass responsibility back to the
10449                    // Package Manager to run the post-install observer callbacks
10450                    // and broadcasts.
10451                    IBackupManager bm = IBackupManager.Stub.asInterface(
10452                            ServiceManager.getService(Context.BACKUP_SERVICE));
10453                    if (bm != null) {
10454                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10455                                + " to BM for possible restore");
10456                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10457                        try {
10458                            // TODO: http://b/22388012
10459                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10460                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10461                            } else {
10462                                doRestore = false;
10463                            }
10464                        } catch (RemoteException e) {
10465                            // can't happen; the backup manager is local
10466                        } catch (Exception e) {
10467                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10468                            doRestore = false;
10469                        }
10470                    } else {
10471                        Slog.e(TAG, "Backup Manager not found!");
10472                        doRestore = false;
10473                    }
10474                }
10475
10476                if (!doRestore) {
10477                    // No restore possible, or the Backup Manager was mysteriously not
10478                    // available -- just fire the post-install work request directly.
10479                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10480
10481                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10482
10483                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10484                    mHandler.sendMessage(msg);
10485                }
10486            }
10487        });
10488    }
10489
10490    private abstract class HandlerParams {
10491        private static final int MAX_RETRIES = 4;
10492
10493        /**
10494         * Number of times startCopy() has been attempted and had a non-fatal
10495         * error.
10496         */
10497        private int mRetries = 0;
10498
10499        /** User handle for the user requesting the information or installation. */
10500        private final UserHandle mUser;
10501        String traceMethod;
10502        int traceCookie;
10503
10504        HandlerParams(UserHandle user) {
10505            mUser = user;
10506        }
10507
10508        UserHandle getUser() {
10509            return mUser;
10510        }
10511
10512        HandlerParams setTraceMethod(String traceMethod) {
10513            this.traceMethod = traceMethod;
10514            return this;
10515        }
10516
10517        HandlerParams setTraceCookie(int traceCookie) {
10518            this.traceCookie = traceCookie;
10519            return this;
10520        }
10521
10522        final boolean startCopy() {
10523            boolean res;
10524            try {
10525                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10526
10527                if (++mRetries > MAX_RETRIES) {
10528                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10529                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10530                    handleServiceError();
10531                    return false;
10532                } else {
10533                    handleStartCopy();
10534                    res = true;
10535                }
10536            } catch (RemoteException e) {
10537                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10538                mHandler.sendEmptyMessage(MCS_RECONNECT);
10539                res = false;
10540            }
10541            handleReturnCode();
10542            return res;
10543        }
10544
10545        final void serviceError() {
10546            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10547            handleServiceError();
10548            handleReturnCode();
10549        }
10550
10551        abstract void handleStartCopy() throws RemoteException;
10552        abstract void handleServiceError();
10553        abstract void handleReturnCode();
10554    }
10555
10556    class MeasureParams extends HandlerParams {
10557        private final PackageStats mStats;
10558        private boolean mSuccess;
10559
10560        private final IPackageStatsObserver mObserver;
10561
10562        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10563            super(new UserHandle(stats.userHandle));
10564            mObserver = observer;
10565            mStats = stats;
10566        }
10567
10568        @Override
10569        public String toString() {
10570            return "MeasureParams{"
10571                + Integer.toHexString(System.identityHashCode(this))
10572                + " " + mStats.packageName + "}";
10573        }
10574
10575        @Override
10576        void handleStartCopy() throws RemoteException {
10577            synchronized (mInstallLock) {
10578                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10579            }
10580
10581            if (mSuccess) {
10582                final boolean mounted;
10583                if (Environment.isExternalStorageEmulated()) {
10584                    mounted = true;
10585                } else {
10586                    final String status = Environment.getExternalStorageState();
10587                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10588                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10589                }
10590
10591                if (mounted) {
10592                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10593
10594                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10595                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10596
10597                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10598                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10599
10600                    // Always subtract cache size, since it's a subdirectory
10601                    mStats.externalDataSize -= mStats.externalCacheSize;
10602
10603                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10604                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10605
10606                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10607                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10608                }
10609            }
10610        }
10611
10612        @Override
10613        void handleReturnCode() {
10614            if (mObserver != null) {
10615                try {
10616                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10617                } catch (RemoteException e) {
10618                    Slog.i(TAG, "Observer no longer exists.");
10619                }
10620            }
10621        }
10622
10623        @Override
10624        void handleServiceError() {
10625            Slog.e(TAG, "Could not measure application " + mStats.packageName
10626                            + " external storage");
10627        }
10628    }
10629
10630    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10631            throws RemoteException {
10632        long result = 0;
10633        for (File path : paths) {
10634            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10635        }
10636        return result;
10637    }
10638
10639    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10640        for (File path : paths) {
10641            try {
10642                mcs.clearDirectory(path.getAbsolutePath());
10643            } catch (RemoteException e) {
10644            }
10645        }
10646    }
10647
10648    static class OriginInfo {
10649        /**
10650         * Location where install is coming from, before it has been
10651         * copied/renamed into place. This could be a single monolithic APK
10652         * file, or a cluster directory. This location may be untrusted.
10653         */
10654        final File file;
10655        final String cid;
10656
10657        /**
10658         * Flag indicating that {@link #file} or {@link #cid} has already been
10659         * staged, meaning downstream users don't need to defensively copy the
10660         * contents.
10661         */
10662        final boolean staged;
10663
10664        /**
10665         * Flag indicating that {@link #file} or {@link #cid} is an already
10666         * installed app that is being moved.
10667         */
10668        final boolean existing;
10669
10670        final String resolvedPath;
10671        final File resolvedFile;
10672
10673        static OriginInfo fromNothing() {
10674            return new OriginInfo(null, null, false, false);
10675        }
10676
10677        static OriginInfo fromUntrustedFile(File file) {
10678            return new OriginInfo(file, null, false, false);
10679        }
10680
10681        static OriginInfo fromExistingFile(File file) {
10682            return new OriginInfo(file, null, false, true);
10683        }
10684
10685        static OriginInfo fromStagedFile(File file) {
10686            return new OriginInfo(file, null, true, false);
10687        }
10688
10689        static OriginInfo fromStagedContainer(String cid) {
10690            return new OriginInfo(null, cid, true, false);
10691        }
10692
10693        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10694            this.file = file;
10695            this.cid = cid;
10696            this.staged = staged;
10697            this.existing = existing;
10698
10699            if (cid != null) {
10700                resolvedPath = PackageHelper.getSdDir(cid);
10701                resolvedFile = new File(resolvedPath);
10702            } else if (file != null) {
10703                resolvedPath = file.getAbsolutePath();
10704                resolvedFile = file;
10705            } else {
10706                resolvedPath = null;
10707                resolvedFile = null;
10708            }
10709        }
10710    }
10711
10712    class MoveInfo {
10713        final int moveId;
10714        final String fromUuid;
10715        final String toUuid;
10716        final String packageName;
10717        final String dataAppName;
10718        final int appId;
10719        final String seinfo;
10720
10721        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10722                String dataAppName, int appId, String seinfo) {
10723            this.moveId = moveId;
10724            this.fromUuid = fromUuid;
10725            this.toUuid = toUuid;
10726            this.packageName = packageName;
10727            this.dataAppName = dataAppName;
10728            this.appId = appId;
10729            this.seinfo = seinfo;
10730        }
10731    }
10732
10733    class InstallParams extends HandlerParams {
10734        final OriginInfo origin;
10735        final MoveInfo move;
10736        final IPackageInstallObserver2 observer;
10737        int installFlags;
10738        final String installerPackageName;
10739        final String volumeUuid;
10740        final VerificationParams verificationParams;
10741        private InstallArgs mArgs;
10742        private int mRet;
10743        final String packageAbiOverride;
10744        final String[] grantedRuntimePermissions;
10745
10746        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10747                int installFlags, String installerPackageName, String volumeUuid,
10748                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10749                String[] grantedPermissions) {
10750            super(user);
10751            this.origin = origin;
10752            this.move = move;
10753            this.observer = observer;
10754            this.installFlags = installFlags;
10755            this.installerPackageName = installerPackageName;
10756            this.volumeUuid = volumeUuid;
10757            this.verificationParams = verificationParams;
10758            this.packageAbiOverride = packageAbiOverride;
10759            this.grantedRuntimePermissions = grantedPermissions;
10760        }
10761
10762        @Override
10763        public String toString() {
10764            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10765                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10766        }
10767
10768        public ManifestDigest getManifestDigest() {
10769            if (verificationParams == null) {
10770                return null;
10771            }
10772            return verificationParams.getManifestDigest();
10773        }
10774
10775        private int installLocationPolicy(PackageInfoLite pkgLite) {
10776            String packageName = pkgLite.packageName;
10777            int installLocation = pkgLite.installLocation;
10778            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10779            // reader
10780            synchronized (mPackages) {
10781                PackageParser.Package pkg = mPackages.get(packageName);
10782                if (pkg != null) {
10783                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10784                        // Check for downgrading.
10785                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10786                            try {
10787                                checkDowngrade(pkg, pkgLite);
10788                            } catch (PackageManagerException e) {
10789                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10790                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10791                            }
10792                        }
10793                        // Check for updated system application.
10794                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10795                            if (onSd) {
10796                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10797                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10798                            }
10799                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10800                        } else {
10801                            if (onSd) {
10802                                // Install flag overrides everything.
10803                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10804                            }
10805                            // If current upgrade specifies particular preference
10806                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10807                                // Application explicitly specified internal.
10808                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10809                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10810                                // App explictly prefers external. Let policy decide
10811                            } else {
10812                                // Prefer previous location
10813                                if (isExternal(pkg)) {
10814                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10815                                }
10816                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10817                            }
10818                        }
10819                    } else {
10820                        // Invalid install. Return error code
10821                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10822                    }
10823                }
10824            }
10825            // All the special cases have been taken care of.
10826            // Return result based on recommended install location.
10827            if (onSd) {
10828                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10829            }
10830            return pkgLite.recommendedInstallLocation;
10831        }
10832
10833        /*
10834         * Invoke remote method to get package information and install
10835         * location values. Override install location based on default
10836         * policy if needed and then create install arguments based
10837         * on the install location.
10838         */
10839        public void handleStartCopy() throws RemoteException {
10840            int ret = PackageManager.INSTALL_SUCCEEDED;
10841
10842            // If we're already staged, we've firmly committed to an install location
10843            if (origin.staged) {
10844                if (origin.file != null) {
10845                    installFlags |= PackageManager.INSTALL_INTERNAL;
10846                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10847                } else if (origin.cid != null) {
10848                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10849                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10850                } else {
10851                    throw new IllegalStateException("Invalid stage location");
10852                }
10853            }
10854
10855            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10856            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10857            PackageInfoLite pkgLite = null;
10858
10859            if (onInt && onSd) {
10860                // Check if both bits are set.
10861                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10862                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10863            } else {
10864                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10865                        packageAbiOverride);
10866
10867                /*
10868                 * If we have too little free space, try to free cache
10869                 * before giving up.
10870                 */
10871                if (!origin.staged && pkgLite.recommendedInstallLocation
10872                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10873                    // TODO: focus freeing disk space on the target device
10874                    final StorageManager storage = StorageManager.from(mContext);
10875                    final long lowThreshold = storage.getStorageLowBytes(
10876                            Environment.getDataDirectory());
10877
10878                    final long sizeBytes = mContainerService.calculateInstalledSize(
10879                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10880
10881                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10882                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10883                                installFlags, packageAbiOverride);
10884                    }
10885
10886                    /*
10887                     * The cache free must have deleted the file we
10888                     * downloaded to install.
10889                     *
10890                     * TODO: fix the "freeCache" call to not delete
10891                     *       the file we care about.
10892                     */
10893                    if (pkgLite.recommendedInstallLocation
10894                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10895                        pkgLite.recommendedInstallLocation
10896                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10897                    }
10898                }
10899            }
10900
10901            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10902                int loc = pkgLite.recommendedInstallLocation;
10903                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10904                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10905                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10906                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10907                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10908                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10909                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10910                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10911                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10912                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10913                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10914                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10915                } else {
10916                    // Override with defaults if needed.
10917                    loc = installLocationPolicy(pkgLite);
10918                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10919                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10920                    } else if (!onSd && !onInt) {
10921                        // Override install location with flags
10922                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10923                            // Set the flag to install on external media.
10924                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10925                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10926                        } else {
10927                            // Make sure the flag for installing on external
10928                            // media is unset
10929                            installFlags |= PackageManager.INSTALL_INTERNAL;
10930                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10931                        }
10932                    }
10933                }
10934            }
10935
10936            final InstallArgs args = createInstallArgs(this);
10937            mArgs = args;
10938
10939            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10940                // TODO: http://b/22976637
10941                // Apps installed for "all" users use the device owner to verify the app
10942                UserHandle verifierUser = getUser();
10943                if (verifierUser == UserHandle.ALL) {
10944                    verifierUser = UserHandle.SYSTEM;
10945                }
10946
10947                /*
10948                 * Determine if we have any installed package verifiers. If we
10949                 * do, then we'll defer to them to verify the packages.
10950                 */
10951                final int requiredUid = mRequiredVerifierPackage == null ? -1
10952                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10953                if (!origin.existing && requiredUid != -1
10954                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10955                    final Intent verification = new Intent(
10956                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10957                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10958                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10959                            PACKAGE_MIME_TYPE);
10960                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10961
10962                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10963                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10964                            verifierUser.getIdentifier());
10965
10966                    if (DEBUG_VERIFY) {
10967                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10968                                + verification.toString() + " with " + pkgLite.verifiers.length
10969                                + " optional verifiers");
10970                    }
10971
10972                    final int verificationId = mPendingVerificationToken++;
10973
10974                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10975
10976                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10977                            installerPackageName);
10978
10979                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10980                            installFlags);
10981
10982                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10983                            pkgLite.packageName);
10984
10985                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10986                            pkgLite.versionCode);
10987
10988                    if (verificationParams != null) {
10989                        if (verificationParams.getVerificationURI() != null) {
10990                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10991                                 verificationParams.getVerificationURI());
10992                        }
10993                        if (verificationParams.getOriginatingURI() != null) {
10994                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10995                                  verificationParams.getOriginatingURI());
10996                        }
10997                        if (verificationParams.getReferrer() != null) {
10998                            verification.putExtra(Intent.EXTRA_REFERRER,
10999                                  verificationParams.getReferrer());
11000                        }
11001                        if (verificationParams.getOriginatingUid() >= 0) {
11002                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11003                                  verificationParams.getOriginatingUid());
11004                        }
11005                        if (verificationParams.getInstallerUid() >= 0) {
11006                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11007                                  verificationParams.getInstallerUid());
11008                        }
11009                    }
11010
11011                    final PackageVerificationState verificationState = new PackageVerificationState(
11012                            requiredUid, args);
11013
11014                    mPendingVerification.append(verificationId, verificationState);
11015
11016                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11017                            receivers, verificationState);
11018
11019                    /*
11020                     * If any sufficient verifiers were listed in the package
11021                     * manifest, attempt to ask them.
11022                     */
11023                    if (sufficientVerifiers != null) {
11024                        final int N = sufficientVerifiers.size();
11025                        if (N == 0) {
11026                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11027                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11028                        } else {
11029                            for (int i = 0; i < N; i++) {
11030                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11031
11032                                final Intent sufficientIntent = new Intent(verification);
11033                                sufficientIntent.setComponent(verifierComponent);
11034                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11035                            }
11036                        }
11037                    }
11038
11039                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11040                            mRequiredVerifierPackage, receivers);
11041                    if (ret == PackageManager.INSTALL_SUCCEEDED
11042                            && mRequiredVerifierPackage != null) {
11043                        Trace.asyncTraceBegin(
11044                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11045                        /*
11046                         * Send the intent to the required verification agent,
11047                         * but only start the verification timeout after the
11048                         * target BroadcastReceivers have run.
11049                         */
11050                        verification.setComponent(requiredVerifierComponent);
11051                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11052                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11053                                new BroadcastReceiver() {
11054                                    @Override
11055                                    public void onReceive(Context context, Intent intent) {
11056                                        final Message msg = mHandler
11057                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11058                                        msg.arg1 = verificationId;
11059                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11060                                    }
11061                                }, null, 0, null, null);
11062
11063                        /*
11064                         * We don't want the copy to proceed until verification
11065                         * succeeds, so null out this field.
11066                         */
11067                        mArgs = null;
11068                    }
11069                } else {
11070                    /*
11071                     * No package verification is enabled, so immediately start
11072                     * the remote call to initiate copy using temporary file.
11073                     */
11074                    ret = args.copyApk(mContainerService, true);
11075                }
11076            }
11077
11078            mRet = ret;
11079        }
11080
11081        @Override
11082        void handleReturnCode() {
11083            // If mArgs is null, then MCS couldn't be reached. When it
11084            // reconnects, it will try again to install. At that point, this
11085            // will succeed.
11086            if (mArgs != null) {
11087                processPendingInstall(mArgs, mRet);
11088            }
11089        }
11090
11091        @Override
11092        void handleServiceError() {
11093            mArgs = createInstallArgs(this);
11094            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11095        }
11096
11097        public boolean isForwardLocked() {
11098            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11099        }
11100    }
11101
11102    /**
11103     * Used during creation of InstallArgs
11104     *
11105     * @param installFlags package installation flags
11106     * @return true if should be installed on external storage
11107     */
11108    private static boolean installOnExternalAsec(int installFlags) {
11109        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11110            return false;
11111        }
11112        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11113            return true;
11114        }
11115        return false;
11116    }
11117
11118    /**
11119     * Used during creation of InstallArgs
11120     *
11121     * @param installFlags package installation flags
11122     * @return true if should be installed as forward locked
11123     */
11124    private static boolean installForwardLocked(int installFlags) {
11125        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11126    }
11127
11128    private InstallArgs createInstallArgs(InstallParams params) {
11129        if (params.move != null) {
11130            return new MoveInstallArgs(params);
11131        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11132            return new AsecInstallArgs(params);
11133        } else {
11134            return new FileInstallArgs(params);
11135        }
11136    }
11137
11138    /**
11139     * Create args that describe an existing installed package. Typically used
11140     * when cleaning up old installs, or used as a move source.
11141     */
11142    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11143            String resourcePath, String[] instructionSets) {
11144        final boolean isInAsec;
11145        if (installOnExternalAsec(installFlags)) {
11146            /* Apps on SD card are always in ASEC containers. */
11147            isInAsec = true;
11148        } else if (installForwardLocked(installFlags)
11149                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11150            /*
11151             * Forward-locked apps are only in ASEC containers if they're the
11152             * new style
11153             */
11154            isInAsec = true;
11155        } else {
11156            isInAsec = false;
11157        }
11158
11159        if (isInAsec) {
11160            return new AsecInstallArgs(codePath, instructionSets,
11161                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11162        } else {
11163            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11164        }
11165    }
11166
11167    static abstract class InstallArgs {
11168        /** @see InstallParams#origin */
11169        final OriginInfo origin;
11170        /** @see InstallParams#move */
11171        final MoveInfo move;
11172
11173        final IPackageInstallObserver2 observer;
11174        // Always refers to PackageManager flags only
11175        final int installFlags;
11176        final String installerPackageName;
11177        final String volumeUuid;
11178        final ManifestDigest manifestDigest;
11179        final UserHandle user;
11180        final String abiOverride;
11181        final String[] installGrantPermissions;
11182        /** If non-null, drop an async trace when the install completes */
11183        final String traceMethod;
11184        final int traceCookie;
11185
11186        // The list of instruction sets supported by this app. This is currently
11187        // only used during the rmdex() phase to clean up resources. We can get rid of this
11188        // if we move dex files under the common app path.
11189        /* nullable */ String[] instructionSets;
11190
11191        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11192                int installFlags, String installerPackageName, String volumeUuid,
11193                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11194                String abiOverride, String[] installGrantPermissions,
11195                String traceMethod, int traceCookie) {
11196            this.origin = origin;
11197            this.move = move;
11198            this.installFlags = installFlags;
11199            this.observer = observer;
11200            this.installerPackageName = installerPackageName;
11201            this.volumeUuid = volumeUuid;
11202            this.manifestDigest = manifestDigest;
11203            this.user = user;
11204            this.instructionSets = instructionSets;
11205            this.abiOverride = abiOverride;
11206            this.installGrantPermissions = installGrantPermissions;
11207            this.traceMethod = traceMethod;
11208            this.traceCookie = traceCookie;
11209        }
11210
11211        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11212        abstract int doPreInstall(int status);
11213
11214        /**
11215         * Rename package into final resting place. All paths on the given
11216         * scanned package should be updated to reflect the rename.
11217         */
11218        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11219        abstract int doPostInstall(int status, int uid);
11220
11221        /** @see PackageSettingBase#codePathString */
11222        abstract String getCodePath();
11223        /** @see PackageSettingBase#resourcePathString */
11224        abstract String getResourcePath();
11225
11226        // Need installer lock especially for dex file removal.
11227        abstract void cleanUpResourcesLI();
11228        abstract boolean doPostDeleteLI(boolean delete);
11229
11230        /**
11231         * Called before the source arguments are copied. This is used mostly
11232         * for MoveParams when it needs to read the source file to put it in the
11233         * destination.
11234         */
11235        int doPreCopy() {
11236            return PackageManager.INSTALL_SUCCEEDED;
11237        }
11238
11239        /**
11240         * Called after the source arguments are copied. This is used mostly for
11241         * MoveParams when it needs to read the source file to put it in the
11242         * destination.
11243         *
11244         * @return
11245         */
11246        int doPostCopy(int uid) {
11247            return PackageManager.INSTALL_SUCCEEDED;
11248        }
11249
11250        protected boolean isFwdLocked() {
11251            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11252        }
11253
11254        protected boolean isExternalAsec() {
11255            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11256        }
11257
11258        UserHandle getUser() {
11259            return user;
11260        }
11261    }
11262
11263    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11264        if (!allCodePaths.isEmpty()) {
11265            if (instructionSets == null) {
11266                throw new IllegalStateException("instructionSet == null");
11267            }
11268            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11269            for (String codePath : allCodePaths) {
11270                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11271                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11272                    if (retCode < 0) {
11273                        Slog.w(TAG, "Couldn't remove dex file for package: "
11274                                + " at location " + codePath + ", retcode=" + retCode);
11275                        // we don't consider this to be a failure of the core package deletion
11276                    }
11277                }
11278            }
11279        }
11280    }
11281
11282    /**
11283     * Logic to handle installation of non-ASEC applications, including copying
11284     * and renaming logic.
11285     */
11286    class FileInstallArgs extends InstallArgs {
11287        private File codeFile;
11288        private File resourceFile;
11289
11290        // Example topology:
11291        // /data/app/com.example/base.apk
11292        // /data/app/com.example/split_foo.apk
11293        // /data/app/com.example/lib/arm/libfoo.so
11294        // /data/app/com.example/lib/arm64/libfoo.so
11295        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11296
11297        /** New install */
11298        FileInstallArgs(InstallParams params) {
11299            super(params.origin, params.move, params.observer, params.installFlags,
11300                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11301                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11302                    params.grantedRuntimePermissions,
11303                    params.traceMethod, params.traceCookie);
11304            if (isFwdLocked()) {
11305                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11306            }
11307        }
11308
11309        /** Existing install */
11310        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11311            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11312                    null, null, null, 0);
11313            this.codeFile = (codePath != null) ? new File(codePath) : null;
11314            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11315        }
11316
11317        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11318            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11319            try {
11320                return doCopyApk(imcs, temp);
11321            } finally {
11322                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11323            }
11324        }
11325
11326        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11327            if (origin.staged) {
11328                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11329                codeFile = origin.file;
11330                resourceFile = origin.file;
11331                return PackageManager.INSTALL_SUCCEEDED;
11332            }
11333
11334            try {
11335                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11336                codeFile = tempDir;
11337                resourceFile = tempDir;
11338            } catch (IOException e) {
11339                Slog.w(TAG, "Failed to create copy file: " + e);
11340                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11341            }
11342
11343            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11344                @Override
11345                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11346                    if (!FileUtils.isValidExtFilename(name)) {
11347                        throw new IllegalArgumentException("Invalid filename: " + name);
11348                    }
11349                    try {
11350                        final File file = new File(codeFile, name);
11351                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11352                                O_RDWR | O_CREAT, 0644);
11353                        Os.chmod(file.getAbsolutePath(), 0644);
11354                        return new ParcelFileDescriptor(fd);
11355                    } catch (ErrnoException e) {
11356                        throw new RemoteException("Failed to open: " + e.getMessage());
11357                    }
11358                }
11359            };
11360
11361            int ret = PackageManager.INSTALL_SUCCEEDED;
11362            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11363            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11364                Slog.e(TAG, "Failed to copy package");
11365                return ret;
11366            }
11367
11368            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11369            NativeLibraryHelper.Handle handle = null;
11370            try {
11371                handle = NativeLibraryHelper.Handle.create(codeFile);
11372                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11373                        abiOverride);
11374            } catch (IOException e) {
11375                Slog.e(TAG, "Copying native libraries failed", e);
11376                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11377            } finally {
11378                IoUtils.closeQuietly(handle);
11379            }
11380
11381            return ret;
11382        }
11383
11384        int doPreInstall(int status) {
11385            if (status != PackageManager.INSTALL_SUCCEEDED) {
11386                cleanUp();
11387            }
11388            return status;
11389        }
11390
11391        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11392            if (status != PackageManager.INSTALL_SUCCEEDED) {
11393                cleanUp();
11394                return false;
11395            }
11396
11397            final File targetDir = codeFile.getParentFile();
11398            final File beforeCodeFile = codeFile;
11399            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11400
11401            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11402            try {
11403                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11404            } catch (ErrnoException e) {
11405                Slog.w(TAG, "Failed to rename", e);
11406                return false;
11407            }
11408
11409            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11410                Slog.w(TAG, "Failed to restorecon");
11411                return false;
11412            }
11413
11414            // Reflect the rename internally
11415            codeFile = afterCodeFile;
11416            resourceFile = afterCodeFile;
11417
11418            // Reflect the rename in scanned details
11419            pkg.codePath = afterCodeFile.getAbsolutePath();
11420            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11421                    pkg.baseCodePath);
11422            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11423                    pkg.splitCodePaths);
11424
11425            // Reflect the rename in app info
11426            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11427            pkg.applicationInfo.setCodePath(pkg.codePath);
11428            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11429            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11430            pkg.applicationInfo.setResourcePath(pkg.codePath);
11431            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11432            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11433
11434            return true;
11435        }
11436
11437        int doPostInstall(int status, int uid) {
11438            if (status != PackageManager.INSTALL_SUCCEEDED) {
11439                cleanUp();
11440            }
11441            return status;
11442        }
11443
11444        @Override
11445        String getCodePath() {
11446            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11447        }
11448
11449        @Override
11450        String getResourcePath() {
11451            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11452        }
11453
11454        private boolean cleanUp() {
11455            if (codeFile == null || !codeFile.exists()) {
11456                return false;
11457            }
11458
11459            if (codeFile.isDirectory()) {
11460                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11461            } else {
11462                codeFile.delete();
11463            }
11464
11465            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11466                resourceFile.delete();
11467            }
11468
11469            return true;
11470        }
11471
11472        void cleanUpResourcesLI() {
11473            // Try enumerating all code paths before deleting
11474            List<String> allCodePaths = Collections.EMPTY_LIST;
11475            if (codeFile != null && codeFile.exists()) {
11476                try {
11477                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11478                    allCodePaths = pkg.getAllCodePaths();
11479                } catch (PackageParserException e) {
11480                    // Ignored; we tried our best
11481                }
11482            }
11483
11484            cleanUp();
11485            removeDexFiles(allCodePaths, instructionSets);
11486        }
11487
11488        boolean doPostDeleteLI(boolean delete) {
11489            // XXX err, shouldn't we respect the delete flag?
11490            cleanUpResourcesLI();
11491            return true;
11492        }
11493    }
11494
11495    private boolean isAsecExternal(String cid) {
11496        final String asecPath = PackageHelper.getSdFilesystem(cid);
11497        return !asecPath.startsWith(mAsecInternalPath);
11498    }
11499
11500    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11501            PackageManagerException {
11502        if (copyRet < 0) {
11503            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11504                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11505                throw new PackageManagerException(copyRet, message);
11506            }
11507        }
11508    }
11509
11510    /**
11511     * Extract the MountService "container ID" from the full code path of an
11512     * .apk.
11513     */
11514    static String cidFromCodePath(String fullCodePath) {
11515        int eidx = fullCodePath.lastIndexOf("/");
11516        String subStr1 = fullCodePath.substring(0, eidx);
11517        int sidx = subStr1.lastIndexOf("/");
11518        return subStr1.substring(sidx+1, eidx);
11519    }
11520
11521    /**
11522     * Logic to handle installation of ASEC applications, including copying and
11523     * renaming logic.
11524     */
11525    class AsecInstallArgs extends InstallArgs {
11526        static final String RES_FILE_NAME = "pkg.apk";
11527        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11528
11529        String cid;
11530        String packagePath;
11531        String resourcePath;
11532
11533        /** New install */
11534        AsecInstallArgs(InstallParams params) {
11535            super(params.origin, params.move, params.observer, params.installFlags,
11536                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11537                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11538                    params.grantedRuntimePermissions,
11539                    params.traceMethod, params.traceCookie);
11540        }
11541
11542        /** Existing install */
11543        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11544                        boolean isExternal, boolean isForwardLocked) {
11545            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11546                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11547                    instructionSets, null, null, null, 0);
11548            // Hackily pretend we're still looking at a full code path
11549            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11550                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11551            }
11552
11553            // Extract cid from fullCodePath
11554            int eidx = fullCodePath.lastIndexOf("/");
11555            String subStr1 = fullCodePath.substring(0, eidx);
11556            int sidx = subStr1.lastIndexOf("/");
11557            cid = subStr1.substring(sidx+1, eidx);
11558            setMountPath(subStr1);
11559        }
11560
11561        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11562            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11563                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11564                    instructionSets, null, null, null, 0);
11565            this.cid = cid;
11566            setMountPath(PackageHelper.getSdDir(cid));
11567        }
11568
11569        void createCopyFile() {
11570            cid = mInstallerService.allocateExternalStageCidLegacy();
11571        }
11572
11573        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11574            if (origin.staged) {
11575                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11576                cid = origin.cid;
11577                setMountPath(PackageHelper.getSdDir(cid));
11578                return PackageManager.INSTALL_SUCCEEDED;
11579            }
11580
11581            if (temp) {
11582                createCopyFile();
11583            } else {
11584                /*
11585                 * Pre-emptively destroy the container since it's destroyed if
11586                 * copying fails due to it existing anyway.
11587                 */
11588                PackageHelper.destroySdDir(cid);
11589            }
11590
11591            final String newMountPath = imcs.copyPackageToContainer(
11592                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11593                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11594
11595            if (newMountPath != null) {
11596                setMountPath(newMountPath);
11597                return PackageManager.INSTALL_SUCCEEDED;
11598            } else {
11599                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11600            }
11601        }
11602
11603        @Override
11604        String getCodePath() {
11605            return packagePath;
11606        }
11607
11608        @Override
11609        String getResourcePath() {
11610            return resourcePath;
11611        }
11612
11613        int doPreInstall(int status) {
11614            if (status != PackageManager.INSTALL_SUCCEEDED) {
11615                // Destroy container
11616                PackageHelper.destroySdDir(cid);
11617            } else {
11618                boolean mounted = PackageHelper.isContainerMounted(cid);
11619                if (!mounted) {
11620                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11621                            Process.SYSTEM_UID);
11622                    if (newMountPath != null) {
11623                        setMountPath(newMountPath);
11624                    } else {
11625                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11626                    }
11627                }
11628            }
11629            return status;
11630        }
11631
11632        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11633            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11634            String newMountPath = null;
11635            if (PackageHelper.isContainerMounted(cid)) {
11636                // Unmount the container
11637                if (!PackageHelper.unMountSdDir(cid)) {
11638                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11639                    return false;
11640                }
11641            }
11642            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11643                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11644                        " which might be stale. Will try to clean up.");
11645                // Clean up the stale container and proceed to recreate.
11646                if (!PackageHelper.destroySdDir(newCacheId)) {
11647                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11648                    return false;
11649                }
11650                // Successfully cleaned up stale container. Try to rename again.
11651                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11652                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11653                            + " inspite of cleaning it up.");
11654                    return false;
11655                }
11656            }
11657            if (!PackageHelper.isContainerMounted(newCacheId)) {
11658                Slog.w(TAG, "Mounting container " + newCacheId);
11659                newMountPath = PackageHelper.mountSdDir(newCacheId,
11660                        getEncryptKey(), Process.SYSTEM_UID);
11661            } else {
11662                newMountPath = PackageHelper.getSdDir(newCacheId);
11663            }
11664            if (newMountPath == null) {
11665                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11666                return false;
11667            }
11668            Log.i(TAG, "Succesfully renamed " + cid +
11669                    " to " + newCacheId +
11670                    " at new path: " + newMountPath);
11671            cid = newCacheId;
11672
11673            final File beforeCodeFile = new File(packagePath);
11674            setMountPath(newMountPath);
11675            final File afterCodeFile = new File(packagePath);
11676
11677            // Reflect the rename in scanned details
11678            pkg.codePath = afterCodeFile.getAbsolutePath();
11679            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11680                    pkg.baseCodePath);
11681            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11682                    pkg.splitCodePaths);
11683
11684            // Reflect the rename in app info
11685            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11686            pkg.applicationInfo.setCodePath(pkg.codePath);
11687            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11688            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11689            pkg.applicationInfo.setResourcePath(pkg.codePath);
11690            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11691            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11692
11693            return true;
11694        }
11695
11696        private void setMountPath(String mountPath) {
11697            final File mountFile = new File(mountPath);
11698
11699            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11700            if (monolithicFile.exists()) {
11701                packagePath = monolithicFile.getAbsolutePath();
11702                if (isFwdLocked()) {
11703                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11704                } else {
11705                    resourcePath = packagePath;
11706                }
11707            } else {
11708                packagePath = mountFile.getAbsolutePath();
11709                resourcePath = packagePath;
11710            }
11711        }
11712
11713        int doPostInstall(int status, int uid) {
11714            if (status != PackageManager.INSTALL_SUCCEEDED) {
11715                cleanUp();
11716            } else {
11717                final int groupOwner;
11718                final String protectedFile;
11719                if (isFwdLocked()) {
11720                    groupOwner = UserHandle.getSharedAppGid(uid);
11721                    protectedFile = RES_FILE_NAME;
11722                } else {
11723                    groupOwner = -1;
11724                    protectedFile = null;
11725                }
11726
11727                if (uid < Process.FIRST_APPLICATION_UID
11728                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11729                    Slog.e(TAG, "Failed to finalize " + cid);
11730                    PackageHelper.destroySdDir(cid);
11731                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11732                }
11733
11734                boolean mounted = PackageHelper.isContainerMounted(cid);
11735                if (!mounted) {
11736                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11737                }
11738            }
11739            return status;
11740        }
11741
11742        private void cleanUp() {
11743            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11744
11745            // Destroy secure container
11746            PackageHelper.destroySdDir(cid);
11747        }
11748
11749        private List<String> getAllCodePaths() {
11750            final File codeFile = new File(getCodePath());
11751            if (codeFile != null && codeFile.exists()) {
11752                try {
11753                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11754                    return pkg.getAllCodePaths();
11755                } catch (PackageParserException e) {
11756                    // Ignored; we tried our best
11757                }
11758            }
11759            return Collections.EMPTY_LIST;
11760        }
11761
11762        void cleanUpResourcesLI() {
11763            // Enumerate all code paths before deleting
11764            cleanUpResourcesLI(getAllCodePaths());
11765        }
11766
11767        private void cleanUpResourcesLI(List<String> allCodePaths) {
11768            cleanUp();
11769            removeDexFiles(allCodePaths, instructionSets);
11770        }
11771
11772        String getPackageName() {
11773            return getAsecPackageName(cid);
11774        }
11775
11776        boolean doPostDeleteLI(boolean delete) {
11777            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11778            final List<String> allCodePaths = getAllCodePaths();
11779            boolean mounted = PackageHelper.isContainerMounted(cid);
11780            if (mounted) {
11781                // Unmount first
11782                if (PackageHelper.unMountSdDir(cid)) {
11783                    mounted = false;
11784                }
11785            }
11786            if (!mounted && delete) {
11787                cleanUpResourcesLI(allCodePaths);
11788            }
11789            return !mounted;
11790        }
11791
11792        @Override
11793        int doPreCopy() {
11794            if (isFwdLocked()) {
11795                if (!PackageHelper.fixSdPermissions(cid,
11796                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11797                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11798                }
11799            }
11800
11801            return PackageManager.INSTALL_SUCCEEDED;
11802        }
11803
11804        @Override
11805        int doPostCopy(int uid) {
11806            if (isFwdLocked()) {
11807                if (uid < Process.FIRST_APPLICATION_UID
11808                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11809                                RES_FILE_NAME)) {
11810                    Slog.e(TAG, "Failed to finalize " + cid);
11811                    PackageHelper.destroySdDir(cid);
11812                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11813                }
11814            }
11815
11816            return PackageManager.INSTALL_SUCCEEDED;
11817        }
11818    }
11819
11820    /**
11821     * Logic to handle movement of existing installed applications.
11822     */
11823    class MoveInstallArgs extends InstallArgs {
11824        private File codeFile;
11825        private File resourceFile;
11826
11827        /** New install */
11828        MoveInstallArgs(InstallParams params) {
11829            super(params.origin, params.move, params.observer, params.installFlags,
11830                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11831                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11832                    params.grantedRuntimePermissions,
11833                    params.traceMethod, params.traceCookie);
11834        }
11835
11836        int copyApk(IMediaContainerService imcs, boolean temp) {
11837            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11838                    + move.fromUuid + " to " + move.toUuid);
11839            synchronized (mInstaller) {
11840                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11841                        move.dataAppName, move.appId, move.seinfo) != 0) {
11842                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11843                }
11844            }
11845
11846            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11847            resourceFile = codeFile;
11848            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11849
11850            return PackageManager.INSTALL_SUCCEEDED;
11851        }
11852
11853        int doPreInstall(int status) {
11854            if (status != PackageManager.INSTALL_SUCCEEDED) {
11855                cleanUp(move.toUuid);
11856            }
11857            return status;
11858        }
11859
11860        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11861            if (status != PackageManager.INSTALL_SUCCEEDED) {
11862                cleanUp(move.toUuid);
11863                return false;
11864            }
11865
11866            // Reflect the move in app info
11867            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11868            pkg.applicationInfo.setCodePath(pkg.codePath);
11869            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11870            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11871            pkg.applicationInfo.setResourcePath(pkg.codePath);
11872            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11873            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11874
11875            return true;
11876        }
11877
11878        int doPostInstall(int status, int uid) {
11879            if (status == PackageManager.INSTALL_SUCCEEDED) {
11880                cleanUp(move.fromUuid);
11881            } else {
11882                cleanUp(move.toUuid);
11883            }
11884            return status;
11885        }
11886
11887        @Override
11888        String getCodePath() {
11889            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11890        }
11891
11892        @Override
11893        String getResourcePath() {
11894            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11895        }
11896
11897        private boolean cleanUp(String volumeUuid) {
11898            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11899                    move.dataAppName);
11900            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11901            synchronized (mInstallLock) {
11902                // Clean up both app data and code
11903                removeDataDirsLI(volumeUuid, move.packageName);
11904                if (codeFile.isDirectory()) {
11905                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11906                } else {
11907                    codeFile.delete();
11908                }
11909            }
11910            return true;
11911        }
11912
11913        void cleanUpResourcesLI() {
11914            throw new UnsupportedOperationException();
11915        }
11916
11917        boolean doPostDeleteLI(boolean delete) {
11918            throw new UnsupportedOperationException();
11919        }
11920    }
11921
11922    static String getAsecPackageName(String packageCid) {
11923        int idx = packageCid.lastIndexOf("-");
11924        if (idx == -1) {
11925            return packageCid;
11926        }
11927        return packageCid.substring(0, idx);
11928    }
11929
11930    // Utility method used to create code paths based on package name and available index.
11931    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11932        String idxStr = "";
11933        int idx = 1;
11934        // Fall back to default value of idx=1 if prefix is not
11935        // part of oldCodePath
11936        if (oldCodePath != null) {
11937            String subStr = oldCodePath;
11938            // Drop the suffix right away
11939            if (suffix != null && subStr.endsWith(suffix)) {
11940                subStr = subStr.substring(0, subStr.length() - suffix.length());
11941            }
11942            // If oldCodePath already contains prefix find out the
11943            // ending index to either increment or decrement.
11944            int sidx = subStr.lastIndexOf(prefix);
11945            if (sidx != -1) {
11946                subStr = subStr.substring(sidx + prefix.length());
11947                if (subStr != null) {
11948                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11949                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11950                    }
11951                    try {
11952                        idx = Integer.parseInt(subStr);
11953                        if (idx <= 1) {
11954                            idx++;
11955                        } else {
11956                            idx--;
11957                        }
11958                    } catch(NumberFormatException e) {
11959                    }
11960                }
11961            }
11962        }
11963        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11964        return prefix + idxStr;
11965    }
11966
11967    private File getNextCodePath(File targetDir, String packageName) {
11968        int suffix = 1;
11969        File result;
11970        do {
11971            result = new File(targetDir, packageName + "-" + suffix);
11972            suffix++;
11973        } while (result.exists());
11974        return result;
11975    }
11976
11977    // Utility method that returns the relative package path with respect
11978    // to the installation directory. Like say for /data/data/com.test-1.apk
11979    // string com.test-1 is returned.
11980    static String deriveCodePathName(String codePath) {
11981        if (codePath == null) {
11982            return null;
11983        }
11984        final File codeFile = new File(codePath);
11985        final String name = codeFile.getName();
11986        if (codeFile.isDirectory()) {
11987            return name;
11988        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11989            final int lastDot = name.lastIndexOf('.');
11990            return name.substring(0, lastDot);
11991        } else {
11992            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11993            return null;
11994        }
11995    }
11996
11997    class PackageInstalledInfo {
11998        String name;
11999        int uid;
12000        // The set of users that originally had this package installed.
12001        int[] origUsers;
12002        // The set of users that now have this package installed.
12003        int[] newUsers;
12004        PackageParser.Package pkg;
12005        int returnCode;
12006        String returnMsg;
12007        PackageRemovedInfo removedInfo;
12008
12009        public void setError(int code, String msg) {
12010            returnCode = code;
12011            returnMsg = msg;
12012            Slog.w(TAG, msg);
12013        }
12014
12015        public void setError(String msg, PackageParserException e) {
12016            returnCode = e.error;
12017            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12018            Slog.w(TAG, msg, e);
12019        }
12020
12021        public void setError(String msg, PackageManagerException e) {
12022            returnCode = e.error;
12023            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12024            Slog.w(TAG, msg, e);
12025        }
12026
12027        // In some error cases we want to convey more info back to the observer
12028        String origPackage;
12029        String origPermission;
12030    }
12031
12032    /*
12033     * Install a non-existing package.
12034     */
12035    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12036            UserHandle user, String installerPackageName, String volumeUuid,
12037            PackageInstalledInfo res) {
12038        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12039
12040        // Remember this for later, in case we need to rollback this install
12041        String pkgName = pkg.packageName;
12042
12043        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12044        // TODO: b/23350563
12045        final boolean dataDirExists = Environment
12046                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12047
12048        synchronized(mPackages) {
12049            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12050                // A package with the same name is already installed, though
12051                // it has been renamed to an older name.  The package we
12052                // are trying to install should be installed as an update to
12053                // the existing one, but that has not been requested, so bail.
12054                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12055                        + " without first uninstalling package running as "
12056                        + mSettings.mRenamedPackages.get(pkgName));
12057                return;
12058            }
12059            if (mPackages.containsKey(pkgName)) {
12060                // Don't allow installation over an existing package with the same name.
12061                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12062                        + " without first uninstalling.");
12063                return;
12064            }
12065        }
12066
12067        try {
12068            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12069                    System.currentTimeMillis(), user);
12070
12071            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12072            // delete the partially installed application. the data directory will have to be
12073            // restored if it was already existing
12074            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12075                // remove package from internal structures.  Note that we want deletePackageX to
12076                // delete the package data and cache directories that it created in
12077                // scanPackageLocked, unless those directories existed before we even tried to
12078                // install.
12079                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12080                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12081                                res.removedInfo, true);
12082            }
12083
12084        } catch (PackageManagerException e) {
12085            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12086        }
12087
12088        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12089    }
12090
12091    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12092        // Can't rotate keys during boot or if sharedUser.
12093        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12094                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12095            return false;
12096        }
12097        // app is using upgradeKeySets; make sure all are valid
12098        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12099        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12100        for (int i = 0; i < upgradeKeySets.length; i++) {
12101            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12102                Slog.wtf(TAG, "Package "
12103                         + (oldPs.name != null ? oldPs.name : "<null>")
12104                         + " contains upgrade-key-set reference to unknown key-set: "
12105                         + upgradeKeySets[i]
12106                         + " reverting to signatures check.");
12107                return false;
12108            }
12109        }
12110        return true;
12111    }
12112
12113    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12114        // Upgrade keysets are being used.  Determine if new package has a superset of the
12115        // required keys.
12116        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12117        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12118        for (int i = 0; i < upgradeKeySets.length; i++) {
12119            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12120            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12121                return true;
12122            }
12123        }
12124        return false;
12125    }
12126
12127    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12128            UserHandle user, String installerPackageName, String volumeUuid,
12129            PackageInstalledInfo res) {
12130        final PackageParser.Package oldPackage;
12131        final String pkgName = pkg.packageName;
12132        final int[] allUsers;
12133        final boolean[] perUserInstalled;
12134
12135        // First find the old package info and check signatures
12136        synchronized(mPackages) {
12137            oldPackage = mPackages.get(pkgName);
12138            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12139            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12140            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12141                if(!checkUpgradeKeySetLP(ps, pkg)) {
12142                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12143                            "New package not signed by keys specified by upgrade-keysets: "
12144                            + pkgName);
12145                    return;
12146                }
12147            } else {
12148                // default to original signature matching
12149                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12150                    != PackageManager.SIGNATURE_MATCH) {
12151                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12152                            "New package has a different signature: " + pkgName);
12153                    return;
12154                }
12155            }
12156
12157            // In case of rollback, remember per-user/profile install state
12158            allUsers = sUserManager.getUserIds();
12159            perUserInstalled = new boolean[allUsers.length];
12160            for (int i = 0; i < allUsers.length; i++) {
12161                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12162            }
12163        }
12164
12165        boolean sysPkg = (isSystemApp(oldPackage));
12166        if (sysPkg) {
12167            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12168                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12169        } else {
12170            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12171                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12172        }
12173    }
12174
12175    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12176            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12177            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12178            String volumeUuid, PackageInstalledInfo res) {
12179        String pkgName = deletedPackage.packageName;
12180        boolean deletedPkg = true;
12181        boolean updatedSettings = false;
12182
12183        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12184                + deletedPackage);
12185        long origUpdateTime;
12186        if (pkg.mExtras != null) {
12187            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12188        } else {
12189            origUpdateTime = 0;
12190        }
12191
12192        // First delete the existing package while retaining the data directory
12193        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12194                res.removedInfo, true)) {
12195            // If the existing package wasn't successfully deleted
12196            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12197            deletedPkg = false;
12198        } else {
12199            // Successfully deleted the old package; proceed with replace.
12200
12201            // If deleted package lived in a container, give users a chance to
12202            // relinquish resources before killing.
12203            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12204                if (DEBUG_INSTALL) {
12205                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12206                }
12207                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12208                final ArrayList<String> pkgList = new ArrayList<String>(1);
12209                pkgList.add(deletedPackage.applicationInfo.packageName);
12210                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12211            }
12212
12213            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12214            try {
12215                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12216                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12217                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12218                        perUserInstalled, res, user);
12219                updatedSettings = true;
12220            } catch (PackageManagerException e) {
12221                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12222            }
12223        }
12224
12225        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12226            // remove package from internal structures.  Note that we want deletePackageX to
12227            // delete the package data and cache directories that it created in
12228            // scanPackageLocked, unless those directories existed before we even tried to
12229            // install.
12230            if(updatedSettings) {
12231                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12232                deletePackageLI(
12233                        pkgName, null, true, allUsers, perUserInstalled,
12234                        PackageManager.DELETE_KEEP_DATA,
12235                                res.removedInfo, true);
12236            }
12237            // Since we failed to install the new package we need to restore the old
12238            // package that we deleted.
12239            if (deletedPkg) {
12240                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12241                File restoreFile = new File(deletedPackage.codePath);
12242                // Parse old package
12243                boolean oldExternal = isExternal(deletedPackage);
12244                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12245                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12246                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12247                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12248                try {
12249                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12250                            null);
12251                } catch (PackageManagerException e) {
12252                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12253                            + e.getMessage());
12254                    return;
12255                }
12256                // Restore of old package succeeded. Update permissions.
12257                // writer
12258                synchronized (mPackages) {
12259                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12260                            UPDATE_PERMISSIONS_ALL);
12261                    // can downgrade to reader
12262                    mSettings.writeLPr();
12263                }
12264                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12265            }
12266        }
12267    }
12268
12269    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12270            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12271            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12272            String volumeUuid, PackageInstalledInfo res) {
12273        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12274                + ", old=" + deletedPackage);
12275        boolean disabledSystem = false;
12276        boolean updatedSettings = false;
12277        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12278        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12279                != 0) {
12280            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12281        }
12282        String packageName = deletedPackage.packageName;
12283        if (packageName == null) {
12284            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12285                    "Attempt to delete null packageName.");
12286            return;
12287        }
12288        PackageParser.Package oldPkg;
12289        PackageSetting oldPkgSetting;
12290        // reader
12291        synchronized (mPackages) {
12292            oldPkg = mPackages.get(packageName);
12293            oldPkgSetting = mSettings.mPackages.get(packageName);
12294            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12295                    (oldPkgSetting == null)) {
12296                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12297                        "Couldn't find package:" + packageName + " information");
12298                return;
12299            }
12300        }
12301
12302        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12303
12304        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12305        res.removedInfo.removedPackage = packageName;
12306        // Remove existing system package
12307        removePackageLI(oldPkgSetting, true);
12308        // writer
12309        synchronized (mPackages) {
12310            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12311            if (!disabledSystem && deletedPackage != null) {
12312                // We didn't need to disable the .apk as a current system package,
12313                // which means we are replacing another update that is already
12314                // installed.  We need to make sure to delete the older one's .apk.
12315                res.removedInfo.args = createInstallArgsForExisting(0,
12316                        deletedPackage.applicationInfo.getCodePath(),
12317                        deletedPackage.applicationInfo.getResourcePath(),
12318                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12319            } else {
12320                res.removedInfo.args = null;
12321            }
12322        }
12323
12324        // Successfully disabled the old package. Now proceed with re-installation
12325        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12326
12327        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12328        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12329
12330        PackageParser.Package newPackage = null;
12331        try {
12332            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12333            if (newPackage.mExtras != null) {
12334                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12335                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12336                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12337
12338                // is the update attempting to change shared user? that isn't going to work...
12339                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12340                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12341                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12342                            + " to " + newPkgSetting.sharedUser);
12343                    updatedSettings = true;
12344                }
12345            }
12346
12347            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12348                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12349                        perUserInstalled, res, user);
12350                updatedSettings = true;
12351            }
12352
12353        } catch (PackageManagerException e) {
12354            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12355        }
12356
12357        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12358            // Re installation failed. Restore old information
12359            // Remove new pkg information
12360            if (newPackage != null) {
12361                removeInstalledPackageLI(newPackage, true);
12362            }
12363            // Add back the old system package
12364            try {
12365                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12366            } catch (PackageManagerException e) {
12367                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12368            }
12369            // Restore the old system information in Settings
12370            synchronized (mPackages) {
12371                if (disabledSystem) {
12372                    mSettings.enableSystemPackageLPw(packageName);
12373                }
12374                if (updatedSettings) {
12375                    mSettings.setInstallerPackageName(packageName,
12376                            oldPkgSetting.installerPackageName);
12377                }
12378                mSettings.writeLPr();
12379            }
12380        }
12381    }
12382
12383    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12384        // Collect all used permissions in the UID
12385        ArraySet<String> usedPermissions = new ArraySet<>();
12386        final int packageCount = su.packages.size();
12387        for (int i = 0; i < packageCount; i++) {
12388            PackageSetting ps = su.packages.valueAt(i);
12389            if (ps.pkg == null) {
12390                continue;
12391            }
12392            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12393            for (int j = 0; j < requestedPermCount; j++) {
12394                String permission = ps.pkg.requestedPermissions.get(j);
12395                BasePermission bp = mSettings.mPermissions.get(permission);
12396                if (bp != null) {
12397                    usedPermissions.add(permission);
12398                }
12399            }
12400        }
12401
12402        PermissionsState permissionsState = su.getPermissionsState();
12403        // Prune install permissions
12404        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12405        final int installPermCount = installPermStates.size();
12406        for (int i = installPermCount - 1; i >= 0;  i--) {
12407            PermissionState permissionState = installPermStates.get(i);
12408            if (!usedPermissions.contains(permissionState.getName())) {
12409                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12410                if (bp != null) {
12411                    permissionsState.revokeInstallPermission(bp);
12412                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12413                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12414                }
12415            }
12416        }
12417
12418        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12419
12420        // Prune runtime permissions
12421        for (int userId : allUserIds) {
12422            List<PermissionState> runtimePermStates = permissionsState
12423                    .getRuntimePermissionStates(userId);
12424            final int runtimePermCount = runtimePermStates.size();
12425            for (int i = runtimePermCount - 1; i >= 0; i--) {
12426                PermissionState permissionState = runtimePermStates.get(i);
12427                if (!usedPermissions.contains(permissionState.getName())) {
12428                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12429                    if (bp != null) {
12430                        permissionsState.revokeRuntimePermission(bp, userId);
12431                        permissionsState.updatePermissionFlags(bp, userId,
12432                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12433                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12434                                runtimePermissionChangedUserIds, userId);
12435                    }
12436                }
12437            }
12438        }
12439
12440        return runtimePermissionChangedUserIds;
12441    }
12442
12443    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12444            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12445            UserHandle user) {
12446        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12447
12448        String pkgName = newPackage.packageName;
12449        synchronized (mPackages) {
12450            //write settings. the installStatus will be incomplete at this stage.
12451            //note that the new package setting would have already been
12452            //added to mPackages. It hasn't been persisted yet.
12453            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12454            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12455            mSettings.writeLPr();
12456            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12457        }
12458
12459        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12460        synchronized (mPackages) {
12461            updatePermissionsLPw(newPackage.packageName, newPackage,
12462                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12463                            ? UPDATE_PERMISSIONS_ALL : 0));
12464            // For system-bundled packages, we assume that installing an upgraded version
12465            // of the package implies that the user actually wants to run that new code,
12466            // so we enable the package.
12467            PackageSetting ps = mSettings.mPackages.get(pkgName);
12468            if (ps != null) {
12469                if (isSystemApp(newPackage)) {
12470                    // NB: implicit assumption that system package upgrades apply to all users
12471                    if (DEBUG_INSTALL) {
12472                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12473                    }
12474                    if (res.origUsers != null) {
12475                        for (int userHandle : res.origUsers) {
12476                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12477                                    userHandle, installerPackageName);
12478                        }
12479                    }
12480                    // Also convey the prior install/uninstall state
12481                    if (allUsers != null && perUserInstalled != null) {
12482                        for (int i = 0; i < allUsers.length; i++) {
12483                            if (DEBUG_INSTALL) {
12484                                Slog.d(TAG, "    user " + allUsers[i]
12485                                        + " => " + perUserInstalled[i]);
12486                            }
12487                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12488                        }
12489                        // these install state changes will be persisted in the
12490                        // upcoming call to mSettings.writeLPr().
12491                    }
12492                }
12493                // It's implied that when a user requests installation, they want the app to be
12494                // installed and enabled.
12495                int userId = user.getIdentifier();
12496                if (userId != UserHandle.USER_ALL) {
12497                    ps.setInstalled(true, userId);
12498                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12499                }
12500            }
12501            res.name = pkgName;
12502            res.uid = newPackage.applicationInfo.uid;
12503            res.pkg = newPackage;
12504            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12505            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12506            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12507            //to update install status
12508            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12509            mSettings.writeLPr();
12510            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12511        }
12512
12513        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12514    }
12515
12516    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12517        try {
12518            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12519            installPackageLI(args, res);
12520        } finally {
12521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12522        }
12523    }
12524
12525    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12526        final int installFlags = args.installFlags;
12527        final String installerPackageName = args.installerPackageName;
12528        final String volumeUuid = args.volumeUuid;
12529        final File tmpPackageFile = new File(args.getCodePath());
12530        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12531        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12532                || (args.volumeUuid != null));
12533        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12534        boolean replace = false;
12535        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12536        if (args.move != null) {
12537            // moving a complete application; perfom an initial scan on the new install location
12538            scanFlags |= SCAN_INITIAL;
12539        }
12540        // Result object to be returned
12541        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12542
12543        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12544
12545        // Retrieve PackageSettings and parse package
12546        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12547                | PackageParser.PARSE_ENFORCE_CODE
12548                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12549                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12550                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12551        PackageParser pp = new PackageParser();
12552        pp.setSeparateProcesses(mSeparateProcesses);
12553        pp.setDisplayMetrics(mMetrics);
12554
12555        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12556        final PackageParser.Package pkg;
12557        try {
12558            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12559        } catch (PackageParserException e) {
12560            res.setError("Failed parse during installPackageLI", e);
12561            return;
12562        } finally {
12563            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12564        }
12565
12566        // Mark that we have an install time CPU ABI override.
12567        pkg.cpuAbiOverride = args.abiOverride;
12568
12569        String pkgName = res.name = pkg.packageName;
12570        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12571            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12572                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12573                return;
12574            }
12575        }
12576
12577        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12578        try {
12579            pp.collectCertificates(pkg, parseFlags);
12580        } catch (PackageParserException e) {
12581            res.setError("Failed collect during installPackageLI", e);
12582            return;
12583        } finally {
12584            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12585        }
12586
12587        /* If the installer passed in a manifest digest, compare it now. */
12588        if (args.manifestDigest != null) {
12589            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12590            try {
12591                pp.collectManifestDigest(pkg);
12592            } catch (PackageParserException e) {
12593                res.setError("Failed collect during installPackageLI", e);
12594                return;
12595            } finally {
12596                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12597            }
12598
12599            if (DEBUG_INSTALL) {
12600                final String parsedManifest = pkg.manifestDigest == null ? "null"
12601                        : pkg.manifestDigest.toString();
12602                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12603                        + parsedManifest);
12604            }
12605
12606            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12607                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12608                return;
12609            }
12610        } else if (DEBUG_INSTALL) {
12611            final String parsedManifest = pkg.manifestDigest == null
12612                    ? "null" : pkg.manifestDigest.toString();
12613            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12614        }
12615
12616        // Get rid of all references to package scan path via parser.
12617        pp = null;
12618        String oldCodePath = null;
12619        boolean systemApp = false;
12620        synchronized (mPackages) {
12621            // Check if installing already existing package
12622            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12623                String oldName = mSettings.mRenamedPackages.get(pkgName);
12624                if (pkg.mOriginalPackages != null
12625                        && pkg.mOriginalPackages.contains(oldName)
12626                        && mPackages.containsKey(oldName)) {
12627                    // This package is derived from an original package,
12628                    // and this device has been updating from that original
12629                    // name.  We must continue using the original name, so
12630                    // rename the new package here.
12631                    pkg.setPackageName(oldName);
12632                    pkgName = pkg.packageName;
12633                    replace = true;
12634                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12635                            + oldName + " pkgName=" + pkgName);
12636                } else if (mPackages.containsKey(pkgName)) {
12637                    // This package, under its official name, already exists
12638                    // on the device; we should replace it.
12639                    replace = true;
12640                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12641                }
12642
12643                // Prevent apps opting out from runtime permissions
12644                if (replace) {
12645                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12646                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12647                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12648                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12649                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12650                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12651                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12652                                        + " doesn't support runtime permissions but the old"
12653                                        + " target SDK " + oldTargetSdk + " does.");
12654                        return;
12655                    }
12656                }
12657            }
12658
12659            PackageSetting ps = mSettings.mPackages.get(pkgName);
12660            if (ps != null) {
12661                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12662
12663                // Quick sanity check that we're signed correctly if updating;
12664                // we'll check this again later when scanning, but we want to
12665                // bail early here before tripping over redefined permissions.
12666                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12667                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12668                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12669                                + pkg.packageName + " upgrade keys do not match the "
12670                                + "previously installed version");
12671                        return;
12672                    }
12673                } else {
12674                    try {
12675                        verifySignaturesLP(ps, pkg);
12676                    } catch (PackageManagerException e) {
12677                        res.setError(e.error, e.getMessage());
12678                        return;
12679                    }
12680                }
12681
12682                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12683                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12684                    systemApp = (ps.pkg.applicationInfo.flags &
12685                            ApplicationInfo.FLAG_SYSTEM) != 0;
12686                }
12687                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12688            }
12689
12690            // Check whether the newly-scanned package wants to define an already-defined perm
12691            int N = pkg.permissions.size();
12692            for (int i = N-1; i >= 0; i--) {
12693                PackageParser.Permission perm = pkg.permissions.get(i);
12694                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12695                if (bp != null) {
12696                    // If the defining package is signed with our cert, it's okay.  This
12697                    // also includes the "updating the same package" case, of course.
12698                    // "updating same package" could also involve key-rotation.
12699                    final boolean sigsOk;
12700                    if (bp.sourcePackage.equals(pkg.packageName)
12701                            && (bp.packageSetting instanceof PackageSetting)
12702                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12703                                    scanFlags))) {
12704                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12705                    } else {
12706                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12707                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12708                    }
12709                    if (!sigsOk) {
12710                        // If the owning package is the system itself, we log but allow
12711                        // install to proceed; we fail the install on all other permission
12712                        // redefinitions.
12713                        if (!bp.sourcePackage.equals("android")) {
12714                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12715                                    + pkg.packageName + " attempting to redeclare permission "
12716                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12717                            res.origPermission = perm.info.name;
12718                            res.origPackage = bp.sourcePackage;
12719                            return;
12720                        } else {
12721                            Slog.w(TAG, "Package " + pkg.packageName
12722                                    + " attempting to redeclare system permission "
12723                                    + perm.info.name + "; ignoring new declaration");
12724                            pkg.permissions.remove(i);
12725                        }
12726                    }
12727                }
12728            }
12729
12730        }
12731
12732        if (systemApp && onExternal) {
12733            // Disable updates to system apps on sdcard
12734            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12735                    "Cannot install updates to system apps on sdcard");
12736            return;
12737        }
12738
12739        if (args.move != null) {
12740            // We did an in-place move, so dex is ready to roll
12741            scanFlags |= SCAN_NO_DEX;
12742            scanFlags |= SCAN_MOVE;
12743
12744            synchronized (mPackages) {
12745                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12746                if (ps == null) {
12747                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12748                            "Missing settings for moved package " + pkgName);
12749                }
12750
12751                // We moved the entire application as-is, so bring over the
12752                // previously derived ABI information.
12753                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12754                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12755            }
12756
12757        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12758            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12759            scanFlags |= SCAN_NO_DEX;
12760
12761            try {
12762                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12763                        true /* extract libs */);
12764            } catch (PackageManagerException pme) {
12765                Slog.e(TAG, "Error deriving application ABI", pme);
12766                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12767                return;
12768            }
12769        }
12770
12771        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12772            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12773            return;
12774        }
12775
12776        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12777
12778        if (replace) {
12779            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12780                    installerPackageName, volumeUuid, res);
12781        } else {
12782            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12783                    args.user, installerPackageName, volumeUuid, res);
12784        }
12785        synchronized (mPackages) {
12786            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12787            if (ps != null) {
12788                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12789            }
12790        }
12791    }
12792
12793    private void startIntentFilterVerifications(int userId, boolean replacing,
12794            PackageParser.Package pkg) {
12795        if (mIntentFilterVerifierComponent == null) {
12796            Slog.w(TAG, "No IntentFilter verification will not be done as "
12797                    + "there is no IntentFilterVerifier available!");
12798            return;
12799        }
12800
12801        final int verifierUid = getPackageUid(
12802                mIntentFilterVerifierComponent.getPackageName(),
12803                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12804
12805        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12806        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12807        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12808        mHandler.sendMessage(msg);
12809    }
12810
12811    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12812            PackageParser.Package pkg) {
12813        int size = pkg.activities.size();
12814        if (size == 0) {
12815            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12816                    "No activity, so no need to verify any IntentFilter!");
12817            return;
12818        }
12819
12820        final boolean hasDomainURLs = hasDomainURLs(pkg);
12821        if (!hasDomainURLs) {
12822            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12823                    "No domain URLs, so no need to verify any IntentFilter!");
12824            return;
12825        }
12826
12827        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12828                + " if any IntentFilter from the " + size
12829                + " Activities needs verification ...");
12830
12831        int count = 0;
12832        final String packageName = pkg.packageName;
12833
12834        synchronized (mPackages) {
12835            // If this is a new install and we see that we've already run verification for this
12836            // package, we have nothing to do: it means the state was restored from backup.
12837            if (!replacing) {
12838                IntentFilterVerificationInfo ivi =
12839                        mSettings.getIntentFilterVerificationLPr(packageName);
12840                if (ivi != null) {
12841                    if (DEBUG_DOMAIN_VERIFICATION) {
12842                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12843                                + ivi.getStatusString());
12844                    }
12845                    return;
12846                }
12847            }
12848
12849            // If any filters need to be verified, then all need to be.
12850            boolean needToVerify = false;
12851            for (PackageParser.Activity a : pkg.activities) {
12852                for (ActivityIntentInfo filter : a.intents) {
12853                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12854                        if (DEBUG_DOMAIN_VERIFICATION) {
12855                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12856                        }
12857                        needToVerify = true;
12858                        break;
12859                    }
12860                }
12861            }
12862
12863            if (needToVerify) {
12864                final int verificationId = mIntentFilterVerificationToken++;
12865                for (PackageParser.Activity a : pkg.activities) {
12866                    for (ActivityIntentInfo filter : a.intents) {
12867                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12868                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12869                                    "Verification needed for IntentFilter:" + filter.toString());
12870                            mIntentFilterVerifier.addOneIntentFilterVerification(
12871                                    verifierUid, userId, verificationId, filter, packageName);
12872                            count++;
12873                        }
12874                    }
12875                }
12876            }
12877        }
12878
12879        if (count > 0) {
12880            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12881                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12882                    +  " for userId:" + userId);
12883            mIntentFilterVerifier.startVerifications(userId);
12884        } else {
12885            if (DEBUG_DOMAIN_VERIFICATION) {
12886                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12887            }
12888        }
12889    }
12890
12891    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12892        final ComponentName cn  = filter.activity.getComponentName();
12893        final String packageName = cn.getPackageName();
12894
12895        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12896                packageName);
12897        if (ivi == null) {
12898            return true;
12899        }
12900        int status = ivi.getStatus();
12901        switch (status) {
12902            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12903            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12904                return true;
12905
12906            default:
12907                // Nothing to do
12908                return false;
12909        }
12910    }
12911
12912    private static boolean isMultiArch(PackageSetting ps) {
12913        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12914    }
12915
12916    private static boolean isMultiArch(ApplicationInfo info) {
12917        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12918    }
12919
12920    private static boolean isExternal(PackageParser.Package pkg) {
12921        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12922    }
12923
12924    private static boolean isExternal(PackageSetting ps) {
12925        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12926    }
12927
12928    private static boolean isExternal(ApplicationInfo info) {
12929        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12930    }
12931
12932    private static boolean isSystemApp(PackageParser.Package pkg) {
12933        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12934    }
12935
12936    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12937        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12938    }
12939
12940    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12941        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12942    }
12943
12944    private static boolean isSystemApp(PackageSetting ps) {
12945        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12946    }
12947
12948    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12949        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12950    }
12951
12952    private int packageFlagsToInstallFlags(PackageSetting ps) {
12953        int installFlags = 0;
12954        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12955            // This existing package was an external ASEC install when we have
12956            // the external flag without a UUID
12957            installFlags |= PackageManager.INSTALL_EXTERNAL;
12958        }
12959        if (ps.isForwardLocked()) {
12960            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12961        }
12962        return installFlags;
12963    }
12964
12965    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12966        if (isExternal(pkg)) {
12967            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12968                return StorageManager.UUID_PRIMARY_PHYSICAL;
12969            } else {
12970                return pkg.volumeUuid;
12971            }
12972        } else {
12973            return StorageManager.UUID_PRIVATE_INTERNAL;
12974        }
12975    }
12976
12977    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12978        if (isExternal(pkg)) {
12979            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12980                return mSettings.getExternalVersion();
12981            } else {
12982                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12983            }
12984        } else {
12985            return mSettings.getInternalVersion();
12986        }
12987    }
12988
12989    private void deleteTempPackageFiles() {
12990        final FilenameFilter filter = new FilenameFilter() {
12991            public boolean accept(File dir, String name) {
12992                return name.startsWith("vmdl") && name.endsWith(".tmp");
12993            }
12994        };
12995        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12996            file.delete();
12997        }
12998    }
12999
13000    @Override
13001    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13002            int flags) {
13003        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13004                flags);
13005    }
13006
13007    @Override
13008    public void deletePackage(final String packageName,
13009            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13010        mContext.enforceCallingOrSelfPermission(
13011                android.Manifest.permission.DELETE_PACKAGES, null);
13012        Preconditions.checkNotNull(packageName);
13013        Preconditions.checkNotNull(observer);
13014        final int uid = Binder.getCallingUid();
13015        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13016        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13017        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13018            mContext.enforceCallingPermission(
13019                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13020                    "deletePackage for user " + userId);
13021        }
13022
13023        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13024            try {
13025                observer.onPackageDeleted(packageName,
13026                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13027            } catch (RemoteException re) {
13028            }
13029            return;
13030        }
13031
13032        for (int currentUserId : users) {
13033            if (getBlockUninstallForUser(packageName, currentUserId)) {
13034                try {
13035                    observer.onPackageDeleted(packageName,
13036                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13037                } catch (RemoteException re) {
13038                }
13039                return;
13040            }
13041        }
13042
13043        if (DEBUG_REMOVE) {
13044            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13045        }
13046        // Queue up an async operation since the package deletion may take a little while.
13047        mHandler.post(new Runnable() {
13048            public void run() {
13049                mHandler.removeCallbacks(this);
13050                final int returnCode = deletePackageX(packageName, userId, flags);
13051                try {
13052                    observer.onPackageDeleted(packageName, returnCode, null);
13053                } catch (RemoteException e) {
13054                    Log.i(TAG, "Observer no longer exists.");
13055                } //end catch
13056            } //end run
13057        });
13058    }
13059
13060    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13061        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13062                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13063        try {
13064            if (dpm != null) {
13065                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwner();
13066                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13067                        : deviceOwnerComponentName.getPackageName();
13068                // Does the package contains the device owner?
13069                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13070                // this check is probably not needed, since DO should be registered as a device
13071                // admin on some user too. (Original bug for this: b/17657954)
13072                if (packageName.equals(deviceOwnerPackageName)) {
13073                    return true;
13074                }
13075                // Does it contain a device admin for any user?
13076                int[] users;
13077                if (userId == UserHandle.USER_ALL) {
13078                    users = sUserManager.getUserIds();
13079                } else {
13080                    users = new int[]{userId};
13081                }
13082                for (int i = 0; i < users.length; ++i) {
13083                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13084                        return true;
13085                    }
13086                }
13087            }
13088        } catch (RemoteException e) {
13089        }
13090        return false;
13091    }
13092
13093    /**
13094     *  This method is an internal method that could be get invoked either
13095     *  to delete an installed package or to clean up a failed installation.
13096     *  After deleting an installed package, a broadcast is sent to notify any
13097     *  listeners that the package has been installed. For cleaning up a failed
13098     *  installation, the broadcast is not necessary since the package's
13099     *  installation wouldn't have sent the initial broadcast either
13100     *  The key steps in deleting a package are
13101     *  deleting the package information in internal structures like mPackages,
13102     *  deleting the packages base directories through installd
13103     *  updating mSettings to reflect current status
13104     *  persisting settings for later use
13105     *  sending a broadcast if necessary
13106     */
13107    private int deletePackageX(String packageName, int userId, int flags) {
13108        final PackageRemovedInfo info = new PackageRemovedInfo();
13109        final boolean res;
13110
13111        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13112                ? UserHandle.ALL : new UserHandle(userId);
13113
13114        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13115            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13116            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13117        }
13118
13119        boolean removedForAllUsers = false;
13120        boolean systemUpdate = false;
13121
13122        // for the uninstall-updates case and restricted profiles, remember the per-
13123        // userhandle installed state
13124        int[] allUsers;
13125        boolean[] perUserInstalled;
13126        synchronized (mPackages) {
13127            PackageSetting ps = mSettings.mPackages.get(packageName);
13128            allUsers = sUserManager.getUserIds();
13129            perUserInstalled = new boolean[allUsers.length];
13130            for (int i = 0; i < allUsers.length; i++) {
13131                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13132            }
13133        }
13134
13135        synchronized (mInstallLock) {
13136            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13137            res = deletePackageLI(packageName, removeForUser,
13138                    true, allUsers, perUserInstalled,
13139                    flags | REMOVE_CHATTY, info, true);
13140            systemUpdate = info.isRemovedPackageSystemUpdate;
13141            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13142                removedForAllUsers = true;
13143            }
13144            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13145                    + " removedForAllUsers=" + removedForAllUsers);
13146        }
13147
13148        if (res) {
13149            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13150
13151            // If the removed package was a system update, the old system package
13152            // was re-enabled; we need to broadcast this information
13153            if (systemUpdate) {
13154                Bundle extras = new Bundle(1);
13155                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13156                        ? info.removedAppId : info.uid);
13157                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13158
13159                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13160                        extras, 0, null, null, null);
13161                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13162                        extras, 0, null, null, null);
13163                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13164                        null, 0, packageName, null, null);
13165            }
13166        }
13167        // Force a gc here.
13168        Runtime.getRuntime().gc();
13169        // Delete the resources here after sending the broadcast to let
13170        // other processes clean up before deleting resources.
13171        if (info.args != null) {
13172            synchronized (mInstallLock) {
13173                info.args.doPostDeleteLI(true);
13174            }
13175        }
13176
13177        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13178    }
13179
13180    class PackageRemovedInfo {
13181        String removedPackage;
13182        int uid = -1;
13183        int removedAppId = -1;
13184        int[] removedUsers = null;
13185        boolean isRemovedPackageSystemUpdate = false;
13186        // Clean up resources deleted packages.
13187        InstallArgs args = null;
13188
13189        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13190            Bundle extras = new Bundle(1);
13191            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13192            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13193            if (replacing) {
13194                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13195            }
13196            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13197            if (removedPackage != null) {
13198                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13199                        extras, 0, null, null, removedUsers);
13200                if (fullRemove && !replacing) {
13201                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13202                            extras, 0, null, null, removedUsers);
13203                }
13204            }
13205            if (removedAppId >= 0) {
13206                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13207                        removedUsers);
13208            }
13209        }
13210    }
13211
13212    /*
13213     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13214     * flag is not set, the data directory is removed as well.
13215     * make sure this flag is set for partially installed apps. If not its meaningless to
13216     * delete a partially installed application.
13217     */
13218    private void removePackageDataLI(PackageSetting ps,
13219            int[] allUserHandles, boolean[] perUserInstalled,
13220            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13221        String packageName = ps.name;
13222        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13223        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13224        // Retrieve object to delete permissions for shared user later on
13225        final PackageSetting deletedPs;
13226        // reader
13227        synchronized (mPackages) {
13228            deletedPs = mSettings.mPackages.get(packageName);
13229            if (outInfo != null) {
13230                outInfo.removedPackage = packageName;
13231                outInfo.removedUsers = deletedPs != null
13232                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13233                        : null;
13234            }
13235        }
13236        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13237            removeDataDirsLI(ps.volumeUuid, packageName);
13238            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13239        }
13240        // writer
13241        synchronized (mPackages) {
13242            if (deletedPs != null) {
13243                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13244                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13245                    clearDefaultBrowserIfNeeded(packageName);
13246                    if (outInfo != null) {
13247                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13248                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13249                    }
13250                    updatePermissionsLPw(deletedPs.name, null, 0);
13251                    if (deletedPs.sharedUser != null) {
13252                        // Remove permissions associated with package. Since runtime
13253                        // permissions are per user we have to kill the removed package
13254                        // or packages running under the shared user of the removed
13255                        // package if revoking the permissions requested only by the removed
13256                        // package is successful and this causes a change in gids.
13257                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13258                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13259                                    userId);
13260                            if (userIdToKill == UserHandle.USER_ALL
13261                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13262                                // If gids changed for this user, kill all affected packages.
13263                                mHandler.post(new Runnable() {
13264                                    @Override
13265                                    public void run() {
13266                                        // This has to happen with no lock held.
13267                                        killApplication(deletedPs.name, deletedPs.appId,
13268                                                KILL_APP_REASON_GIDS_CHANGED);
13269                                    }
13270                                });
13271                                break;
13272                            }
13273                        }
13274                    }
13275                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13276                }
13277                // make sure to preserve per-user disabled state if this removal was just
13278                // a downgrade of a system app to the factory package
13279                if (allUserHandles != null && perUserInstalled != null) {
13280                    if (DEBUG_REMOVE) {
13281                        Slog.d(TAG, "Propagating install state across downgrade");
13282                    }
13283                    for (int i = 0; i < allUserHandles.length; i++) {
13284                        if (DEBUG_REMOVE) {
13285                            Slog.d(TAG, "    user " + allUserHandles[i]
13286                                    + " => " + perUserInstalled[i]);
13287                        }
13288                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13289                    }
13290                }
13291            }
13292            // can downgrade to reader
13293            if (writeSettings) {
13294                // Save settings now
13295                mSettings.writeLPr();
13296            }
13297        }
13298        if (outInfo != null) {
13299            // A user ID was deleted here. Go through all users and remove it
13300            // from KeyStore.
13301            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13302        }
13303    }
13304
13305    static boolean locationIsPrivileged(File path) {
13306        try {
13307            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13308                    .getCanonicalPath();
13309            return path.getCanonicalPath().startsWith(privilegedAppDir);
13310        } catch (IOException e) {
13311            Slog.e(TAG, "Unable to access code path " + path);
13312        }
13313        return false;
13314    }
13315
13316    /*
13317     * Tries to delete system package.
13318     */
13319    private boolean deleteSystemPackageLI(PackageSetting newPs,
13320            int[] allUserHandles, boolean[] perUserInstalled,
13321            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13322        final boolean applyUserRestrictions
13323                = (allUserHandles != null) && (perUserInstalled != null);
13324        PackageSetting disabledPs = null;
13325        // Confirm if the system package has been updated
13326        // An updated system app can be deleted. This will also have to restore
13327        // the system pkg from system partition
13328        // reader
13329        synchronized (mPackages) {
13330            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13331        }
13332        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13333                + " disabledPs=" + disabledPs);
13334        if (disabledPs == null) {
13335            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13336            return false;
13337        } else if (DEBUG_REMOVE) {
13338            Slog.d(TAG, "Deleting system pkg from data partition");
13339        }
13340        if (DEBUG_REMOVE) {
13341            if (applyUserRestrictions) {
13342                Slog.d(TAG, "Remembering install states:");
13343                for (int i = 0; i < allUserHandles.length; i++) {
13344                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13345                }
13346            }
13347        }
13348        // Delete the updated package
13349        outInfo.isRemovedPackageSystemUpdate = true;
13350        if (disabledPs.versionCode < newPs.versionCode) {
13351            // Delete data for downgrades
13352            flags &= ~PackageManager.DELETE_KEEP_DATA;
13353        } else {
13354            // Preserve data by setting flag
13355            flags |= PackageManager.DELETE_KEEP_DATA;
13356        }
13357        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13358                allUserHandles, perUserInstalled, outInfo, writeSettings);
13359        if (!ret) {
13360            return false;
13361        }
13362        // writer
13363        synchronized (mPackages) {
13364            // Reinstate the old system package
13365            mSettings.enableSystemPackageLPw(newPs.name);
13366            // Remove any native libraries from the upgraded package.
13367            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13368        }
13369        // Install the system package
13370        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13371        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13372        if (locationIsPrivileged(disabledPs.codePath)) {
13373            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13374        }
13375
13376        final PackageParser.Package newPkg;
13377        try {
13378            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13379        } catch (PackageManagerException e) {
13380            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13381            return false;
13382        }
13383
13384        // writer
13385        synchronized (mPackages) {
13386            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13387
13388            // Propagate the permissions state as we do not want to drop on the floor
13389            // runtime permissions. The update permissions method below will take
13390            // care of removing obsolete permissions and grant install permissions.
13391            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13392            updatePermissionsLPw(newPkg.packageName, newPkg,
13393                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13394
13395            if (applyUserRestrictions) {
13396                if (DEBUG_REMOVE) {
13397                    Slog.d(TAG, "Propagating install state across reinstall");
13398                }
13399                for (int i = 0; i < allUserHandles.length; i++) {
13400                    if (DEBUG_REMOVE) {
13401                        Slog.d(TAG, "    user " + allUserHandles[i]
13402                                + " => " + perUserInstalled[i]);
13403                    }
13404                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13405
13406                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13407                }
13408                // Regardless of writeSettings we need to ensure that this restriction
13409                // state propagation is persisted
13410                mSettings.writeAllUsersPackageRestrictionsLPr();
13411            }
13412            // can downgrade to reader here
13413            if (writeSettings) {
13414                mSettings.writeLPr();
13415            }
13416        }
13417        return true;
13418    }
13419
13420    private boolean deleteInstalledPackageLI(PackageSetting ps,
13421            boolean deleteCodeAndResources, int flags,
13422            int[] allUserHandles, boolean[] perUserInstalled,
13423            PackageRemovedInfo outInfo, boolean writeSettings) {
13424        if (outInfo != null) {
13425            outInfo.uid = ps.appId;
13426        }
13427
13428        // Delete package data from internal structures and also remove data if flag is set
13429        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13430
13431        // Delete application code and resources
13432        if (deleteCodeAndResources && (outInfo != null)) {
13433            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13434                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13435            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13436        }
13437        return true;
13438    }
13439
13440    @Override
13441    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13442            int userId) {
13443        mContext.enforceCallingOrSelfPermission(
13444                android.Manifest.permission.DELETE_PACKAGES, null);
13445        synchronized (mPackages) {
13446            PackageSetting ps = mSettings.mPackages.get(packageName);
13447            if (ps == null) {
13448                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13449                return false;
13450            }
13451            if (!ps.getInstalled(userId)) {
13452                // Can't block uninstall for an app that is not installed or enabled.
13453                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13454                return false;
13455            }
13456            ps.setBlockUninstall(blockUninstall, userId);
13457            mSettings.writePackageRestrictionsLPr(userId);
13458        }
13459        return true;
13460    }
13461
13462    @Override
13463    public boolean getBlockUninstallForUser(String packageName, int userId) {
13464        synchronized (mPackages) {
13465            PackageSetting ps = mSettings.mPackages.get(packageName);
13466            if (ps == null) {
13467                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13468                return false;
13469            }
13470            return ps.getBlockUninstall(userId);
13471        }
13472    }
13473
13474    /*
13475     * This method handles package deletion in general
13476     */
13477    private boolean deletePackageLI(String packageName, UserHandle user,
13478            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13479            int flags, PackageRemovedInfo outInfo,
13480            boolean writeSettings) {
13481        if (packageName == null) {
13482            Slog.w(TAG, "Attempt to delete null packageName.");
13483            return false;
13484        }
13485        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13486        PackageSetting ps;
13487        boolean dataOnly = false;
13488        int removeUser = -1;
13489        int appId = -1;
13490        synchronized (mPackages) {
13491            ps = mSettings.mPackages.get(packageName);
13492            if (ps == null) {
13493                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13494                return false;
13495            }
13496            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13497                    && user.getIdentifier() != UserHandle.USER_ALL) {
13498                // The caller is asking that the package only be deleted for a single
13499                // user.  To do this, we just mark its uninstalled state and delete
13500                // its data.  If this is a system app, we only allow this to happen if
13501                // they have set the special DELETE_SYSTEM_APP which requests different
13502                // semantics than normal for uninstalling system apps.
13503                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13504                final int userId = user.getIdentifier();
13505                ps.setUserState(userId,
13506                        COMPONENT_ENABLED_STATE_DEFAULT,
13507                        false, //installed
13508                        true,  //stopped
13509                        true,  //notLaunched
13510                        false, //hidden
13511                        null, null, null,
13512                        false, // blockUninstall
13513                        ps.readUserState(userId).domainVerificationStatus, 0);
13514                if (!isSystemApp(ps)) {
13515                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13516                        // Other user still have this package installed, so all
13517                        // we need to do is clear this user's data and save that
13518                        // it is uninstalled.
13519                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13520                        removeUser = user.getIdentifier();
13521                        appId = ps.appId;
13522                        scheduleWritePackageRestrictionsLocked(removeUser);
13523                    } else {
13524                        // We need to set it back to 'installed' so the uninstall
13525                        // broadcasts will be sent correctly.
13526                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13527                        ps.setInstalled(true, user.getIdentifier());
13528                    }
13529                } else {
13530                    // This is a system app, so we assume that the
13531                    // other users still have this package installed, so all
13532                    // we need to do is clear this user's data and save that
13533                    // it is uninstalled.
13534                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13535                    removeUser = user.getIdentifier();
13536                    appId = ps.appId;
13537                    scheduleWritePackageRestrictionsLocked(removeUser);
13538                }
13539            }
13540        }
13541
13542        if (removeUser >= 0) {
13543            // From above, we determined that we are deleting this only
13544            // for a single user.  Continue the work here.
13545            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13546            if (outInfo != null) {
13547                outInfo.removedPackage = packageName;
13548                outInfo.removedAppId = appId;
13549                outInfo.removedUsers = new int[] {removeUser};
13550            }
13551            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13552            removeKeystoreDataIfNeeded(removeUser, appId);
13553            schedulePackageCleaning(packageName, removeUser, false);
13554            synchronized (mPackages) {
13555                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13556                    scheduleWritePackageRestrictionsLocked(removeUser);
13557                }
13558                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13559            }
13560            return true;
13561        }
13562
13563        if (dataOnly) {
13564            // Delete application data first
13565            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13566            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13567            return true;
13568        }
13569
13570        boolean ret = false;
13571        if (isSystemApp(ps)) {
13572            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13573            // When an updated system application is deleted we delete the existing resources as well and
13574            // fall back to existing code in system partition
13575            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13576                    flags, outInfo, writeSettings);
13577        } else {
13578            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13579            // Kill application pre-emptively especially for apps on sd.
13580            killApplication(packageName, ps.appId, "uninstall pkg");
13581            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13582                    allUserHandles, perUserInstalled,
13583                    outInfo, writeSettings);
13584        }
13585
13586        return ret;
13587    }
13588
13589    private final class ClearStorageConnection implements ServiceConnection {
13590        IMediaContainerService mContainerService;
13591
13592        @Override
13593        public void onServiceConnected(ComponentName name, IBinder service) {
13594            synchronized (this) {
13595                mContainerService = IMediaContainerService.Stub.asInterface(service);
13596                notifyAll();
13597            }
13598        }
13599
13600        @Override
13601        public void onServiceDisconnected(ComponentName name) {
13602        }
13603    }
13604
13605    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13606        final boolean mounted;
13607        if (Environment.isExternalStorageEmulated()) {
13608            mounted = true;
13609        } else {
13610            final String status = Environment.getExternalStorageState();
13611
13612            mounted = status.equals(Environment.MEDIA_MOUNTED)
13613                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13614        }
13615
13616        if (!mounted) {
13617            return;
13618        }
13619
13620        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13621        int[] users;
13622        if (userId == UserHandle.USER_ALL) {
13623            users = sUserManager.getUserIds();
13624        } else {
13625            users = new int[] { userId };
13626        }
13627        final ClearStorageConnection conn = new ClearStorageConnection();
13628        if (mContext.bindServiceAsUser(
13629                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13630            try {
13631                for (int curUser : users) {
13632                    long timeout = SystemClock.uptimeMillis() + 5000;
13633                    synchronized (conn) {
13634                        long now = SystemClock.uptimeMillis();
13635                        while (conn.mContainerService == null && now < timeout) {
13636                            try {
13637                                conn.wait(timeout - now);
13638                            } catch (InterruptedException e) {
13639                            }
13640                        }
13641                    }
13642                    if (conn.mContainerService == null) {
13643                        return;
13644                    }
13645
13646                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13647                    clearDirectory(conn.mContainerService,
13648                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13649                    if (allData) {
13650                        clearDirectory(conn.mContainerService,
13651                                userEnv.buildExternalStorageAppDataDirs(packageName));
13652                        clearDirectory(conn.mContainerService,
13653                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13654                    }
13655                }
13656            } finally {
13657                mContext.unbindService(conn);
13658            }
13659        }
13660    }
13661
13662    @Override
13663    public void clearApplicationUserData(final String packageName,
13664            final IPackageDataObserver observer, final int userId) {
13665        mContext.enforceCallingOrSelfPermission(
13666                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13667        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13668        // Queue up an async operation since the package deletion may take a little while.
13669        mHandler.post(new Runnable() {
13670            public void run() {
13671                mHandler.removeCallbacks(this);
13672                final boolean succeeded;
13673                synchronized (mInstallLock) {
13674                    succeeded = clearApplicationUserDataLI(packageName, userId);
13675                }
13676                clearExternalStorageDataSync(packageName, userId, true);
13677                if (succeeded) {
13678                    // invoke DeviceStorageMonitor's update method to clear any notifications
13679                    DeviceStorageMonitorInternal
13680                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13681                    if (dsm != null) {
13682                        dsm.checkMemory();
13683                    }
13684                }
13685                if(observer != null) {
13686                    try {
13687                        observer.onRemoveCompleted(packageName, succeeded);
13688                    } catch (RemoteException e) {
13689                        Log.i(TAG, "Observer no longer exists.");
13690                    }
13691                } //end if observer
13692            } //end run
13693        });
13694    }
13695
13696    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13697        if (packageName == null) {
13698            Slog.w(TAG, "Attempt to delete null packageName.");
13699            return false;
13700        }
13701
13702        // Try finding details about the requested package
13703        PackageParser.Package pkg;
13704        synchronized (mPackages) {
13705            pkg = mPackages.get(packageName);
13706            if (pkg == null) {
13707                final PackageSetting ps = mSettings.mPackages.get(packageName);
13708                if (ps != null) {
13709                    pkg = ps.pkg;
13710                }
13711            }
13712
13713            if (pkg == null) {
13714                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13715                return false;
13716            }
13717
13718            PackageSetting ps = (PackageSetting) pkg.mExtras;
13719            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13720        }
13721
13722        // Always delete data directories for package, even if we found no other
13723        // record of app. This helps users recover from UID mismatches without
13724        // resorting to a full data wipe.
13725        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13726        if (retCode < 0) {
13727            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13728            return false;
13729        }
13730
13731        final int appId = pkg.applicationInfo.uid;
13732        removeKeystoreDataIfNeeded(userId, appId);
13733
13734        // Create a native library symlink only if we have native libraries
13735        // and if the native libraries are 32 bit libraries. We do not provide
13736        // this symlink for 64 bit libraries.
13737        if (pkg.applicationInfo.primaryCpuAbi != null &&
13738                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13739            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13740            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13741                    nativeLibPath, userId) < 0) {
13742                Slog.w(TAG, "Failed linking native library dir");
13743                return false;
13744            }
13745        }
13746
13747        return true;
13748    }
13749
13750    /**
13751     * Reverts user permission state changes (permissions and flags) in
13752     * all packages for a given user.
13753     *
13754     * @param userId The device user for which to do a reset.
13755     */
13756    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13757        final int packageCount = mPackages.size();
13758        for (int i = 0; i < packageCount; i++) {
13759            PackageParser.Package pkg = mPackages.valueAt(i);
13760            PackageSetting ps = (PackageSetting) pkg.mExtras;
13761            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13762        }
13763    }
13764
13765    /**
13766     * Reverts user permission state changes (permissions and flags).
13767     *
13768     * @param ps The package for which to reset.
13769     * @param userId The device user for which to do a reset.
13770     */
13771    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13772            final PackageSetting ps, final int userId) {
13773        if (ps.pkg == null) {
13774            return;
13775        }
13776
13777        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13778                | FLAG_PERMISSION_USER_FIXED
13779                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13780
13781        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13782                | FLAG_PERMISSION_POLICY_FIXED;
13783
13784        boolean writeInstallPermissions = false;
13785        boolean writeRuntimePermissions = false;
13786
13787        final int permissionCount = ps.pkg.requestedPermissions.size();
13788        for (int i = 0; i < permissionCount; i++) {
13789            String permission = ps.pkg.requestedPermissions.get(i);
13790
13791            BasePermission bp = mSettings.mPermissions.get(permission);
13792            if (bp == null) {
13793                continue;
13794            }
13795
13796            // If shared user we just reset the state to which only this app contributed.
13797            if (ps.sharedUser != null) {
13798                boolean used = false;
13799                final int packageCount = ps.sharedUser.packages.size();
13800                for (int j = 0; j < packageCount; j++) {
13801                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13802                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13803                            && pkg.pkg.requestedPermissions.contains(permission)) {
13804                        used = true;
13805                        break;
13806                    }
13807                }
13808                if (used) {
13809                    continue;
13810                }
13811            }
13812
13813            PermissionsState permissionsState = ps.getPermissionsState();
13814
13815            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13816
13817            // Always clear the user settable flags.
13818            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13819                    bp.name) != null;
13820            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13821                if (hasInstallState) {
13822                    writeInstallPermissions = true;
13823                } else {
13824                    writeRuntimePermissions = true;
13825                }
13826            }
13827
13828            // Below is only runtime permission handling.
13829            if (!bp.isRuntime()) {
13830                continue;
13831            }
13832
13833            // Never clobber system or policy.
13834            if ((oldFlags & policyOrSystemFlags) != 0) {
13835                continue;
13836            }
13837
13838            // If this permission was granted by default, make sure it is.
13839            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13840                if (permissionsState.grantRuntimePermission(bp, userId)
13841                        != PERMISSION_OPERATION_FAILURE) {
13842                    writeRuntimePermissions = true;
13843                }
13844            } else {
13845                // Otherwise, reset the permission.
13846                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13847                switch (revokeResult) {
13848                    case PERMISSION_OPERATION_SUCCESS: {
13849                        writeRuntimePermissions = true;
13850                    } break;
13851
13852                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13853                        writeRuntimePermissions = true;
13854                        final int appId = ps.appId;
13855                        mHandler.post(new Runnable() {
13856                            @Override
13857                            public void run() {
13858                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13859                            }
13860                        });
13861                    } break;
13862                }
13863            }
13864        }
13865
13866        // Synchronously write as we are taking permissions away.
13867        if (writeRuntimePermissions) {
13868            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13869        }
13870
13871        // Synchronously write as we are taking permissions away.
13872        if (writeInstallPermissions) {
13873            mSettings.writeLPr();
13874        }
13875    }
13876
13877    /**
13878     * Remove entries from the keystore daemon. Will only remove it if the
13879     * {@code appId} is valid.
13880     */
13881    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13882        if (appId < 0) {
13883            return;
13884        }
13885
13886        final KeyStore keyStore = KeyStore.getInstance();
13887        if (keyStore != null) {
13888            if (userId == UserHandle.USER_ALL) {
13889                for (final int individual : sUserManager.getUserIds()) {
13890                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13891                }
13892            } else {
13893                keyStore.clearUid(UserHandle.getUid(userId, appId));
13894            }
13895        } else {
13896            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13897        }
13898    }
13899
13900    @Override
13901    public void deleteApplicationCacheFiles(final String packageName,
13902            final IPackageDataObserver observer) {
13903        mContext.enforceCallingOrSelfPermission(
13904                android.Manifest.permission.DELETE_CACHE_FILES, null);
13905        // Queue up an async operation since the package deletion may take a little while.
13906        final int userId = UserHandle.getCallingUserId();
13907        mHandler.post(new Runnable() {
13908            public void run() {
13909                mHandler.removeCallbacks(this);
13910                final boolean succeded;
13911                synchronized (mInstallLock) {
13912                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13913                }
13914                clearExternalStorageDataSync(packageName, userId, false);
13915                if (observer != null) {
13916                    try {
13917                        observer.onRemoveCompleted(packageName, succeded);
13918                    } catch (RemoteException e) {
13919                        Log.i(TAG, "Observer no longer exists.");
13920                    }
13921                } //end if observer
13922            } //end run
13923        });
13924    }
13925
13926    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13927        if (packageName == null) {
13928            Slog.w(TAG, "Attempt to delete null packageName.");
13929            return false;
13930        }
13931        PackageParser.Package p;
13932        synchronized (mPackages) {
13933            p = mPackages.get(packageName);
13934        }
13935        if (p == null) {
13936            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13937            return false;
13938        }
13939        final ApplicationInfo applicationInfo = p.applicationInfo;
13940        if (applicationInfo == null) {
13941            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13942            return false;
13943        }
13944        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13945        if (retCode < 0) {
13946            Slog.w(TAG, "Couldn't remove cache files for package: "
13947                       + packageName + " u" + userId);
13948            return false;
13949        }
13950        return true;
13951    }
13952
13953    @Override
13954    public void getPackageSizeInfo(final String packageName, int userHandle,
13955            final IPackageStatsObserver observer) {
13956        mContext.enforceCallingOrSelfPermission(
13957                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13958        if (packageName == null) {
13959            throw new IllegalArgumentException("Attempt to get size of null packageName");
13960        }
13961
13962        PackageStats stats = new PackageStats(packageName, userHandle);
13963
13964        /*
13965         * Queue up an async operation since the package measurement may take a
13966         * little while.
13967         */
13968        Message msg = mHandler.obtainMessage(INIT_COPY);
13969        msg.obj = new MeasureParams(stats, observer);
13970        mHandler.sendMessage(msg);
13971    }
13972
13973    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13974            PackageStats pStats) {
13975        if (packageName == null) {
13976            Slog.w(TAG, "Attempt to get size of null packageName.");
13977            return false;
13978        }
13979        PackageParser.Package p;
13980        boolean dataOnly = false;
13981        String libDirRoot = null;
13982        String asecPath = null;
13983        PackageSetting ps = null;
13984        synchronized (mPackages) {
13985            p = mPackages.get(packageName);
13986            ps = mSettings.mPackages.get(packageName);
13987            if(p == null) {
13988                dataOnly = true;
13989                if((ps == null) || (ps.pkg == null)) {
13990                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13991                    return false;
13992                }
13993                p = ps.pkg;
13994            }
13995            if (ps != null) {
13996                libDirRoot = ps.legacyNativeLibraryPathString;
13997            }
13998            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13999                final long token = Binder.clearCallingIdentity();
14000                try {
14001                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14002                    if (secureContainerId != null) {
14003                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14004                    }
14005                } finally {
14006                    Binder.restoreCallingIdentity(token);
14007                }
14008            }
14009        }
14010        String publicSrcDir = null;
14011        if(!dataOnly) {
14012            final ApplicationInfo applicationInfo = p.applicationInfo;
14013            if (applicationInfo == null) {
14014                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14015                return false;
14016            }
14017            if (p.isForwardLocked()) {
14018                publicSrcDir = applicationInfo.getBaseResourcePath();
14019            }
14020        }
14021        // TODO: extend to measure size of split APKs
14022        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14023        // not just the first level.
14024        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14025        // just the primary.
14026        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14027
14028        String apkPath;
14029        File packageDir = new File(p.codePath);
14030
14031        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14032            apkPath = packageDir.getAbsolutePath();
14033            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14034            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14035                libDirRoot = null;
14036            }
14037        } else {
14038            apkPath = p.baseCodePath;
14039        }
14040
14041        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14042                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14043        if (res < 0) {
14044            return false;
14045        }
14046
14047        // Fix-up for forward-locked applications in ASEC containers.
14048        if (!isExternal(p)) {
14049            pStats.codeSize += pStats.externalCodeSize;
14050            pStats.externalCodeSize = 0L;
14051        }
14052
14053        return true;
14054    }
14055
14056
14057    @Override
14058    public void addPackageToPreferred(String packageName) {
14059        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14060    }
14061
14062    @Override
14063    public void removePackageFromPreferred(String packageName) {
14064        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14065    }
14066
14067    @Override
14068    public List<PackageInfo> getPreferredPackages(int flags) {
14069        return new ArrayList<PackageInfo>();
14070    }
14071
14072    private int getUidTargetSdkVersionLockedLPr(int uid) {
14073        Object obj = mSettings.getUserIdLPr(uid);
14074        if (obj instanceof SharedUserSetting) {
14075            final SharedUserSetting sus = (SharedUserSetting) obj;
14076            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14077            final Iterator<PackageSetting> it = sus.packages.iterator();
14078            while (it.hasNext()) {
14079                final PackageSetting ps = it.next();
14080                if (ps.pkg != null) {
14081                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14082                    if (v < vers) vers = v;
14083                }
14084            }
14085            return vers;
14086        } else if (obj instanceof PackageSetting) {
14087            final PackageSetting ps = (PackageSetting) obj;
14088            if (ps.pkg != null) {
14089                return ps.pkg.applicationInfo.targetSdkVersion;
14090            }
14091        }
14092        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14093    }
14094
14095    @Override
14096    public void addPreferredActivity(IntentFilter filter, int match,
14097            ComponentName[] set, ComponentName activity, int userId) {
14098        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14099                "Adding preferred");
14100    }
14101
14102    private void addPreferredActivityInternal(IntentFilter filter, int match,
14103            ComponentName[] set, ComponentName activity, boolean always, int userId,
14104            String opname) {
14105        // writer
14106        int callingUid = Binder.getCallingUid();
14107        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14108        if (filter.countActions() == 0) {
14109            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14110            return;
14111        }
14112        synchronized (mPackages) {
14113            if (mContext.checkCallingOrSelfPermission(
14114                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14115                    != PackageManager.PERMISSION_GRANTED) {
14116                if (getUidTargetSdkVersionLockedLPr(callingUid)
14117                        < Build.VERSION_CODES.FROYO) {
14118                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14119                            + callingUid);
14120                    return;
14121                }
14122                mContext.enforceCallingOrSelfPermission(
14123                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14124            }
14125
14126            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14127            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14128                    + userId + ":");
14129            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14130            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14131            scheduleWritePackageRestrictionsLocked(userId);
14132        }
14133    }
14134
14135    @Override
14136    public void replacePreferredActivity(IntentFilter filter, int match,
14137            ComponentName[] set, ComponentName activity, int userId) {
14138        if (filter.countActions() != 1) {
14139            throw new IllegalArgumentException(
14140                    "replacePreferredActivity expects filter to have only 1 action.");
14141        }
14142        if (filter.countDataAuthorities() != 0
14143                || filter.countDataPaths() != 0
14144                || filter.countDataSchemes() > 1
14145                || filter.countDataTypes() != 0) {
14146            throw new IllegalArgumentException(
14147                    "replacePreferredActivity expects filter to have no data authorities, " +
14148                    "paths, or types; and at most one scheme.");
14149        }
14150
14151        final int callingUid = Binder.getCallingUid();
14152        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14153        synchronized (mPackages) {
14154            if (mContext.checkCallingOrSelfPermission(
14155                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14156                    != PackageManager.PERMISSION_GRANTED) {
14157                if (getUidTargetSdkVersionLockedLPr(callingUid)
14158                        < Build.VERSION_CODES.FROYO) {
14159                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14160                            + Binder.getCallingUid());
14161                    return;
14162                }
14163                mContext.enforceCallingOrSelfPermission(
14164                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14165            }
14166
14167            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14168            if (pir != null) {
14169                // Get all of the existing entries that exactly match this filter.
14170                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14171                if (existing != null && existing.size() == 1) {
14172                    PreferredActivity cur = existing.get(0);
14173                    if (DEBUG_PREFERRED) {
14174                        Slog.i(TAG, "Checking replace of preferred:");
14175                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14176                        if (!cur.mPref.mAlways) {
14177                            Slog.i(TAG, "  -- CUR; not mAlways!");
14178                        } else {
14179                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14180                            Slog.i(TAG, "  -- CUR: mSet="
14181                                    + Arrays.toString(cur.mPref.mSetComponents));
14182                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14183                            Slog.i(TAG, "  -- NEW: mMatch="
14184                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14185                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14186                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14187                        }
14188                    }
14189                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14190                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14191                            && cur.mPref.sameSet(set)) {
14192                        // Setting the preferred activity to what it happens to be already
14193                        if (DEBUG_PREFERRED) {
14194                            Slog.i(TAG, "Replacing with same preferred activity "
14195                                    + cur.mPref.mShortComponent + " for user "
14196                                    + userId + ":");
14197                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14198                        }
14199                        return;
14200                    }
14201                }
14202
14203                if (existing != null) {
14204                    if (DEBUG_PREFERRED) {
14205                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14206                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14207                    }
14208                    for (int i = 0; i < existing.size(); i++) {
14209                        PreferredActivity pa = existing.get(i);
14210                        if (DEBUG_PREFERRED) {
14211                            Slog.i(TAG, "Removing existing preferred activity "
14212                                    + pa.mPref.mComponent + ":");
14213                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14214                        }
14215                        pir.removeFilter(pa);
14216                    }
14217                }
14218            }
14219            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14220                    "Replacing preferred");
14221        }
14222    }
14223
14224    @Override
14225    public void clearPackagePreferredActivities(String packageName) {
14226        final int uid = Binder.getCallingUid();
14227        // writer
14228        synchronized (mPackages) {
14229            PackageParser.Package pkg = mPackages.get(packageName);
14230            if (pkg == null || pkg.applicationInfo.uid != uid) {
14231                if (mContext.checkCallingOrSelfPermission(
14232                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14233                        != PackageManager.PERMISSION_GRANTED) {
14234                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14235                            < Build.VERSION_CODES.FROYO) {
14236                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14237                                + Binder.getCallingUid());
14238                        return;
14239                    }
14240                    mContext.enforceCallingOrSelfPermission(
14241                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14242                }
14243            }
14244
14245            int user = UserHandle.getCallingUserId();
14246            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14247                scheduleWritePackageRestrictionsLocked(user);
14248            }
14249        }
14250    }
14251
14252    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14253    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14254        ArrayList<PreferredActivity> removed = null;
14255        boolean changed = false;
14256        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14257            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14258            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14259            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14260                continue;
14261            }
14262            Iterator<PreferredActivity> it = pir.filterIterator();
14263            while (it.hasNext()) {
14264                PreferredActivity pa = it.next();
14265                // Mark entry for removal only if it matches the package name
14266                // and the entry is of type "always".
14267                if (packageName == null ||
14268                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14269                                && pa.mPref.mAlways)) {
14270                    if (removed == null) {
14271                        removed = new ArrayList<PreferredActivity>();
14272                    }
14273                    removed.add(pa);
14274                }
14275            }
14276            if (removed != null) {
14277                for (int j=0; j<removed.size(); j++) {
14278                    PreferredActivity pa = removed.get(j);
14279                    pir.removeFilter(pa);
14280                }
14281                changed = true;
14282            }
14283        }
14284        return changed;
14285    }
14286
14287    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14288    private void clearIntentFilterVerificationsLPw(int userId) {
14289        final int packageCount = mPackages.size();
14290        for (int i = 0; i < packageCount; i++) {
14291            PackageParser.Package pkg = mPackages.valueAt(i);
14292            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14293        }
14294    }
14295
14296    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14297    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14298        if (userId == UserHandle.USER_ALL) {
14299            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14300                    sUserManager.getUserIds())) {
14301                for (int oneUserId : sUserManager.getUserIds()) {
14302                    scheduleWritePackageRestrictionsLocked(oneUserId);
14303                }
14304            }
14305        } else {
14306            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14307                scheduleWritePackageRestrictionsLocked(userId);
14308            }
14309        }
14310    }
14311
14312    void clearDefaultBrowserIfNeeded(String packageName) {
14313        for (int oneUserId : sUserManager.getUserIds()) {
14314            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14315            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14316            if (packageName.equals(defaultBrowserPackageName)) {
14317                setDefaultBrowserPackageName(null, oneUserId);
14318            }
14319        }
14320    }
14321
14322    @Override
14323    public void resetApplicationPreferences(int userId) {
14324        mContext.enforceCallingOrSelfPermission(
14325                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14326        // writer
14327        synchronized (mPackages) {
14328            final long identity = Binder.clearCallingIdentity();
14329            try {
14330                clearPackagePreferredActivitiesLPw(null, userId);
14331                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14332                // TODO: We have to reset the default SMS and Phone. This requires
14333                // significant refactoring to keep all default apps in the package
14334                // manager (cleaner but more work) or have the services provide
14335                // callbacks to the package manager to request a default app reset.
14336                applyFactoryDefaultBrowserLPw(userId);
14337                clearIntentFilterVerificationsLPw(userId);
14338                primeDomainVerificationsLPw(userId);
14339                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14340                scheduleWritePackageRestrictionsLocked(userId);
14341            } finally {
14342                Binder.restoreCallingIdentity(identity);
14343            }
14344        }
14345    }
14346
14347    @Override
14348    public int getPreferredActivities(List<IntentFilter> outFilters,
14349            List<ComponentName> outActivities, String packageName) {
14350
14351        int num = 0;
14352        final int userId = UserHandle.getCallingUserId();
14353        // reader
14354        synchronized (mPackages) {
14355            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14356            if (pir != null) {
14357                final Iterator<PreferredActivity> it = pir.filterIterator();
14358                while (it.hasNext()) {
14359                    final PreferredActivity pa = it.next();
14360                    if (packageName == null
14361                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14362                                    && pa.mPref.mAlways)) {
14363                        if (outFilters != null) {
14364                            outFilters.add(new IntentFilter(pa));
14365                        }
14366                        if (outActivities != null) {
14367                            outActivities.add(pa.mPref.mComponent);
14368                        }
14369                    }
14370                }
14371            }
14372        }
14373
14374        return num;
14375    }
14376
14377    @Override
14378    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14379            int userId) {
14380        int callingUid = Binder.getCallingUid();
14381        if (callingUid != Process.SYSTEM_UID) {
14382            throw new SecurityException(
14383                    "addPersistentPreferredActivity can only be run by the system");
14384        }
14385        if (filter.countActions() == 0) {
14386            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14387            return;
14388        }
14389        synchronized (mPackages) {
14390            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14391                    " :");
14392            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14393            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14394                    new PersistentPreferredActivity(filter, activity));
14395            scheduleWritePackageRestrictionsLocked(userId);
14396        }
14397    }
14398
14399    @Override
14400    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14401        int callingUid = Binder.getCallingUid();
14402        if (callingUid != Process.SYSTEM_UID) {
14403            throw new SecurityException(
14404                    "clearPackagePersistentPreferredActivities can only be run by the system");
14405        }
14406        ArrayList<PersistentPreferredActivity> removed = null;
14407        boolean changed = false;
14408        synchronized (mPackages) {
14409            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14410                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14411                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14412                        .valueAt(i);
14413                if (userId != thisUserId) {
14414                    continue;
14415                }
14416                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14417                while (it.hasNext()) {
14418                    PersistentPreferredActivity ppa = it.next();
14419                    // Mark entry for removal only if it matches the package name.
14420                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14421                        if (removed == null) {
14422                            removed = new ArrayList<PersistentPreferredActivity>();
14423                        }
14424                        removed.add(ppa);
14425                    }
14426                }
14427                if (removed != null) {
14428                    for (int j=0; j<removed.size(); j++) {
14429                        PersistentPreferredActivity ppa = removed.get(j);
14430                        ppir.removeFilter(ppa);
14431                    }
14432                    changed = true;
14433                }
14434            }
14435
14436            if (changed) {
14437                scheduleWritePackageRestrictionsLocked(userId);
14438            }
14439        }
14440    }
14441
14442    /**
14443     * Common machinery for picking apart a restored XML blob and passing
14444     * it to a caller-supplied functor to be applied to the running system.
14445     */
14446    private void restoreFromXml(XmlPullParser parser, int userId,
14447            String expectedStartTag, BlobXmlRestorer functor)
14448            throws IOException, XmlPullParserException {
14449        int type;
14450        while ((type = parser.next()) != XmlPullParser.START_TAG
14451                && type != XmlPullParser.END_DOCUMENT) {
14452        }
14453        if (type != XmlPullParser.START_TAG) {
14454            // oops didn't find a start tag?!
14455            if (DEBUG_BACKUP) {
14456                Slog.e(TAG, "Didn't find start tag during restore");
14457            }
14458            return;
14459        }
14460
14461        // this is supposed to be TAG_PREFERRED_BACKUP
14462        if (!expectedStartTag.equals(parser.getName())) {
14463            if (DEBUG_BACKUP) {
14464                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14465            }
14466            return;
14467        }
14468
14469        // skip interfering stuff, then we're aligned with the backing implementation
14470        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14471        functor.apply(parser, userId);
14472    }
14473
14474    private interface BlobXmlRestorer {
14475        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14476    }
14477
14478    /**
14479     * Non-Binder method, support for the backup/restore mechanism: write the
14480     * full set of preferred activities in its canonical XML format.  Returns the
14481     * XML output as a byte array, or null if there is none.
14482     */
14483    @Override
14484    public byte[] getPreferredActivityBackup(int userId) {
14485        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14486            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14487        }
14488
14489        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14490        try {
14491            final XmlSerializer serializer = new FastXmlSerializer();
14492            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14493            serializer.startDocument(null, true);
14494            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14495
14496            synchronized (mPackages) {
14497                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14498            }
14499
14500            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14501            serializer.endDocument();
14502            serializer.flush();
14503        } catch (Exception e) {
14504            if (DEBUG_BACKUP) {
14505                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14506            }
14507            return null;
14508        }
14509
14510        return dataStream.toByteArray();
14511    }
14512
14513    @Override
14514    public void restorePreferredActivities(byte[] backup, int userId) {
14515        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14516            throw new SecurityException("Only the system may call restorePreferredActivities()");
14517        }
14518
14519        try {
14520            final XmlPullParser parser = Xml.newPullParser();
14521            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14522            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14523                    new BlobXmlRestorer() {
14524                        @Override
14525                        public void apply(XmlPullParser parser, int userId)
14526                                throws XmlPullParserException, IOException {
14527                            synchronized (mPackages) {
14528                                mSettings.readPreferredActivitiesLPw(parser, userId);
14529                            }
14530                        }
14531                    } );
14532        } catch (Exception e) {
14533            if (DEBUG_BACKUP) {
14534                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14535            }
14536        }
14537    }
14538
14539    /**
14540     * Non-Binder method, support for the backup/restore mechanism: write the
14541     * default browser (etc) settings in its canonical XML format.  Returns the default
14542     * browser XML representation as a byte array, or null if there is none.
14543     */
14544    @Override
14545    public byte[] getDefaultAppsBackup(int userId) {
14546        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14547            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14548        }
14549
14550        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14551        try {
14552            final XmlSerializer serializer = new FastXmlSerializer();
14553            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14554            serializer.startDocument(null, true);
14555            serializer.startTag(null, TAG_DEFAULT_APPS);
14556
14557            synchronized (mPackages) {
14558                mSettings.writeDefaultAppsLPr(serializer, userId);
14559            }
14560
14561            serializer.endTag(null, TAG_DEFAULT_APPS);
14562            serializer.endDocument();
14563            serializer.flush();
14564        } catch (Exception e) {
14565            if (DEBUG_BACKUP) {
14566                Slog.e(TAG, "Unable to write default apps for backup", e);
14567            }
14568            return null;
14569        }
14570
14571        return dataStream.toByteArray();
14572    }
14573
14574    @Override
14575    public void restoreDefaultApps(byte[] backup, int userId) {
14576        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14577            throw new SecurityException("Only the system may call restoreDefaultApps()");
14578        }
14579
14580        try {
14581            final XmlPullParser parser = Xml.newPullParser();
14582            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14583            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14584                    new BlobXmlRestorer() {
14585                        @Override
14586                        public void apply(XmlPullParser parser, int userId)
14587                                throws XmlPullParserException, IOException {
14588                            synchronized (mPackages) {
14589                                mSettings.readDefaultAppsLPw(parser, userId);
14590                            }
14591                        }
14592                    } );
14593        } catch (Exception e) {
14594            if (DEBUG_BACKUP) {
14595                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14596            }
14597        }
14598    }
14599
14600    @Override
14601    public byte[] getIntentFilterVerificationBackup(int userId) {
14602        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14603            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14604        }
14605
14606        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14607        try {
14608            final XmlSerializer serializer = new FastXmlSerializer();
14609            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14610            serializer.startDocument(null, true);
14611            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14612
14613            synchronized (mPackages) {
14614                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14615            }
14616
14617            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14618            serializer.endDocument();
14619            serializer.flush();
14620        } catch (Exception e) {
14621            if (DEBUG_BACKUP) {
14622                Slog.e(TAG, "Unable to write default apps for backup", e);
14623            }
14624            return null;
14625        }
14626
14627        return dataStream.toByteArray();
14628    }
14629
14630    @Override
14631    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14632        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14633            throw new SecurityException("Only the system may call restorePreferredActivities()");
14634        }
14635
14636        try {
14637            final XmlPullParser parser = Xml.newPullParser();
14638            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14639            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14640                    new BlobXmlRestorer() {
14641                        @Override
14642                        public void apply(XmlPullParser parser, int userId)
14643                                throws XmlPullParserException, IOException {
14644                            synchronized (mPackages) {
14645                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14646                                mSettings.writeLPr();
14647                            }
14648                        }
14649                    } );
14650        } catch (Exception e) {
14651            if (DEBUG_BACKUP) {
14652                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14653            }
14654        }
14655    }
14656
14657    @Override
14658    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14659            int sourceUserId, int targetUserId, int flags) {
14660        mContext.enforceCallingOrSelfPermission(
14661                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14662        int callingUid = Binder.getCallingUid();
14663        enforceOwnerRights(ownerPackage, callingUid);
14664        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14665        if (intentFilter.countActions() == 0) {
14666            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14667            return;
14668        }
14669        synchronized (mPackages) {
14670            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14671                    ownerPackage, targetUserId, flags);
14672            CrossProfileIntentResolver resolver =
14673                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14674            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14675            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14676            if (existing != null) {
14677                int size = existing.size();
14678                for (int i = 0; i < size; i++) {
14679                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14680                        return;
14681                    }
14682                }
14683            }
14684            resolver.addFilter(newFilter);
14685            scheduleWritePackageRestrictionsLocked(sourceUserId);
14686        }
14687    }
14688
14689    @Override
14690    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14691        mContext.enforceCallingOrSelfPermission(
14692                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14693        int callingUid = Binder.getCallingUid();
14694        enforceOwnerRights(ownerPackage, callingUid);
14695        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14696        synchronized (mPackages) {
14697            CrossProfileIntentResolver resolver =
14698                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14699            ArraySet<CrossProfileIntentFilter> set =
14700                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14701            for (CrossProfileIntentFilter filter : set) {
14702                if (filter.getOwnerPackage().equals(ownerPackage)) {
14703                    resolver.removeFilter(filter);
14704                }
14705            }
14706            scheduleWritePackageRestrictionsLocked(sourceUserId);
14707        }
14708    }
14709
14710    // Enforcing that callingUid is owning pkg on userId
14711    private void enforceOwnerRights(String pkg, int callingUid) {
14712        // The system owns everything.
14713        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14714            return;
14715        }
14716        int callingUserId = UserHandle.getUserId(callingUid);
14717        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14718        if (pi == null) {
14719            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14720                    + callingUserId);
14721        }
14722        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14723            throw new SecurityException("Calling uid " + callingUid
14724                    + " does not own package " + pkg);
14725        }
14726    }
14727
14728    @Override
14729    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14730        Intent intent = new Intent(Intent.ACTION_MAIN);
14731        intent.addCategory(Intent.CATEGORY_HOME);
14732
14733        final int callingUserId = UserHandle.getCallingUserId();
14734        List<ResolveInfo> list = queryIntentActivities(intent, null,
14735                PackageManager.GET_META_DATA, callingUserId);
14736        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14737                true, false, false, callingUserId);
14738
14739        allHomeCandidates.clear();
14740        if (list != null) {
14741            for (ResolveInfo ri : list) {
14742                allHomeCandidates.add(ri);
14743            }
14744        }
14745        return (preferred == null || preferred.activityInfo == null)
14746                ? null
14747                : new ComponentName(preferred.activityInfo.packageName,
14748                        preferred.activityInfo.name);
14749    }
14750
14751    @Override
14752    public void setApplicationEnabledSetting(String appPackageName,
14753            int newState, int flags, int userId, String callingPackage) {
14754        if (!sUserManager.exists(userId)) return;
14755        if (callingPackage == null) {
14756            callingPackage = Integer.toString(Binder.getCallingUid());
14757        }
14758        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14759    }
14760
14761    @Override
14762    public void setComponentEnabledSetting(ComponentName componentName,
14763            int newState, int flags, int userId) {
14764        if (!sUserManager.exists(userId)) return;
14765        setEnabledSetting(componentName.getPackageName(),
14766                componentName.getClassName(), newState, flags, userId, null);
14767    }
14768
14769    private void setEnabledSetting(final String packageName, String className, int newState,
14770            final int flags, int userId, String callingPackage) {
14771        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14772              || newState == COMPONENT_ENABLED_STATE_ENABLED
14773              || newState == COMPONENT_ENABLED_STATE_DISABLED
14774              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14775              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14776            throw new IllegalArgumentException("Invalid new component state: "
14777                    + newState);
14778        }
14779        PackageSetting pkgSetting;
14780        final int uid = Binder.getCallingUid();
14781        final int permission = mContext.checkCallingOrSelfPermission(
14782                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14783        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14784        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14785        boolean sendNow = false;
14786        boolean isApp = (className == null);
14787        String componentName = isApp ? packageName : className;
14788        int packageUid = -1;
14789        ArrayList<String> components;
14790
14791        // writer
14792        synchronized (mPackages) {
14793            pkgSetting = mSettings.mPackages.get(packageName);
14794            if (pkgSetting == null) {
14795                if (className == null) {
14796                    throw new IllegalArgumentException(
14797                            "Unknown package: " + packageName);
14798                }
14799                throw new IllegalArgumentException(
14800                        "Unknown component: " + packageName
14801                        + "/" + className);
14802            }
14803            // Allow root and verify that userId is not being specified by a different user
14804            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14805                throw new SecurityException(
14806                        "Permission Denial: attempt to change component state from pid="
14807                        + Binder.getCallingPid()
14808                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14809            }
14810            if (className == null) {
14811                // We're dealing with an application/package level state change
14812                if (pkgSetting.getEnabled(userId) == newState) {
14813                    // Nothing to do
14814                    return;
14815                }
14816                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14817                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14818                    // Don't care about who enables an app.
14819                    callingPackage = null;
14820                }
14821                pkgSetting.setEnabled(newState, userId, callingPackage);
14822                // pkgSetting.pkg.mSetEnabled = newState;
14823            } else {
14824                // We're dealing with a component level state change
14825                // First, verify that this is a valid class name.
14826                PackageParser.Package pkg = pkgSetting.pkg;
14827                if (pkg == null || !pkg.hasComponentClassName(className)) {
14828                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14829                        throw new IllegalArgumentException("Component class " + className
14830                                + " does not exist in " + packageName);
14831                    } else {
14832                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14833                                + className + " does not exist in " + packageName);
14834                    }
14835                }
14836                switch (newState) {
14837                case COMPONENT_ENABLED_STATE_ENABLED:
14838                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14839                        return;
14840                    }
14841                    break;
14842                case COMPONENT_ENABLED_STATE_DISABLED:
14843                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14844                        return;
14845                    }
14846                    break;
14847                case COMPONENT_ENABLED_STATE_DEFAULT:
14848                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14849                        return;
14850                    }
14851                    break;
14852                default:
14853                    Slog.e(TAG, "Invalid new component state: " + newState);
14854                    return;
14855                }
14856            }
14857            scheduleWritePackageRestrictionsLocked(userId);
14858            components = mPendingBroadcasts.get(userId, packageName);
14859            final boolean newPackage = components == null;
14860            if (newPackage) {
14861                components = new ArrayList<String>();
14862            }
14863            if (!components.contains(componentName)) {
14864                components.add(componentName);
14865            }
14866            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14867                sendNow = true;
14868                // Purge entry from pending broadcast list if another one exists already
14869                // since we are sending one right away.
14870                mPendingBroadcasts.remove(userId, packageName);
14871            } else {
14872                if (newPackage) {
14873                    mPendingBroadcasts.put(userId, packageName, components);
14874                }
14875                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14876                    // Schedule a message
14877                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14878                }
14879            }
14880        }
14881
14882        long callingId = Binder.clearCallingIdentity();
14883        try {
14884            if (sendNow) {
14885                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14886                sendPackageChangedBroadcast(packageName,
14887                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14888            }
14889        } finally {
14890            Binder.restoreCallingIdentity(callingId);
14891        }
14892    }
14893
14894    private void sendPackageChangedBroadcast(String packageName,
14895            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14896        if (DEBUG_INSTALL)
14897            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14898                    + componentNames);
14899        Bundle extras = new Bundle(4);
14900        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14901        String nameList[] = new String[componentNames.size()];
14902        componentNames.toArray(nameList);
14903        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14904        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14905        extras.putInt(Intent.EXTRA_UID, packageUid);
14906        // If this is not reporting a change of the overall package, then only send it
14907        // to registered receivers.  We don't want to launch a swath of apps for every
14908        // little component state change.
14909        final int flags = !componentNames.contains(packageName)
14910                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
14911        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
14912                new int[] {UserHandle.getUserId(packageUid)});
14913    }
14914
14915    @Override
14916    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14917        if (!sUserManager.exists(userId)) return;
14918        final int uid = Binder.getCallingUid();
14919        final int permission = mContext.checkCallingOrSelfPermission(
14920                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14921        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14922        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14923        // writer
14924        synchronized (mPackages) {
14925            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14926                    allowedByPermission, uid, userId)) {
14927                scheduleWritePackageRestrictionsLocked(userId);
14928            }
14929        }
14930    }
14931
14932    @Override
14933    public String getInstallerPackageName(String packageName) {
14934        // reader
14935        synchronized (mPackages) {
14936            return mSettings.getInstallerPackageNameLPr(packageName);
14937        }
14938    }
14939
14940    @Override
14941    public int getApplicationEnabledSetting(String packageName, int userId) {
14942        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14943        int uid = Binder.getCallingUid();
14944        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14945        // reader
14946        synchronized (mPackages) {
14947            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14948        }
14949    }
14950
14951    @Override
14952    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14953        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14954        int uid = Binder.getCallingUid();
14955        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14956        // reader
14957        synchronized (mPackages) {
14958            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14959        }
14960    }
14961
14962    @Override
14963    public void enterSafeMode() {
14964        enforceSystemOrRoot("Only the system can request entering safe mode");
14965
14966        if (!mSystemReady) {
14967            mSafeMode = true;
14968        }
14969    }
14970
14971    @Override
14972    public void systemReady() {
14973        mSystemReady = true;
14974
14975        // Read the compatibilty setting when the system is ready.
14976        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14977                mContext.getContentResolver(),
14978                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14979        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14980        if (DEBUG_SETTINGS) {
14981            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14982        }
14983
14984        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14985
14986        synchronized (mPackages) {
14987            // Verify that all of the preferred activity components actually
14988            // exist.  It is possible for applications to be updated and at
14989            // that point remove a previously declared activity component that
14990            // had been set as a preferred activity.  We try to clean this up
14991            // the next time we encounter that preferred activity, but it is
14992            // possible for the user flow to never be able to return to that
14993            // situation so here we do a sanity check to make sure we haven't
14994            // left any junk around.
14995            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14996            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14997                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14998                removed.clear();
14999                for (PreferredActivity pa : pir.filterSet()) {
15000                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15001                        removed.add(pa);
15002                    }
15003                }
15004                if (removed.size() > 0) {
15005                    for (int r=0; r<removed.size(); r++) {
15006                        PreferredActivity pa = removed.get(r);
15007                        Slog.w(TAG, "Removing dangling preferred activity: "
15008                                + pa.mPref.mComponent);
15009                        pir.removeFilter(pa);
15010                    }
15011                    mSettings.writePackageRestrictionsLPr(
15012                            mSettings.mPreferredActivities.keyAt(i));
15013                }
15014            }
15015
15016            for (int userId : UserManagerService.getInstance().getUserIds()) {
15017                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15018                    grantPermissionsUserIds = ArrayUtils.appendInt(
15019                            grantPermissionsUserIds, userId);
15020                }
15021            }
15022        }
15023        sUserManager.systemReady();
15024
15025        // If we upgraded grant all default permissions before kicking off.
15026        for (int userId : grantPermissionsUserIds) {
15027            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15028        }
15029
15030        // Kick off any messages waiting for system ready
15031        if (mPostSystemReadyMessages != null) {
15032            for (Message msg : mPostSystemReadyMessages) {
15033                msg.sendToTarget();
15034            }
15035            mPostSystemReadyMessages = null;
15036        }
15037
15038        // Watch for external volumes that come and go over time
15039        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15040        storage.registerListener(mStorageListener);
15041
15042        mInstallerService.systemReady();
15043        mPackageDexOptimizer.systemReady();
15044
15045        MountServiceInternal mountServiceInternal = LocalServices.getService(
15046                MountServiceInternal.class);
15047        mountServiceInternal.addExternalStoragePolicy(
15048                new MountServiceInternal.ExternalStorageMountPolicy() {
15049            @Override
15050            public int getMountMode(int uid, String packageName) {
15051                if (Process.isIsolated(uid)) {
15052                    return Zygote.MOUNT_EXTERNAL_NONE;
15053                }
15054                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15055                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15056                }
15057                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15058                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15059                }
15060                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15061                    return Zygote.MOUNT_EXTERNAL_READ;
15062                }
15063                return Zygote.MOUNT_EXTERNAL_WRITE;
15064            }
15065
15066            @Override
15067            public boolean hasExternalStorage(int uid, String packageName) {
15068                return true;
15069            }
15070        });
15071    }
15072
15073    @Override
15074    public boolean isSafeMode() {
15075        return mSafeMode;
15076    }
15077
15078    @Override
15079    public boolean hasSystemUidErrors() {
15080        return mHasSystemUidErrors;
15081    }
15082
15083    static String arrayToString(int[] array) {
15084        StringBuffer buf = new StringBuffer(128);
15085        buf.append('[');
15086        if (array != null) {
15087            for (int i=0; i<array.length; i++) {
15088                if (i > 0) buf.append(", ");
15089                buf.append(array[i]);
15090            }
15091        }
15092        buf.append(']');
15093        return buf.toString();
15094    }
15095
15096    static class DumpState {
15097        public static final int DUMP_LIBS = 1 << 0;
15098        public static final int DUMP_FEATURES = 1 << 1;
15099        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15100        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15101        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15102        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15103        public static final int DUMP_PERMISSIONS = 1 << 6;
15104        public static final int DUMP_PACKAGES = 1 << 7;
15105        public static final int DUMP_SHARED_USERS = 1 << 8;
15106        public static final int DUMP_MESSAGES = 1 << 9;
15107        public static final int DUMP_PROVIDERS = 1 << 10;
15108        public static final int DUMP_VERIFIERS = 1 << 11;
15109        public static final int DUMP_PREFERRED = 1 << 12;
15110        public static final int DUMP_PREFERRED_XML = 1 << 13;
15111        public static final int DUMP_KEYSETS = 1 << 14;
15112        public static final int DUMP_VERSION = 1 << 15;
15113        public static final int DUMP_INSTALLS = 1 << 16;
15114        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15115        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15116
15117        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15118
15119        private int mTypes;
15120
15121        private int mOptions;
15122
15123        private boolean mTitlePrinted;
15124
15125        private SharedUserSetting mSharedUser;
15126
15127        public boolean isDumping(int type) {
15128            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15129                return true;
15130            }
15131
15132            return (mTypes & type) != 0;
15133        }
15134
15135        public void setDump(int type) {
15136            mTypes |= type;
15137        }
15138
15139        public boolean isOptionEnabled(int option) {
15140            return (mOptions & option) != 0;
15141        }
15142
15143        public void setOptionEnabled(int option) {
15144            mOptions |= option;
15145        }
15146
15147        public boolean onTitlePrinted() {
15148            final boolean printed = mTitlePrinted;
15149            mTitlePrinted = true;
15150            return printed;
15151        }
15152
15153        public boolean getTitlePrinted() {
15154            return mTitlePrinted;
15155        }
15156
15157        public void setTitlePrinted(boolean enabled) {
15158            mTitlePrinted = enabled;
15159        }
15160
15161        public SharedUserSetting getSharedUser() {
15162            return mSharedUser;
15163        }
15164
15165        public void setSharedUser(SharedUserSetting user) {
15166            mSharedUser = user;
15167        }
15168    }
15169
15170    @Override
15171    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15172            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15173        (new PackageManagerShellCommand(this)).exec(
15174                this, in, out, err, args, resultReceiver);
15175    }
15176
15177    @Override
15178    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15179        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15180                != PackageManager.PERMISSION_GRANTED) {
15181            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15182                    + Binder.getCallingPid()
15183                    + ", uid=" + Binder.getCallingUid()
15184                    + " without permission "
15185                    + android.Manifest.permission.DUMP);
15186            return;
15187        }
15188
15189        DumpState dumpState = new DumpState();
15190        boolean fullPreferred = false;
15191        boolean checkin = false;
15192
15193        String packageName = null;
15194        ArraySet<String> permissionNames = null;
15195
15196        int opti = 0;
15197        while (opti < args.length) {
15198            String opt = args[opti];
15199            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15200                break;
15201            }
15202            opti++;
15203
15204            if ("-a".equals(opt)) {
15205                // Right now we only know how to print all.
15206            } else if ("-h".equals(opt)) {
15207                pw.println("Package manager dump options:");
15208                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15209                pw.println("    --checkin: dump for a checkin");
15210                pw.println("    -f: print details of intent filters");
15211                pw.println("    -h: print this help");
15212                pw.println("  cmd may be one of:");
15213                pw.println("    l[ibraries]: list known shared libraries");
15214                pw.println("    f[eatures]: list device features");
15215                pw.println("    k[eysets]: print known keysets");
15216                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15217                pw.println("    perm[issions]: dump permissions");
15218                pw.println("    permission [name ...]: dump declaration and use of given permission");
15219                pw.println("    pref[erred]: print preferred package settings");
15220                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15221                pw.println("    prov[iders]: dump content providers");
15222                pw.println("    p[ackages]: dump installed packages");
15223                pw.println("    s[hared-users]: dump shared user IDs");
15224                pw.println("    m[essages]: print collected runtime messages");
15225                pw.println("    v[erifiers]: print package verifier info");
15226                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15227                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15228                pw.println("    version: print database version info");
15229                pw.println("    write: write current settings now");
15230                pw.println("    installs: details about install sessions");
15231                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15232                pw.println("    <package.name>: info about given package");
15233                return;
15234            } else if ("--checkin".equals(opt)) {
15235                checkin = true;
15236            } else if ("-f".equals(opt)) {
15237                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15238            } else {
15239                pw.println("Unknown argument: " + opt + "; use -h for help");
15240            }
15241        }
15242
15243        // Is the caller requesting to dump a particular piece of data?
15244        if (opti < args.length) {
15245            String cmd = args[opti];
15246            opti++;
15247            // Is this a package name?
15248            if ("android".equals(cmd) || cmd.contains(".")) {
15249                packageName = cmd;
15250                // When dumping a single package, we always dump all of its
15251                // filter information since the amount of data will be reasonable.
15252                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15253            } else if ("check-permission".equals(cmd)) {
15254                if (opti >= args.length) {
15255                    pw.println("Error: check-permission missing permission argument");
15256                    return;
15257                }
15258                String perm = args[opti];
15259                opti++;
15260                if (opti >= args.length) {
15261                    pw.println("Error: check-permission missing package argument");
15262                    return;
15263                }
15264                String pkg = args[opti];
15265                opti++;
15266                int user = UserHandle.getUserId(Binder.getCallingUid());
15267                if (opti < args.length) {
15268                    try {
15269                        user = Integer.parseInt(args[opti]);
15270                    } catch (NumberFormatException e) {
15271                        pw.println("Error: check-permission user argument is not a number: "
15272                                + args[opti]);
15273                        return;
15274                    }
15275                }
15276                pw.println(checkPermission(perm, pkg, user));
15277                return;
15278            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15279                dumpState.setDump(DumpState.DUMP_LIBS);
15280            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15281                dumpState.setDump(DumpState.DUMP_FEATURES);
15282            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15283                if (opti >= args.length) {
15284                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15285                            | DumpState.DUMP_SERVICE_RESOLVERS
15286                            | DumpState.DUMP_RECEIVER_RESOLVERS
15287                            | DumpState.DUMP_CONTENT_RESOLVERS);
15288                } else {
15289                    while (opti < args.length) {
15290                        String name = args[opti];
15291                        if ("a".equals(name) || "activity".equals(name)) {
15292                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15293                        } else if ("s".equals(name) || "service".equals(name)) {
15294                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15295                        } else if ("r".equals(name) || "receiver".equals(name)) {
15296                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15297                        } else if ("c".equals(name) || "content".equals(name)) {
15298                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15299                        } else {
15300                            pw.println("Error: unknown resolver table type: " + name);
15301                            return;
15302                        }
15303                        opti++;
15304                    }
15305                }
15306            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15307                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15308            } else if ("permission".equals(cmd)) {
15309                if (opti >= args.length) {
15310                    pw.println("Error: permission requires permission name");
15311                    return;
15312                }
15313                permissionNames = new ArraySet<>();
15314                while (opti < args.length) {
15315                    permissionNames.add(args[opti]);
15316                    opti++;
15317                }
15318                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15319                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15320            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15321                dumpState.setDump(DumpState.DUMP_PREFERRED);
15322            } else if ("preferred-xml".equals(cmd)) {
15323                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15324                if (opti < args.length && "--full".equals(args[opti])) {
15325                    fullPreferred = true;
15326                    opti++;
15327                }
15328            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15329                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15330            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15331                dumpState.setDump(DumpState.DUMP_PACKAGES);
15332            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15333                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15334            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15335                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15336            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15337                dumpState.setDump(DumpState.DUMP_MESSAGES);
15338            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15339                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15340            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15341                    || "intent-filter-verifiers".equals(cmd)) {
15342                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15343            } else if ("version".equals(cmd)) {
15344                dumpState.setDump(DumpState.DUMP_VERSION);
15345            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15346                dumpState.setDump(DumpState.DUMP_KEYSETS);
15347            } else if ("installs".equals(cmd)) {
15348                dumpState.setDump(DumpState.DUMP_INSTALLS);
15349            } else if ("write".equals(cmd)) {
15350                synchronized (mPackages) {
15351                    mSettings.writeLPr();
15352                    pw.println("Settings written.");
15353                    return;
15354                }
15355            }
15356        }
15357
15358        if (checkin) {
15359            pw.println("vers,1");
15360        }
15361
15362        // reader
15363        synchronized (mPackages) {
15364            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15365                if (!checkin) {
15366                    if (dumpState.onTitlePrinted())
15367                        pw.println();
15368                    pw.println("Database versions:");
15369                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15370                }
15371            }
15372
15373            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15374                if (!checkin) {
15375                    if (dumpState.onTitlePrinted())
15376                        pw.println();
15377                    pw.println("Verifiers:");
15378                    pw.print("  Required: ");
15379                    pw.print(mRequiredVerifierPackage);
15380                    pw.print(" (uid=");
15381                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15382                    pw.println(")");
15383                } else if (mRequiredVerifierPackage != null) {
15384                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15385                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15386                }
15387            }
15388
15389            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15390                    packageName == null) {
15391                if (mIntentFilterVerifierComponent != null) {
15392                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15393                    if (!checkin) {
15394                        if (dumpState.onTitlePrinted())
15395                            pw.println();
15396                        pw.println("Intent Filter Verifier:");
15397                        pw.print("  Using: ");
15398                        pw.print(verifierPackageName);
15399                        pw.print(" (uid=");
15400                        pw.print(getPackageUid(verifierPackageName, 0));
15401                        pw.println(")");
15402                    } else if (verifierPackageName != null) {
15403                        pw.print("ifv,"); pw.print(verifierPackageName);
15404                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15405                    }
15406                } else {
15407                    pw.println();
15408                    pw.println("No Intent Filter Verifier available!");
15409                }
15410            }
15411
15412            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15413                boolean printedHeader = false;
15414                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15415                while (it.hasNext()) {
15416                    String name = it.next();
15417                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15418                    if (!checkin) {
15419                        if (!printedHeader) {
15420                            if (dumpState.onTitlePrinted())
15421                                pw.println();
15422                            pw.println("Libraries:");
15423                            printedHeader = true;
15424                        }
15425                        pw.print("  ");
15426                    } else {
15427                        pw.print("lib,");
15428                    }
15429                    pw.print(name);
15430                    if (!checkin) {
15431                        pw.print(" -> ");
15432                    }
15433                    if (ent.path != null) {
15434                        if (!checkin) {
15435                            pw.print("(jar) ");
15436                            pw.print(ent.path);
15437                        } else {
15438                            pw.print(",jar,");
15439                            pw.print(ent.path);
15440                        }
15441                    } else {
15442                        if (!checkin) {
15443                            pw.print("(apk) ");
15444                            pw.print(ent.apk);
15445                        } else {
15446                            pw.print(",apk,");
15447                            pw.print(ent.apk);
15448                        }
15449                    }
15450                    pw.println();
15451                }
15452            }
15453
15454            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15455                if (dumpState.onTitlePrinted())
15456                    pw.println();
15457                if (!checkin) {
15458                    pw.println("Features:");
15459                }
15460                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15461                while (it.hasNext()) {
15462                    String name = it.next();
15463                    if (!checkin) {
15464                        pw.print("  ");
15465                    } else {
15466                        pw.print("feat,");
15467                    }
15468                    pw.println(name);
15469                }
15470            }
15471
15472            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15473                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15474                        : "Activity Resolver Table:", "  ", packageName,
15475                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15476                    dumpState.setTitlePrinted(true);
15477                }
15478            }
15479            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15480                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15481                        : "Receiver Resolver Table:", "  ", packageName,
15482                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15483                    dumpState.setTitlePrinted(true);
15484                }
15485            }
15486            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15487                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15488                        : "Service Resolver Table:", "  ", packageName,
15489                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15490                    dumpState.setTitlePrinted(true);
15491                }
15492            }
15493            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15494                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15495                        : "Provider Resolver Table:", "  ", packageName,
15496                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15497                    dumpState.setTitlePrinted(true);
15498                }
15499            }
15500
15501            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15502                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15503                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15504                    int user = mSettings.mPreferredActivities.keyAt(i);
15505                    if (pir.dump(pw,
15506                            dumpState.getTitlePrinted()
15507                                ? "\nPreferred Activities User " + user + ":"
15508                                : "Preferred Activities User " + user + ":", "  ",
15509                            packageName, true, false)) {
15510                        dumpState.setTitlePrinted(true);
15511                    }
15512                }
15513            }
15514
15515            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15516                pw.flush();
15517                FileOutputStream fout = new FileOutputStream(fd);
15518                BufferedOutputStream str = new BufferedOutputStream(fout);
15519                XmlSerializer serializer = new FastXmlSerializer();
15520                try {
15521                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15522                    serializer.startDocument(null, true);
15523                    serializer.setFeature(
15524                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15525                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15526                    serializer.endDocument();
15527                    serializer.flush();
15528                } catch (IllegalArgumentException e) {
15529                    pw.println("Failed writing: " + e);
15530                } catch (IllegalStateException e) {
15531                    pw.println("Failed writing: " + e);
15532                } catch (IOException e) {
15533                    pw.println("Failed writing: " + e);
15534                }
15535            }
15536
15537            if (!checkin
15538                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15539                    && packageName == null) {
15540                pw.println();
15541                int count = mSettings.mPackages.size();
15542                if (count == 0) {
15543                    pw.println("No applications!");
15544                    pw.println();
15545                } else {
15546                    final String prefix = "  ";
15547                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15548                    if (allPackageSettings.size() == 0) {
15549                        pw.println("No domain preferred apps!");
15550                        pw.println();
15551                    } else {
15552                        pw.println("App verification status:");
15553                        pw.println();
15554                        count = 0;
15555                        for (PackageSetting ps : allPackageSettings) {
15556                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15557                            if (ivi == null || ivi.getPackageName() == null) continue;
15558                            pw.println(prefix + "Package: " + ivi.getPackageName());
15559                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15560                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15561                            pw.println();
15562                            count++;
15563                        }
15564                        if (count == 0) {
15565                            pw.println(prefix + "No app verification established.");
15566                            pw.println();
15567                        }
15568                        for (int userId : sUserManager.getUserIds()) {
15569                            pw.println("App linkages for user " + userId + ":");
15570                            pw.println();
15571                            count = 0;
15572                            for (PackageSetting ps : allPackageSettings) {
15573                                final long status = ps.getDomainVerificationStatusForUser(userId);
15574                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15575                                    continue;
15576                                }
15577                                pw.println(prefix + "Package: " + ps.name);
15578                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15579                                String statusStr = IntentFilterVerificationInfo.
15580                                        getStatusStringFromValue(status);
15581                                pw.println(prefix + "Status:  " + statusStr);
15582                                pw.println();
15583                                count++;
15584                            }
15585                            if (count == 0) {
15586                                pw.println(prefix + "No configured app linkages.");
15587                                pw.println();
15588                            }
15589                        }
15590                    }
15591                }
15592            }
15593
15594            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15595                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15596                if (packageName == null && permissionNames == null) {
15597                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15598                        if (iperm == 0) {
15599                            if (dumpState.onTitlePrinted())
15600                                pw.println();
15601                            pw.println("AppOp Permissions:");
15602                        }
15603                        pw.print("  AppOp Permission ");
15604                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15605                        pw.println(":");
15606                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15607                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15608                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15609                        }
15610                    }
15611                }
15612            }
15613
15614            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15615                boolean printedSomething = false;
15616                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15617                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15618                        continue;
15619                    }
15620                    if (!printedSomething) {
15621                        if (dumpState.onTitlePrinted())
15622                            pw.println();
15623                        pw.println("Registered ContentProviders:");
15624                        printedSomething = true;
15625                    }
15626                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15627                    pw.print("    "); pw.println(p.toString());
15628                }
15629                printedSomething = false;
15630                for (Map.Entry<String, PackageParser.Provider> entry :
15631                        mProvidersByAuthority.entrySet()) {
15632                    PackageParser.Provider p = entry.getValue();
15633                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15634                        continue;
15635                    }
15636                    if (!printedSomething) {
15637                        if (dumpState.onTitlePrinted())
15638                            pw.println();
15639                        pw.println("ContentProvider Authorities:");
15640                        printedSomething = true;
15641                    }
15642                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15643                    pw.print("    "); pw.println(p.toString());
15644                    if (p.info != null && p.info.applicationInfo != null) {
15645                        final String appInfo = p.info.applicationInfo.toString();
15646                        pw.print("      applicationInfo="); pw.println(appInfo);
15647                    }
15648                }
15649            }
15650
15651            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15652                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15653            }
15654
15655            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15656                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15657            }
15658
15659            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15660                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15661            }
15662
15663            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15664                // XXX should handle packageName != null by dumping only install data that
15665                // the given package is involved with.
15666                if (dumpState.onTitlePrinted()) pw.println();
15667                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15668            }
15669
15670            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15671                if (dumpState.onTitlePrinted()) pw.println();
15672                mSettings.dumpReadMessagesLPr(pw, dumpState);
15673
15674                pw.println();
15675                pw.println("Package warning messages:");
15676                BufferedReader in = null;
15677                String line = null;
15678                try {
15679                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15680                    while ((line = in.readLine()) != null) {
15681                        if (line.contains("ignored: updated version")) continue;
15682                        pw.println(line);
15683                    }
15684                } catch (IOException ignored) {
15685                } finally {
15686                    IoUtils.closeQuietly(in);
15687                }
15688            }
15689
15690            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15691                BufferedReader in = null;
15692                String line = null;
15693                try {
15694                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15695                    while ((line = in.readLine()) != null) {
15696                        if (line.contains("ignored: updated version")) continue;
15697                        pw.print("msg,");
15698                        pw.println(line);
15699                    }
15700                } catch (IOException ignored) {
15701                } finally {
15702                    IoUtils.closeQuietly(in);
15703                }
15704            }
15705        }
15706    }
15707
15708    private String dumpDomainString(String packageName) {
15709        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15710        List<IntentFilter> filters = getAllIntentFilters(packageName);
15711
15712        ArraySet<String> result = new ArraySet<>();
15713        if (iviList.size() > 0) {
15714            for (IntentFilterVerificationInfo ivi : iviList) {
15715                for (String host : ivi.getDomains()) {
15716                    result.add(host);
15717                }
15718            }
15719        }
15720        if (filters != null && filters.size() > 0) {
15721            for (IntentFilter filter : filters) {
15722                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15723                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15724                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15725                    result.addAll(filter.getHostsList());
15726                }
15727            }
15728        }
15729
15730        StringBuilder sb = new StringBuilder(result.size() * 16);
15731        for (String domain : result) {
15732            if (sb.length() > 0) sb.append(" ");
15733            sb.append(domain);
15734        }
15735        return sb.toString();
15736    }
15737
15738    // ------- apps on sdcard specific code -------
15739    static final boolean DEBUG_SD_INSTALL = false;
15740
15741    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15742
15743    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15744
15745    private boolean mMediaMounted = false;
15746
15747    static String getEncryptKey() {
15748        try {
15749            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15750                    SD_ENCRYPTION_KEYSTORE_NAME);
15751            if (sdEncKey == null) {
15752                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15753                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15754                if (sdEncKey == null) {
15755                    Slog.e(TAG, "Failed to create encryption keys");
15756                    return null;
15757                }
15758            }
15759            return sdEncKey;
15760        } catch (NoSuchAlgorithmException nsae) {
15761            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15762            return null;
15763        } catch (IOException ioe) {
15764            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15765            return null;
15766        }
15767    }
15768
15769    /*
15770     * Update media status on PackageManager.
15771     */
15772    @Override
15773    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15774        int callingUid = Binder.getCallingUid();
15775        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15776            throw new SecurityException("Media status can only be updated by the system");
15777        }
15778        // reader; this apparently protects mMediaMounted, but should probably
15779        // be a different lock in that case.
15780        synchronized (mPackages) {
15781            Log.i(TAG, "Updating external media status from "
15782                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15783                    + (mediaStatus ? "mounted" : "unmounted"));
15784            if (DEBUG_SD_INSTALL)
15785                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15786                        + ", mMediaMounted=" + mMediaMounted);
15787            if (mediaStatus == mMediaMounted) {
15788                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15789                        : 0, -1);
15790                mHandler.sendMessage(msg);
15791                return;
15792            }
15793            mMediaMounted = mediaStatus;
15794        }
15795        // Queue up an async operation since the package installation may take a
15796        // little while.
15797        mHandler.post(new Runnable() {
15798            public void run() {
15799                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15800            }
15801        });
15802    }
15803
15804    /**
15805     * Called by MountService when the initial ASECs to scan are available.
15806     * Should block until all the ASEC containers are finished being scanned.
15807     */
15808    public void scanAvailableAsecs() {
15809        updateExternalMediaStatusInner(true, false, false);
15810        if (mShouldRestoreconData) {
15811            SELinuxMMAC.setRestoreconDone();
15812            mShouldRestoreconData = false;
15813        }
15814    }
15815
15816    /*
15817     * Collect information of applications on external media, map them against
15818     * existing containers and update information based on current mount status.
15819     * Please note that we always have to report status if reportStatus has been
15820     * set to true especially when unloading packages.
15821     */
15822    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15823            boolean externalStorage) {
15824        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15825        int[] uidArr = EmptyArray.INT;
15826
15827        final String[] list = PackageHelper.getSecureContainerList();
15828        if (ArrayUtils.isEmpty(list)) {
15829            Log.i(TAG, "No secure containers found");
15830        } else {
15831            // Process list of secure containers and categorize them
15832            // as active or stale based on their package internal state.
15833
15834            // reader
15835            synchronized (mPackages) {
15836                for (String cid : list) {
15837                    // Leave stages untouched for now; installer service owns them
15838                    if (PackageInstallerService.isStageName(cid)) continue;
15839
15840                    if (DEBUG_SD_INSTALL)
15841                        Log.i(TAG, "Processing container " + cid);
15842                    String pkgName = getAsecPackageName(cid);
15843                    if (pkgName == null) {
15844                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15845                        continue;
15846                    }
15847                    if (DEBUG_SD_INSTALL)
15848                        Log.i(TAG, "Looking for pkg : " + pkgName);
15849
15850                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15851                    if (ps == null) {
15852                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15853                        continue;
15854                    }
15855
15856                    /*
15857                     * Skip packages that are not external if we're unmounting
15858                     * external storage.
15859                     */
15860                    if (externalStorage && !isMounted && !isExternal(ps)) {
15861                        continue;
15862                    }
15863
15864                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15865                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15866                    // The package status is changed only if the code path
15867                    // matches between settings and the container id.
15868                    if (ps.codePathString != null
15869                            && ps.codePathString.startsWith(args.getCodePath())) {
15870                        if (DEBUG_SD_INSTALL) {
15871                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15872                                    + " at code path: " + ps.codePathString);
15873                        }
15874
15875                        // We do have a valid package installed on sdcard
15876                        processCids.put(args, ps.codePathString);
15877                        final int uid = ps.appId;
15878                        if (uid != -1) {
15879                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15880                        }
15881                    } else {
15882                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15883                                + ps.codePathString);
15884                    }
15885                }
15886            }
15887
15888            Arrays.sort(uidArr);
15889        }
15890
15891        // Process packages with valid entries.
15892        if (isMounted) {
15893            if (DEBUG_SD_INSTALL)
15894                Log.i(TAG, "Loading packages");
15895            loadMediaPackages(processCids, uidArr, externalStorage);
15896            startCleaningPackages();
15897            mInstallerService.onSecureContainersAvailable();
15898        } else {
15899            if (DEBUG_SD_INSTALL)
15900                Log.i(TAG, "Unloading packages");
15901            unloadMediaPackages(processCids, uidArr, reportStatus);
15902        }
15903    }
15904
15905    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15906            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15907        final int size = infos.size();
15908        final String[] packageNames = new String[size];
15909        final int[] packageUids = new int[size];
15910        for (int i = 0; i < size; i++) {
15911            final ApplicationInfo info = infos.get(i);
15912            packageNames[i] = info.packageName;
15913            packageUids[i] = info.uid;
15914        }
15915        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15916                finishedReceiver);
15917    }
15918
15919    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15920            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15921        sendResourcesChangedBroadcast(mediaStatus, replacing,
15922                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15923    }
15924
15925    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15926            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15927        int size = pkgList.length;
15928        if (size > 0) {
15929            // Send broadcasts here
15930            Bundle extras = new Bundle();
15931            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15932            if (uidArr != null) {
15933                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15934            }
15935            if (replacing) {
15936                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15937            }
15938            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15939                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15940            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
15941        }
15942    }
15943
15944   /*
15945     * Look at potentially valid container ids from processCids If package
15946     * information doesn't match the one on record or package scanning fails,
15947     * the cid is added to list of removeCids. We currently don't delete stale
15948     * containers.
15949     */
15950    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15951            boolean externalStorage) {
15952        ArrayList<String> pkgList = new ArrayList<String>();
15953        Set<AsecInstallArgs> keys = processCids.keySet();
15954
15955        for (AsecInstallArgs args : keys) {
15956            String codePath = processCids.get(args);
15957            if (DEBUG_SD_INSTALL)
15958                Log.i(TAG, "Loading container : " + args.cid);
15959            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15960            try {
15961                // Make sure there are no container errors first.
15962                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15963                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15964                            + " when installing from sdcard");
15965                    continue;
15966                }
15967                // Check code path here.
15968                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15969                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15970                            + " does not match one in settings " + codePath);
15971                    continue;
15972                }
15973                // Parse package
15974                int parseFlags = mDefParseFlags;
15975                if (args.isExternalAsec()) {
15976                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15977                }
15978                if (args.isFwdLocked()) {
15979                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15980                }
15981
15982                synchronized (mInstallLock) {
15983                    PackageParser.Package pkg = null;
15984                    try {
15985                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
15986                    } catch (PackageManagerException e) {
15987                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15988                    }
15989                    // Scan the package
15990                    if (pkg != null) {
15991                        /*
15992                         * TODO why is the lock being held? doPostInstall is
15993                         * called in other places without the lock. This needs
15994                         * to be straightened out.
15995                         */
15996                        // writer
15997                        synchronized (mPackages) {
15998                            retCode = PackageManager.INSTALL_SUCCEEDED;
15999                            pkgList.add(pkg.packageName);
16000                            // Post process args
16001                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16002                                    pkg.applicationInfo.uid);
16003                        }
16004                    } else {
16005                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16006                    }
16007                }
16008
16009            } finally {
16010                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16011                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16012                }
16013            }
16014        }
16015        // writer
16016        synchronized (mPackages) {
16017            // If the platform SDK has changed since the last time we booted,
16018            // we need to re-grant app permission to catch any new ones that
16019            // appear. This is really a hack, and means that apps can in some
16020            // cases get permissions that the user didn't initially explicitly
16021            // allow... it would be nice to have some better way to handle
16022            // this situation.
16023            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16024                    : mSettings.getInternalVersion();
16025            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16026                    : StorageManager.UUID_PRIVATE_INTERNAL;
16027
16028            int updateFlags = UPDATE_PERMISSIONS_ALL;
16029            if (ver.sdkVersion != mSdkVersion) {
16030                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16031                        + mSdkVersion + "; regranting permissions for external");
16032                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16033            }
16034            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16035
16036            // Yay, everything is now upgraded
16037            ver.forceCurrent();
16038
16039            // can downgrade to reader
16040            // Persist settings
16041            mSettings.writeLPr();
16042        }
16043        // Send a broadcast to let everyone know we are done processing
16044        if (pkgList.size() > 0) {
16045            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16046        }
16047    }
16048
16049   /*
16050     * Utility method to unload a list of specified containers
16051     */
16052    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16053        // Just unmount all valid containers.
16054        for (AsecInstallArgs arg : cidArgs) {
16055            synchronized (mInstallLock) {
16056                arg.doPostDeleteLI(false);
16057           }
16058       }
16059   }
16060
16061    /*
16062     * Unload packages mounted on external media. This involves deleting package
16063     * data from internal structures, sending broadcasts about diabled packages,
16064     * gc'ing to free up references, unmounting all secure containers
16065     * corresponding to packages on external media, and posting a
16066     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16067     * that we always have to post this message if status has been requested no
16068     * matter what.
16069     */
16070    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16071            final boolean reportStatus) {
16072        if (DEBUG_SD_INSTALL)
16073            Log.i(TAG, "unloading media packages");
16074        ArrayList<String> pkgList = new ArrayList<String>();
16075        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16076        final Set<AsecInstallArgs> keys = processCids.keySet();
16077        for (AsecInstallArgs args : keys) {
16078            String pkgName = args.getPackageName();
16079            if (DEBUG_SD_INSTALL)
16080                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16081            // Delete package internally
16082            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16083            synchronized (mInstallLock) {
16084                boolean res = deletePackageLI(pkgName, null, false, null, null,
16085                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16086                if (res) {
16087                    pkgList.add(pkgName);
16088                } else {
16089                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16090                    failedList.add(args);
16091                }
16092            }
16093        }
16094
16095        // reader
16096        synchronized (mPackages) {
16097            // We didn't update the settings after removing each package;
16098            // write them now for all packages.
16099            mSettings.writeLPr();
16100        }
16101
16102        // We have to absolutely send UPDATED_MEDIA_STATUS only
16103        // after confirming that all the receivers processed the ordered
16104        // broadcast when packages get disabled, force a gc to clean things up.
16105        // and unload all the containers.
16106        if (pkgList.size() > 0) {
16107            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16108                    new IIntentReceiver.Stub() {
16109                public void performReceive(Intent intent, int resultCode, String data,
16110                        Bundle extras, boolean ordered, boolean sticky,
16111                        int sendingUser) throws RemoteException {
16112                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16113                            reportStatus ? 1 : 0, 1, keys);
16114                    mHandler.sendMessage(msg);
16115                }
16116            });
16117        } else {
16118            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16119                    keys);
16120            mHandler.sendMessage(msg);
16121        }
16122    }
16123
16124    private void loadPrivatePackages(final VolumeInfo vol) {
16125        mHandler.post(new Runnable() {
16126            @Override
16127            public void run() {
16128                loadPrivatePackagesInner(vol);
16129            }
16130        });
16131    }
16132
16133    private void loadPrivatePackagesInner(VolumeInfo vol) {
16134        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16135        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16136
16137        final VersionInfo ver;
16138        final List<PackageSetting> packages;
16139        synchronized (mPackages) {
16140            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16141            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16142        }
16143
16144        for (PackageSetting ps : packages) {
16145            synchronized (mInstallLock) {
16146                final PackageParser.Package pkg;
16147                try {
16148                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16149                    loaded.add(pkg.applicationInfo);
16150                } catch (PackageManagerException e) {
16151                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16152                }
16153
16154                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16155                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16156                }
16157            }
16158        }
16159
16160        synchronized (mPackages) {
16161            int updateFlags = UPDATE_PERMISSIONS_ALL;
16162            if (ver.sdkVersion != mSdkVersion) {
16163                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16164                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16165                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16166            }
16167            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16168
16169            // Yay, everything is now upgraded
16170            ver.forceCurrent();
16171
16172            mSettings.writeLPr();
16173        }
16174
16175        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16176        sendResourcesChangedBroadcast(true, false, loaded, null);
16177    }
16178
16179    private void unloadPrivatePackages(final VolumeInfo vol) {
16180        mHandler.post(new Runnable() {
16181            @Override
16182            public void run() {
16183                unloadPrivatePackagesInner(vol);
16184            }
16185        });
16186    }
16187
16188    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16189        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16190        synchronized (mInstallLock) {
16191        synchronized (mPackages) {
16192            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16193            for (PackageSetting ps : packages) {
16194                if (ps.pkg == null) continue;
16195
16196                final ApplicationInfo info = ps.pkg.applicationInfo;
16197                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16198                if (deletePackageLI(ps.name, null, false, null, null,
16199                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16200                    unloaded.add(info);
16201                } else {
16202                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16203                }
16204            }
16205
16206            mSettings.writeLPr();
16207        }
16208        }
16209
16210        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16211        sendResourcesChangedBroadcast(false, false, unloaded, null);
16212    }
16213
16214    /**
16215     * Examine all users present on given mounted volume, and destroy data
16216     * belonging to users that are no longer valid, or whose user ID has been
16217     * recycled.
16218     */
16219    private void reconcileUsers(String volumeUuid) {
16220        final File[] files = FileUtils
16221                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16222        for (File file : files) {
16223            if (!file.isDirectory()) continue;
16224
16225            final int userId;
16226            final UserInfo info;
16227            try {
16228                userId = Integer.parseInt(file.getName());
16229                info = sUserManager.getUserInfo(userId);
16230            } catch (NumberFormatException e) {
16231                Slog.w(TAG, "Invalid user directory " + file);
16232                continue;
16233            }
16234
16235            boolean destroyUser = false;
16236            if (info == null) {
16237                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16238                        + " because no matching user was found");
16239                destroyUser = true;
16240            } else {
16241                try {
16242                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16243                } catch (IOException e) {
16244                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16245                            + " because we failed to enforce serial number: " + e);
16246                    destroyUser = true;
16247                }
16248            }
16249
16250            if (destroyUser) {
16251                synchronized (mInstallLock) {
16252                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16253                }
16254            }
16255        }
16256
16257        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16258        final UserManager um = mContext.getSystemService(UserManager.class);
16259        for (UserInfo user : um.getUsers()) {
16260            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16261            if (userDir.exists()) continue;
16262
16263            try {
16264                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber);
16265                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16266            } catch (IOException e) {
16267                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16268            }
16269        }
16270    }
16271
16272    /**
16273     * Examine all apps present on given mounted volume, and destroy apps that
16274     * aren't expected, either due to uninstallation or reinstallation on
16275     * another volume.
16276     */
16277    private void reconcileApps(String volumeUuid) {
16278        final File[] files = FileUtils
16279                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16280        for (File file : files) {
16281            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16282                    && !PackageInstallerService.isStageName(file.getName());
16283            if (!isPackage) {
16284                // Ignore entries which are not packages
16285                continue;
16286            }
16287
16288            boolean destroyApp = false;
16289            String packageName = null;
16290            try {
16291                final PackageLite pkg = PackageParser.parsePackageLite(file,
16292                        PackageParser.PARSE_MUST_BE_APK);
16293                packageName = pkg.packageName;
16294
16295                synchronized (mPackages) {
16296                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16297                    if (ps == null) {
16298                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16299                                + volumeUuid + " because we found no install record");
16300                        destroyApp = true;
16301                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16302                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16303                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16304                        destroyApp = true;
16305                    }
16306                }
16307
16308            } catch (PackageParserException e) {
16309                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16310                destroyApp = true;
16311            }
16312
16313            if (destroyApp) {
16314                synchronized (mInstallLock) {
16315                    if (packageName != null) {
16316                        removeDataDirsLI(volumeUuid, packageName);
16317                    }
16318                    if (file.isDirectory()) {
16319                        mInstaller.rmPackageDir(file.getAbsolutePath());
16320                    } else {
16321                        file.delete();
16322                    }
16323                }
16324            }
16325        }
16326    }
16327
16328    private void unfreezePackage(String packageName) {
16329        synchronized (mPackages) {
16330            final PackageSetting ps = mSettings.mPackages.get(packageName);
16331            if (ps != null) {
16332                ps.frozen = false;
16333            }
16334        }
16335    }
16336
16337    @Override
16338    public int movePackage(final String packageName, final String volumeUuid) {
16339        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16340
16341        final int moveId = mNextMoveId.getAndIncrement();
16342        mHandler.post(new Runnable() {
16343            @Override
16344            public void run() {
16345                try {
16346                    movePackageInternal(packageName, volumeUuid, moveId);
16347                } catch (PackageManagerException e) {
16348                    Slog.w(TAG, "Failed to move " + packageName, e);
16349                    mMoveCallbacks.notifyStatusChanged(moveId,
16350                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16351                }
16352            }
16353        });
16354        return moveId;
16355    }
16356
16357    private void movePackageInternal(final String packageName, final String volumeUuid,
16358            final int moveId) throws PackageManagerException {
16359        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16360        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16361        final PackageManager pm = mContext.getPackageManager();
16362
16363        final boolean currentAsec;
16364        final String currentVolumeUuid;
16365        final File codeFile;
16366        final String installerPackageName;
16367        final String packageAbiOverride;
16368        final int appId;
16369        final String seinfo;
16370        final String label;
16371
16372        // reader
16373        synchronized (mPackages) {
16374            final PackageParser.Package pkg = mPackages.get(packageName);
16375            final PackageSetting ps = mSettings.mPackages.get(packageName);
16376            if (pkg == null || ps == null) {
16377                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16378            }
16379
16380            if (pkg.applicationInfo.isSystemApp()) {
16381                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16382                        "Cannot move system application");
16383            }
16384
16385            if (pkg.applicationInfo.isExternalAsec()) {
16386                currentAsec = true;
16387                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16388            } else if (pkg.applicationInfo.isForwardLocked()) {
16389                currentAsec = true;
16390                currentVolumeUuid = "forward_locked";
16391            } else {
16392                currentAsec = false;
16393                currentVolumeUuid = ps.volumeUuid;
16394
16395                final File probe = new File(pkg.codePath);
16396                final File probeOat = new File(probe, "oat");
16397                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16398                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16399                            "Move only supported for modern cluster style installs");
16400                }
16401            }
16402
16403            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16404                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16405                        "Package already moved to " + volumeUuid);
16406            }
16407
16408            if (ps.frozen) {
16409                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16410                        "Failed to move already frozen package");
16411            }
16412            ps.frozen = true;
16413
16414            codeFile = new File(pkg.codePath);
16415            installerPackageName = ps.installerPackageName;
16416            packageAbiOverride = ps.cpuAbiOverrideString;
16417            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16418            seinfo = pkg.applicationInfo.seinfo;
16419            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16420        }
16421
16422        // Now that we're guarded by frozen state, kill app during move
16423        final long token = Binder.clearCallingIdentity();
16424        try {
16425            killApplication(packageName, appId, "move pkg");
16426        } finally {
16427            Binder.restoreCallingIdentity(token);
16428        }
16429
16430        final Bundle extras = new Bundle();
16431        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16432        extras.putString(Intent.EXTRA_TITLE, label);
16433        mMoveCallbacks.notifyCreated(moveId, extras);
16434
16435        int installFlags;
16436        final boolean moveCompleteApp;
16437        final File measurePath;
16438
16439        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16440            installFlags = INSTALL_INTERNAL;
16441            moveCompleteApp = !currentAsec;
16442            measurePath = Environment.getDataAppDirectory(volumeUuid);
16443        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16444            installFlags = INSTALL_EXTERNAL;
16445            moveCompleteApp = false;
16446            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16447        } else {
16448            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16449            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16450                    || !volume.isMountedWritable()) {
16451                unfreezePackage(packageName);
16452                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16453                        "Move location not mounted private volume");
16454            }
16455
16456            Preconditions.checkState(!currentAsec);
16457
16458            installFlags = INSTALL_INTERNAL;
16459            moveCompleteApp = true;
16460            measurePath = Environment.getDataAppDirectory(volumeUuid);
16461        }
16462
16463        final PackageStats stats = new PackageStats(null, -1);
16464        synchronized (mInstaller) {
16465            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16466                unfreezePackage(packageName);
16467                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16468                        "Failed to measure package size");
16469            }
16470        }
16471
16472        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16473                + stats.dataSize);
16474
16475        final long startFreeBytes = measurePath.getFreeSpace();
16476        final long sizeBytes;
16477        if (moveCompleteApp) {
16478            sizeBytes = stats.codeSize + stats.dataSize;
16479        } else {
16480            sizeBytes = stats.codeSize;
16481        }
16482
16483        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16484            unfreezePackage(packageName);
16485            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16486                    "Not enough free space to move");
16487        }
16488
16489        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16490
16491        final CountDownLatch installedLatch = new CountDownLatch(1);
16492        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16493            @Override
16494            public void onUserActionRequired(Intent intent) throws RemoteException {
16495                throw new IllegalStateException();
16496            }
16497
16498            @Override
16499            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16500                    Bundle extras) throws RemoteException {
16501                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16502                        + PackageManager.installStatusToString(returnCode, msg));
16503
16504                installedLatch.countDown();
16505
16506                // Regardless of success or failure of the move operation,
16507                // always unfreeze the package
16508                unfreezePackage(packageName);
16509
16510                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16511                switch (status) {
16512                    case PackageInstaller.STATUS_SUCCESS:
16513                        mMoveCallbacks.notifyStatusChanged(moveId,
16514                                PackageManager.MOVE_SUCCEEDED);
16515                        break;
16516                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16517                        mMoveCallbacks.notifyStatusChanged(moveId,
16518                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16519                        break;
16520                    default:
16521                        mMoveCallbacks.notifyStatusChanged(moveId,
16522                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16523                        break;
16524                }
16525            }
16526        };
16527
16528        final MoveInfo move;
16529        if (moveCompleteApp) {
16530            // Kick off a thread to report progress estimates
16531            new Thread() {
16532                @Override
16533                public void run() {
16534                    while (true) {
16535                        try {
16536                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16537                                break;
16538                            }
16539                        } catch (InterruptedException ignored) {
16540                        }
16541
16542                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16543                        final int progress = 10 + (int) MathUtils.constrain(
16544                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16545                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16546                    }
16547                }
16548            }.start();
16549
16550            final String dataAppName = codeFile.getName();
16551            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16552                    dataAppName, appId, seinfo);
16553        } else {
16554            move = null;
16555        }
16556
16557        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16558
16559        final Message msg = mHandler.obtainMessage(INIT_COPY);
16560        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16561        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16562                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16563        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16564        msg.obj = params;
16565
16566        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16567                System.identityHashCode(msg.obj));
16568        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16569                System.identityHashCode(msg.obj));
16570
16571        mHandler.sendMessage(msg);
16572    }
16573
16574    @Override
16575    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16576        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16577
16578        final int realMoveId = mNextMoveId.getAndIncrement();
16579        final Bundle extras = new Bundle();
16580        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16581        mMoveCallbacks.notifyCreated(realMoveId, extras);
16582
16583        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16584            @Override
16585            public void onCreated(int moveId, Bundle extras) {
16586                // Ignored
16587            }
16588
16589            @Override
16590            public void onStatusChanged(int moveId, int status, long estMillis) {
16591                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16592            }
16593        };
16594
16595        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16596        storage.setPrimaryStorageUuid(volumeUuid, callback);
16597        return realMoveId;
16598    }
16599
16600    @Override
16601    public int getMoveStatus(int moveId) {
16602        mContext.enforceCallingOrSelfPermission(
16603                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16604        return mMoveCallbacks.mLastStatus.get(moveId);
16605    }
16606
16607    @Override
16608    public void registerMoveCallback(IPackageMoveObserver callback) {
16609        mContext.enforceCallingOrSelfPermission(
16610                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16611        mMoveCallbacks.register(callback);
16612    }
16613
16614    @Override
16615    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16616        mContext.enforceCallingOrSelfPermission(
16617                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16618        mMoveCallbacks.unregister(callback);
16619    }
16620
16621    @Override
16622    public boolean setInstallLocation(int loc) {
16623        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16624                null);
16625        if (getInstallLocation() == loc) {
16626            return true;
16627        }
16628        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16629                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16630            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16631                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16632            return true;
16633        }
16634        return false;
16635   }
16636
16637    @Override
16638    public int getInstallLocation() {
16639        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16640                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16641                PackageHelper.APP_INSTALL_AUTO);
16642    }
16643
16644    /** Called by UserManagerService */
16645    void cleanUpUser(UserManagerService userManager, int userHandle) {
16646        synchronized (mPackages) {
16647            mDirtyUsers.remove(userHandle);
16648            mUserNeedsBadging.delete(userHandle);
16649            mSettings.removeUserLPw(userHandle);
16650            mPendingBroadcasts.remove(userHandle);
16651        }
16652        synchronized (mInstallLock) {
16653            if (mInstaller != null) {
16654                final StorageManager storage = mContext.getSystemService(StorageManager.class);
16655                for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16656                    final String volumeUuid = vol.getFsUuid();
16657                    if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16658                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16659                }
16660            }
16661            synchronized (mPackages) {
16662                removeUnusedPackagesLILPw(userManager, userHandle);
16663            }
16664        }
16665    }
16666
16667    /**
16668     * We're removing userHandle and would like to remove any downloaded packages
16669     * that are no longer in use by any other user.
16670     * @param userHandle the user being removed
16671     */
16672    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16673        final boolean DEBUG_CLEAN_APKS = false;
16674        int [] users = userManager.getUserIds();
16675        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16676        while (psit.hasNext()) {
16677            PackageSetting ps = psit.next();
16678            if (ps.pkg == null) {
16679                continue;
16680            }
16681            final String packageName = ps.pkg.packageName;
16682            // Skip over if system app
16683            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16684                continue;
16685            }
16686            if (DEBUG_CLEAN_APKS) {
16687                Slog.i(TAG, "Checking package " + packageName);
16688            }
16689            boolean keep = false;
16690            for (int i = 0; i < users.length; i++) {
16691                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16692                    keep = true;
16693                    if (DEBUG_CLEAN_APKS) {
16694                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16695                                + users[i]);
16696                    }
16697                    break;
16698                }
16699            }
16700            if (!keep) {
16701                if (DEBUG_CLEAN_APKS) {
16702                    Slog.i(TAG, "  Removing package " + packageName);
16703                }
16704                mHandler.post(new Runnable() {
16705                    public void run() {
16706                        deletePackageX(packageName, userHandle, 0);
16707                    } //end run
16708                });
16709            }
16710        }
16711    }
16712
16713    /** Called by UserManagerService */
16714    void createNewUser(int userHandle) {
16715        if (mInstaller != null) {
16716            synchronized (mInstallLock) {
16717                synchronized (mPackages) {
16718                    mInstaller.createUserConfig(userHandle);
16719                    mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16720                }
16721            }
16722            synchronized (mPackages) {
16723                applyFactoryDefaultBrowserLPw(userHandle);
16724                primeDomainVerificationsLPw(userHandle);
16725            }
16726        }
16727    }
16728
16729    void newUserCreated(final int userHandle) {
16730        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16731    }
16732
16733    @Override
16734    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16735        mContext.enforceCallingOrSelfPermission(
16736                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16737                "Only package verification agents can read the verifier device identity");
16738
16739        synchronized (mPackages) {
16740            return mSettings.getVerifierDeviceIdentityLPw();
16741        }
16742    }
16743
16744    @Override
16745    public void setPermissionEnforced(String permission, boolean enforced) {
16746        // TODO: Now that we no longer change GID for storage, this should to away.
16747        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16748                "setPermissionEnforced");
16749        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16750            synchronized (mPackages) {
16751                if (mSettings.mReadExternalStorageEnforced == null
16752                        || mSettings.mReadExternalStorageEnforced != enforced) {
16753                    mSettings.mReadExternalStorageEnforced = enforced;
16754                    mSettings.writeLPr();
16755                }
16756            }
16757            // kill any non-foreground processes so we restart them and
16758            // grant/revoke the GID.
16759            final IActivityManager am = ActivityManagerNative.getDefault();
16760            if (am != null) {
16761                final long token = Binder.clearCallingIdentity();
16762                try {
16763                    am.killProcessesBelowForeground("setPermissionEnforcement");
16764                } catch (RemoteException e) {
16765                } finally {
16766                    Binder.restoreCallingIdentity(token);
16767                }
16768            }
16769        } else {
16770            throw new IllegalArgumentException("No selective enforcement for " + permission);
16771        }
16772    }
16773
16774    @Override
16775    @Deprecated
16776    public boolean isPermissionEnforced(String permission) {
16777        return true;
16778    }
16779
16780    @Override
16781    public boolean isStorageLow() {
16782        final long token = Binder.clearCallingIdentity();
16783        try {
16784            final DeviceStorageMonitorInternal
16785                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16786            if (dsm != null) {
16787                return dsm.isMemoryLow();
16788            } else {
16789                return false;
16790            }
16791        } finally {
16792            Binder.restoreCallingIdentity(token);
16793        }
16794    }
16795
16796    @Override
16797    public IPackageInstaller getPackageInstaller() {
16798        return mInstallerService;
16799    }
16800
16801    private boolean userNeedsBadging(int userId) {
16802        int index = mUserNeedsBadging.indexOfKey(userId);
16803        if (index < 0) {
16804            final UserInfo userInfo;
16805            final long token = Binder.clearCallingIdentity();
16806            try {
16807                userInfo = sUserManager.getUserInfo(userId);
16808            } finally {
16809                Binder.restoreCallingIdentity(token);
16810            }
16811            final boolean b;
16812            if (userInfo != null && userInfo.isManagedProfile()) {
16813                b = true;
16814            } else {
16815                b = false;
16816            }
16817            mUserNeedsBadging.put(userId, b);
16818            return b;
16819        }
16820        return mUserNeedsBadging.valueAt(index);
16821    }
16822
16823    @Override
16824    public KeySet getKeySetByAlias(String packageName, String alias) {
16825        if (packageName == null || alias == null) {
16826            return null;
16827        }
16828        synchronized(mPackages) {
16829            final PackageParser.Package pkg = mPackages.get(packageName);
16830            if (pkg == null) {
16831                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16832                throw new IllegalArgumentException("Unknown package: " + packageName);
16833            }
16834            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16835            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16836        }
16837    }
16838
16839    @Override
16840    public KeySet getSigningKeySet(String packageName) {
16841        if (packageName == null) {
16842            return null;
16843        }
16844        synchronized(mPackages) {
16845            final PackageParser.Package pkg = mPackages.get(packageName);
16846            if (pkg == null) {
16847                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16848                throw new IllegalArgumentException("Unknown package: " + packageName);
16849            }
16850            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16851                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16852                throw new SecurityException("May not access signing KeySet of other apps.");
16853            }
16854            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16855            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16856        }
16857    }
16858
16859    @Override
16860    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16861        if (packageName == null || ks == null) {
16862            return false;
16863        }
16864        synchronized(mPackages) {
16865            final PackageParser.Package pkg = mPackages.get(packageName);
16866            if (pkg == null) {
16867                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16868                throw new IllegalArgumentException("Unknown package: " + packageName);
16869            }
16870            IBinder ksh = ks.getToken();
16871            if (ksh instanceof KeySetHandle) {
16872                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16873                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16874            }
16875            return false;
16876        }
16877    }
16878
16879    @Override
16880    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16881        if (packageName == null || ks == null) {
16882            return false;
16883        }
16884        synchronized(mPackages) {
16885            final PackageParser.Package pkg = mPackages.get(packageName);
16886            if (pkg == null) {
16887                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16888                throw new IllegalArgumentException("Unknown package: " + packageName);
16889            }
16890            IBinder ksh = ks.getToken();
16891            if (ksh instanceof KeySetHandle) {
16892                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16893                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16894            }
16895            return false;
16896        }
16897    }
16898
16899    /**
16900     * Check and throw if the given before/after packages would be considered a
16901     * downgrade.
16902     */
16903    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16904            throws PackageManagerException {
16905        if (after.versionCode < before.mVersionCode) {
16906            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16907                    "Update version code " + after.versionCode + " is older than current "
16908                    + before.mVersionCode);
16909        } else if (after.versionCode == before.mVersionCode) {
16910            if (after.baseRevisionCode < before.baseRevisionCode) {
16911                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16912                        "Update base revision code " + after.baseRevisionCode
16913                        + " is older than current " + before.baseRevisionCode);
16914            }
16915
16916            if (!ArrayUtils.isEmpty(after.splitNames)) {
16917                for (int i = 0; i < after.splitNames.length; i++) {
16918                    final String splitName = after.splitNames[i];
16919                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16920                    if (j != -1) {
16921                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16922                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16923                                    "Update split " + splitName + " revision code "
16924                                    + after.splitRevisionCodes[i] + " is older than current "
16925                                    + before.splitRevisionCodes[j]);
16926                        }
16927                    }
16928                }
16929            }
16930        }
16931    }
16932
16933    private static class MoveCallbacks extends Handler {
16934        private static final int MSG_CREATED = 1;
16935        private static final int MSG_STATUS_CHANGED = 2;
16936
16937        private final RemoteCallbackList<IPackageMoveObserver>
16938                mCallbacks = new RemoteCallbackList<>();
16939
16940        private final SparseIntArray mLastStatus = new SparseIntArray();
16941
16942        public MoveCallbacks(Looper looper) {
16943            super(looper);
16944        }
16945
16946        public void register(IPackageMoveObserver callback) {
16947            mCallbacks.register(callback);
16948        }
16949
16950        public void unregister(IPackageMoveObserver callback) {
16951            mCallbacks.unregister(callback);
16952        }
16953
16954        @Override
16955        public void handleMessage(Message msg) {
16956            final SomeArgs args = (SomeArgs) msg.obj;
16957            final int n = mCallbacks.beginBroadcast();
16958            for (int i = 0; i < n; i++) {
16959                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16960                try {
16961                    invokeCallback(callback, msg.what, args);
16962                } catch (RemoteException ignored) {
16963                }
16964            }
16965            mCallbacks.finishBroadcast();
16966            args.recycle();
16967        }
16968
16969        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16970                throws RemoteException {
16971            switch (what) {
16972                case MSG_CREATED: {
16973                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16974                    break;
16975                }
16976                case MSG_STATUS_CHANGED: {
16977                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16978                    break;
16979                }
16980            }
16981        }
16982
16983        private void notifyCreated(int moveId, Bundle extras) {
16984            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16985
16986            final SomeArgs args = SomeArgs.obtain();
16987            args.argi1 = moveId;
16988            args.arg2 = extras;
16989            obtainMessage(MSG_CREATED, args).sendToTarget();
16990        }
16991
16992        private void notifyStatusChanged(int moveId, int status) {
16993            notifyStatusChanged(moveId, status, -1);
16994        }
16995
16996        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16997            Slog.v(TAG, "Move " + moveId + " status " + status);
16998
16999            final SomeArgs args = SomeArgs.obtain();
17000            args.argi1 = moveId;
17001            args.argi2 = status;
17002            args.arg3 = estMillis;
17003            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17004
17005            synchronized (mLastStatus) {
17006                mLastStatus.put(moveId, status);
17007            }
17008        }
17009    }
17010
17011    private final class OnPermissionChangeListeners extends Handler {
17012        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17013
17014        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17015                new RemoteCallbackList<>();
17016
17017        public OnPermissionChangeListeners(Looper looper) {
17018            super(looper);
17019        }
17020
17021        @Override
17022        public void handleMessage(Message msg) {
17023            switch (msg.what) {
17024                case MSG_ON_PERMISSIONS_CHANGED: {
17025                    final int uid = msg.arg1;
17026                    handleOnPermissionsChanged(uid);
17027                } break;
17028            }
17029        }
17030
17031        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17032            mPermissionListeners.register(listener);
17033
17034        }
17035
17036        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17037            mPermissionListeners.unregister(listener);
17038        }
17039
17040        public void onPermissionsChanged(int uid) {
17041            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17042                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17043            }
17044        }
17045
17046        private void handleOnPermissionsChanged(int uid) {
17047            final int count = mPermissionListeners.beginBroadcast();
17048            try {
17049                for (int i = 0; i < count; i++) {
17050                    IOnPermissionsChangeListener callback = mPermissionListeners
17051                            .getBroadcastItem(i);
17052                    try {
17053                        callback.onPermissionsChanged(uid);
17054                    } catch (RemoteException e) {
17055                        Log.e(TAG, "Permission listener is dead", e);
17056                    }
17057                }
17058            } finally {
17059                mPermissionListeners.finishBroadcast();
17060            }
17061        }
17062    }
17063
17064    private class PackageManagerInternalImpl extends PackageManagerInternal {
17065        @Override
17066        public void setLocationPackagesProvider(PackagesProvider provider) {
17067            synchronized (mPackages) {
17068                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17069            }
17070        }
17071
17072        @Override
17073        public void setImePackagesProvider(PackagesProvider provider) {
17074            synchronized (mPackages) {
17075                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17076            }
17077        }
17078
17079        @Override
17080        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17081            synchronized (mPackages) {
17082                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17083            }
17084        }
17085
17086        @Override
17087        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17088            synchronized (mPackages) {
17089                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17090            }
17091        }
17092
17093        @Override
17094        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17095            synchronized (mPackages) {
17096                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17097            }
17098        }
17099
17100        @Override
17101        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17102            synchronized (mPackages) {
17103                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17104            }
17105        }
17106
17107        @Override
17108        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17109            synchronized (mPackages) {
17110                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17111            }
17112        }
17113
17114        @Override
17115        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17116            synchronized (mPackages) {
17117                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17118                        packageName, userId);
17119            }
17120        }
17121
17122        @Override
17123        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17124            synchronized (mPackages) {
17125                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17126                        packageName, userId);
17127            }
17128        }
17129        @Override
17130        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17131            synchronized (mPackages) {
17132                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17133                        packageName, userId);
17134            }
17135        }
17136    }
17137
17138    @Override
17139    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17140        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17141        synchronized (mPackages) {
17142            final long identity = Binder.clearCallingIdentity();
17143            try {
17144                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17145                        packageNames, userId);
17146            } finally {
17147                Binder.restoreCallingIdentity(identity);
17148            }
17149        }
17150    }
17151
17152    private static void enforceSystemOrPhoneCaller(String tag) {
17153        int callingUid = Binder.getCallingUid();
17154        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17155            throw new SecurityException(
17156                    "Cannot call " + tag + " from UID " + callingUid);
17157        }
17158    }
17159}
17160