PackageManagerService.java revision 12705131b95d5d6bcfae79d7991ff3e6f02457e4
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_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
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_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
71import static android.content.pm.PackageManager.PERMISSION_DENIED;
72import static android.content.pm.PackageManager.PERMISSION_GRANTED;
73import static android.content.pm.PackageParser.isApkFile;
74import static android.os.Process.PACKAGE_INFO_GID;
75import static android.os.Process.SYSTEM_UID;
76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
77import static android.system.OsConstants.O_CREAT;
78import static android.system.OsConstants.O_RDWR;
79
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
84import static com.android.internal.util.ArrayUtils.appendInt;
85import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
94
95import android.Manifest;
96import android.annotation.NonNull;
97import android.annotation.Nullable;
98import android.app.ActivityManager;
99import android.app.ActivityManagerNative;
100import android.app.AppGlobals;
101import android.app.IActivityManager;
102import android.app.admin.IDevicePolicyManager;
103import android.app.backup.IBackupManager;
104import android.content.BroadcastReceiver;
105import android.content.ComponentName;
106import android.content.Context;
107import android.content.IIntentReceiver;
108import android.content.Intent;
109import android.content.IntentFilter;
110import android.content.IntentSender;
111import android.content.IntentSender.SendIntentException;
112import android.content.ServiceConnection;
113import android.content.pm.ActivityInfo;
114import android.content.pm.ApplicationInfo;
115import android.content.pm.AppsQueryHelper;
116import android.content.pm.ComponentInfo;
117import android.content.pm.EphemeralApplicationInfo;
118import android.content.pm.EphemeralResolveInfo;
119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
120import android.content.pm.FeatureInfo;
121import android.content.pm.IOnPermissionsChangeListener;
122import android.content.pm.IPackageDataObserver;
123import android.content.pm.IPackageDeleteObserver;
124import android.content.pm.IPackageDeleteObserver2;
125import android.content.pm.IPackageInstallObserver2;
126import android.content.pm.IPackageInstaller;
127import android.content.pm.IPackageManager;
128import android.content.pm.IPackageMoveObserver;
129import android.content.pm.IPackageStatsObserver;
130import android.content.pm.InstrumentationInfo;
131import android.content.pm.IntentFilterVerificationInfo;
132import android.content.pm.KeySet;
133import android.content.pm.PackageCleanItem;
134import android.content.pm.PackageInfo;
135import android.content.pm.PackageInfoLite;
136import android.content.pm.PackageInstaller;
137import android.content.pm.PackageManager;
138import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
139import android.content.pm.PackageManagerInternal;
140import android.content.pm.PackageParser;
141import android.content.pm.PackageParser.ActivityIntentInfo;
142import android.content.pm.PackageParser.PackageLite;
143import android.content.pm.PackageParser.PackageParserException;
144import android.content.pm.PackageStats;
145import android.content.pm.PackageUserState;
146import android.content.pm.ParceledListSlice;
147import android.content.pm.PermissionGroupInfo;
148import android.content.pm.PermissionInfo;
149import android.content.pm.ProviderInfo;
150import android.content.pm.ResolveInfo;
151import android.content.pm.ServiceInfo;
152import android.content.pm.Signature;
153import android.content.pm.UserInfo;
154import android.content.pm.VerificationParams;
155import android.content.pm.VerifierDeviceIdentity;
156import android.content.pm.VerifierInfo;
157import android.content.res.Resources;
158import android.graphics.Bitmap;
159import android.hardware.display.DisplayManager;
160import android.net.Uri;
161import android.os.Binder;
162import android.os.Build;
163import android.os.Bundle;
164import android.os.Debug;
165import android.os.Environment;
166import android.os.Environment.UserEnvironment;
167import android.os.FileUtils;
168import android.os.Handler;
169import android.os.IBinder;
170import android.os.Looper;
171import android.os.Message;
172import android.os.Parcel;
173import android.os.ParcelFileDescriptor;
174import android.os.Process;
175import android.os.RemoteCallbackList;
176import android.os.RemoteException;
177import android.os.ResultReceiver;
178import android.os.SELinux;
179import android.os.ServiceManager;
180import android.os.SystemClock;
181import android.os.SystemProperties;
182import android.os.Trace;
183import android.os.UserHandle;
184import android.os.UserManager;
185import android.os.storage.IMountService;
186import android.os.storage.MountServiceInternal;
187import android.os.storage.StorageEventListener;
188import android.os.storage.StorageManager;
189import android.os.storage.VolumeInfo;
190import android.os.storage.VolumeRecord;
191import android.security.KeyStore;
192import android.security.SystemKeyStore;
193import android.system.ErrnoException;
194import android.system.Os;
195import android.system.StructStat;
196import android.text.TextUtils;
197import android.text.format.DateUtils;
198import android.util.ArrayMap;
199import android.util.ArraySet;
200import android.util.AtomicFile;
201import android.util.DisplayMetrics;
202import android.util.EventLog;
203import android.util.ExceptionUtils;
204import android.util.Log;
205import android.util.LogPrinter;
206import android.util.MathUtils;
207import android.util.PrintStreamPrinter;
208import android.util.Slog;
209import android.util.SparseArray;
210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
212import android.util.Xml;
213import android.view.Display;
214
215import com.android.internal.R;
216import com.android.internal.annotations.GuardedBy;
217import com.android.internal.app.IMediaContainerService;
218import com.android.internal.app.ResolverActivity;
219import com.android.internal.content.NativeLibraryHelper;
220import com.android.internal.content.PackageHelper;
221import com.android.internal.os.IParcelFileDescriptorFactory;
222import com.android.internal.os.SomeArgs;
223import com.android.internal.os.Zygote;
224import com.android.internal.util.ArrayUtils;
225import com.android.internal.util.FastPrintWriter;
226import com.android.internal.util.FastXmlSerializer;
227import com.android.internal.util.IndentingPrintWriter;
228import com.android.internal.util.Preconditions;
229import com.android.server.EventLogTags;
230import com.android.server.FgThread;
231import com.android.server.IntentResolver;
232import com.android.server.LocalServices;
233import com.android.server.ServiceThread;
234import com.android.server.SystemConfig;
235import com.android.server.Watchdog;
236import com.android.server.pm.PermissionsState.PermissionState;
237import com.android.server.pm.Settings.DatabaseVersion;
238import com.android.server.pm.Settings.VersionInfo;
239import com.android.server.storage.DeviceStorageMonitorInternal;
240
241import dalvik.system.DexFile;
242import dalvik.system.VMRuntime;
243
244import libcore.io.IoUtils;
245import libcore.util.EmptyArray;
246
247import org.xmlpull.v1.XmlPullParser;
248import org.xmlpull.v1.XmlPullParserException;
249import org.xmlpull.v1.XmlSerializer;
250
251import java.io.BufferedInputStream;
252import java.io.BufferedOutputStream;
253import java.io.BufferedReader;
254import java.io.ByteArrayInputStream;
255import java.io.ByteArrayOutputStream;
256import java.io.File;
257import java.io.FileDescriptor;
258import java.io.FileNotFoundException;
259import java.io.FileOutputStream;
260import java.io.FileReader;
261import java.io.FilenameFilter;
262import java.io.IOException;
263import java.io.InputStream;
264import java.io.PrintWriter;
265import java.nio.charset.StandardCharsets;
266import java.security.MessageDigest;
267import java.security.NoSuchAlgorithmException;
268import java.security.PublicKey;
269import java.security.cert.CertificateEncodingException;
270import java.security.cert.CertificateException;
271import java.text.SimpleDateFormat;
272import java.util.ArrayList;
273import java.util.Arrays;
274import java.util.Collection;
275import java.util.Collections;
276import java.util.Comparator;
277import java.util.Date;
278import java.util.Iterator;
279import java.util.List;
280import java.util.Map;
281import java.util.Objects;
282import java.util.Set;
283import java.util.concurrent.CountDownLatch;
284import java.util.concurrent.TimeUnit;
285import java.util.concurrent.atomic.AtomicBoolean;
286import java.util.concurrent.atomic.AtomicInteger;
287import java.util.concurrent.atomic.AtomicLong;
288
289/**
290 * Keep track of all those .apks everywhere.
291 *
292 * This is very central to the platform's security; please run the unit
293 * tests whenever making modifications here:
294 *
295runtest -c android.content.pm.PackageManagerTests frameworks-core
296 *
297 * {@hide}
298 */
299public class PackageManagerService extends IPackageManager.Stub {
300    static final String TAG = "PackageManager";
301    static final boolean DEBUG_SETTINGS = false;
302    static final boolean DEBUG_PREFERRED = false;
303    static final boolean DEBUG_UPGRADE = false;
304    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
305    private static final boolean DEBUG_BACKUP = false;
306    private static final boolean DEBUG_INSTALL = false;
307    private static final boolean DEBUG_REMOVE = false;
308    private static final boolean DEBUG_BROADCASTS = false;
309    private static final boolean DEBUG_SHOW_INFO = false;
310    private static final boolean DEBUG_PACKAGE_INFO = false;
311    private static final boolean DEBUG_INTENT_MATCHING = false;
312    private static final boolean DEBUG_PACKAGE_SCANNING = false;
313    private static final boolean DEBUG_VERIFY = false;
314    private static final boolean DEBUG_DEXOPT = false;
315    private static final boolean DEBUG_ABI_SELECTION = false;
316    private static final boolean DEBUG_EPHEMERAL = false;
317    private static final boolean DEBUG_TRIAGED_MISSING = false;
318
319    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
320
321    private static final boolean DISABLE_EPHEMERAL_APPS = true;
322
323    private static final int RADIO_UID = Process.PHONE_UID;
324    private static final int LOG_UID = Process.LOG_UID;
325    private static final int NFC_UID = Process.NFC_UID;
326    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
327    private static final int SHELL_UID = Process.SHELL_UID;
328
329    // Cap the size of permission trees that 3rd party apps can define
330    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
331
332    // Suffix used during package installation when copying/moving
333    // package apks to install directory.
334    private static final String INSTALL_PACKAGE_SUFFIX = "-";
335
336    static final int SCAN_NO_DEX = 1<<1;
337    static final int SCAN_FORCE_DEX = 1<<2;
338    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
339    static final int SCAN_NEW_INSTALL = 1<<4;
340    static final int SCAN_NO_PATHS = 1<<5;
341    static final int SCAN_UPDATE_TIME = 1<<6;
342    static final int SCAN_DEFER_DEX = 1<<7;
343    static final int SCAN_BOOTING = 1<<8;
344    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
345    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
346    static final int SCAN_REPLACING = 1<<11;
347    static final int SCAN_REQUIRE_KNOWN = 1<<12;
348    static final int SCAN_MOVE = 1<<13;
349    static final int SCAN_INITIAL = 1<<14;
350
351    static final int REMOVE_CHATTY = 1<<16;
352
353    private static final int[] EMPTY_INT_ARRAY = new int[0];
354
355    /**
356     * Timeout (in milliseconds) after which the watchdog should declare that
357     * our handler thread is wedged.  The usual default for such things is one
358     * minute but we sometimes do very lengthy I/O operations on this thread,
359     * such as installing multi-gigabyte applications, so ours needs to be longer.
360     */
361    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
362
363    /**
364     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
365     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
366     * settings entry if available, otherwise we use the hardcoded default.  If it's been
367     * more than this long since the last fstrim, we force one during the boot sequence.
368     *
369     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
370     * one gets run at the next available charging+idle time.  This final mandatory
371     * no-fstrim check kicks in only of the other scheduling criteria is never met.
372     */
373    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
374
375    /**
376     * Whether verification is enabled by default.
377     */
378    private static final boolean DEFAULT_VERIFY_ENABLE = true;
379
380    /**
381     * The default maximum time to wait for the verification agent to return in
382     * milliseconds.
383     */
384    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
385
386    /**
387     * The default response for package verification timeout.
388     *
389     * This can be either PackageManager.VERIFICATION_ALLOW or
390     * PackageManager.VERIFICATION_REJECT.
391     */
392    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
393
394    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
395
396    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
397            DEFAULT_CONTAINER_PACKAGE,
398            "com.android.defcontainer.DefaultContainerService");
399
400    private static final String KILL_APP_REASON_GIDS_CHANGED =
401            "permission grant or revoke changed gids";
402
403    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
404            "permissions revoked";
405
406    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
407
408    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
409
410    /** Permission grant: not grant the permission. */
411    private static final int GRANT_DENIED = 1;
412
413    /** Permission grant: grant the permission as an install permission. */
414    private static final int GRANT_INSTALL = 2;
415
416    /** Permission grant: grant the permission as a runtime one. */
417    private static final int GRANT_RUNTIME = 3;
418
419    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
420    private static final int GRANT_UPGRADE = 4;
421
422    /** Canonical intent used to identify what counts as a "web browser" app */
423    private static final Intent sBrowserIntent;
424    static {
425        sBrowserIntent = new Intent();
426        sBrowserIntent.setAction(Intent.ACTION_VIEW);
427        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
428        sBrowserIntent.setData(Uri.parse("http:"));
429    }
430
431    final ServiceThread mHandlerThread;
432
433    final PackageHandler mHandler;
434
435    /**
436     * Messages for {@link #mHandler} that need to wait for system ready before
437     * being dispatched.
438     */
439    private ArrayList<Message> mPostSystemReadyMessages;
440
441    final int mSdkVersion = Build.VERSION.SDK_INT;
442
443    final Context mContext;
444    final boolean mFactoryTest;
445    final boolean mOnlyCore;
446    final DisplayMetrics mMetrics;
447    final int mDefParseFlags;
448    final String[] mSeparateProcesses;
449    final boolean mIsUpgrade;
450
451    /** The location for ASEC container files on internal storage. */
452    final String mAsecInternalPath;
453
454    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
455    // LOCK HELD.  Can be called with mInstallLock held.
456    @GuardedBy("mInstallLock")
457    final Installer mInstaller;
458
459    /** Directory where installed third-party apps stored */
460    final File mAppInstallDir;
461    final File mEphemeralInstallDir;
462
463    /**
464     * Directory to which applications installed internally have their
465     * 32 bit native libraries copied.
466     */
467    private File mAppLib32InstallDir;
468
469    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
470    // apps.
471    final File mDrmAppPrivateInstallDir;
472
473    // ----------------------------------------------------------------
474
475    // Lock for state used when installing and doing other long running
476    // operations.  Methods that must be called with this lock held have
477    // the suffix "LI".
478    final Object mInstallLock = new Object();
479
480    // ----------------------------------------------------------------
481
482    // Keys are String (package name), values are Package.  This also serves
483    // as the lock for the global state.  Methods that must be called with
484    // this lock held have the prefix "LP".
485    @GuardedBy("mPackages")
486    final ArrayMap<String, PackageParser.Package> mPackages =
487            new ArrayMap<String, PackageParser.Package>();
488
489    // Tracks available target package names -> overlay package paths.
490    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
491        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
492
493    /**
494     * Tracks new system packages [received in an OTA] that we expect to
495     * find updated user-installed versions. Keys are package name, values
496     * are package location.
497     */
498    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
499
500    /**
501     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
502     */
503    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
504    /**
505     * Whether or not system app permissions should be promoted from install to runtime.
506     */
507    boolean mPromoteSystemApps;
508
509    final Settings mSettings;
510    boolean mRestoredSettings;
511
512    // System configuration read by SystemConfig.
513    final int[] mGlobalGids;
514    final SparseArray<ArraySet<String>> mSystemPermissions;
515    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
516
517    // If mac_permissions.xml was found for seinfo labeling.
518    boolean mFoundPolicyFile;
519
520    // If a recursive restorecon of /data/data/<pkg> is needed.
521    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
522
523    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
524
525    public static final class SharedLibraryEntry {
526        public final String path;
527        public final String apk;
528
529        SharedLibraryEntry(String _path, String _apk) {
530            path = _path;
531            apk = _apk;
532        }
533    }
534
535    // Currently known shared libraries.
536    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
537            new ArrayMap<String, SharedLibraryEntry>();
538
539    // All available activities, for your resolving pleasure.
540    final ActivityIntentResolver mActivities =
541            new ActivityIntentResolver();
542
543    // All available receivers, for your resolving pleasure.
544    final ActivityIntentResolver mReceivers =
545            new ActivityIntentResolver();
546
547    // All available services, for your resolving pleasure.
548    final ServiceIntentResolver mServices = new ServiceIntentResolver();
549
550    // All available providers, for your resolving pleasure.
551    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
552
553    // Mapping from provider base names (first directory in content URI codePath)
554    // to the provider information.
555    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
556            new ArrayMap<String, PackageParser.Provider>();
557
558    // Mapping from instrumentation class names to info about them.
559    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
560            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
561
562    // Mapping from permission names to info about them.
563    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
564            new ArrayMap<String, PackageParser.PermissionGroup>();
565
566    // Packages whose data we have transfered into another package, thus
567    // should no longer exist.
568    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
569
570    // Broadcast actions that are only available to the system.
571    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
572
573    /** List of packages waiting for verification. */
574    final SparseArray<PackageVerificationState> mPendingVerification
575            = new SparseArray<PackageVerificationState>();
576
577    /** Set of packages associated with each app op permission. */
578    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
579
580    final PackageInstallerService mInstallerService;
581
582    private final PackageDexOptimizer mPackageDexOptimizer;
583
584    private AtomicInteger mNextMoveId = new AtomicInteger();
585    private final MoveCallbacks mMoveCallbacks;
586
587    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
588
589    // Cache of users who need badging.
590    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
591
592    /** Token for keys in mPendingVerification. */
593    private int mPendingVerificationToken = 0;
594
595    volatile boolean mSystemReady;
596    volatile boolean mSafeMode;
597    volatile boolean mHasSystemUidErrors;
598
599    ApplicationInfo mAndroidApplication;
600    final ActivityInfo mResolveActivity = new ActivityInfo();
601    final ResolveInfo mResolveInfo = new ResolveInfo();
602    ComponentName mResolveComponentName;
603    PackageParser.Package mPlatformPackage;
604    ComponentName mCustomResolverComponentName;
605
606    boolean mResolverReplaced = false;
607
608    private final @Nullable ComponentName mIntentFilterVerifierComponent;
609    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
610
611    private int mIntentFilterVerificationToken = 0;
612
613    /** Component that knows whether or not an ephemeral application exists */
614    final ComponentName mEphemeralResolverComponent;
615    /** The service connection to the ephemeral resolver */
616    final EphemeralResolverConnection mEphemeralResolverConnection;
617
618    /** Component used to install ephemeral applications */
619    final ComponentName mEphemeralInstallerComponent;
620    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
621    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
622
623    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
624            = new SparseArray<IntentFilterVerificationState>();
625
626    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
627            new DefaultPermissionGrantPolicy(this);
628
629    // List of packages names to keep cached, even if they are uninstalled for all users
630    private List<String> mKeepUninstalledPackages;
631
632    private static class IFVerificationParams {
633        PackageParser.Package pkg;
634        boolean replacing;
635        int userId;
636        int verifierUid;
637
638        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
639                int _userId, int _verifierUid) {
640            pkg = _pkg;
641            replacing = _replacing;
642            userId = _userId;
643            replacing = _replacing;
644            verifierUid = _verifierUid;
645        }
646    }
647
648    private interface IntentFilterVerifier<T extends IntentFilter> {
649        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
650                                               T filter, String packageName);
651        void startVerifications(int userId);
652        void receiveVerificationResponse(int verificationId);
653    }
654
655    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
656        private Context mContext;
657        private ComponentName mIntentFilterVerifierComponent;
658        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
659
660        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
661            mContext = context;
662            mIntentFilterVerifierComponent = verifierComponent;
663        }
664
665        private String getDefaultScheme() {
666            return IntentFilter.SCHEME_HTTPS;
667        }
668
669        @Override
670        public void startVerifications(int userId) {
671            // Launch verifications requests
672            int count = mCurrentIntentFilterVerifications.size();
673            for (int n=0; n<count; n++) {
674                int verificationId = mCurrentIntentFilterVerifications.get(n);
675                final IntentFilterVerificationState ivs =
676                        mIntentFilterVerificationStates.get(verificationId);
677
678                String packageName = ivs.getPackageName();
679
680                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
681                final int filterCount = filters.size();
682                ArraySet<String> domainsSet = new ArraySet<>();
683                for (int m=0; m<filterCount; m++) {
684                    PackageParser.ActivityIntentInfo filter = filters.get(m);
685                    domainsSet.addAll(filter.getHostsList());
686                }
687                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
688                synchronized (mPackages) {
689                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
690                            packageName, domainsList) != null) {
691                        scheduleWriteSettingsLocked();
692                    }
693                }
694                sendVerificationRequest(userId, verificationId, ivs);
695            }
696            mCurrentIntentFilterVerifications.clear();
697        }
698
699        private void sendVerificationRequest(int userId, int verificationId,
700                IntentFilterVerificationState ivs) {
701
702            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
703            verificationIntent.putExtra(
704                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
705                    verificationId);
706            verificationIntent.putExtra(
707                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
708                    getDefaultScheme());
709            verificationIntent.putExtra(
710                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
711                    ivs.getHostsString());
712            verificationIntent.putExtra(
713                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
714                    ivs.getPackageName());
715            verificationIntent.setComponent(mIntentFilterVerifierComponent);
716            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
717
718            UserHandle user = new UserHandle(userId);
719            mContext.sendBroadcastAsUser(verificationIntent, user);
720            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
721                    "Sending IntentFilter verification broadcast");
722        }
723
724        public void receiveVerificationResponse(int verificationId) {
725            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
726
727            final boolean verified = ivs.isVerified();
728
729            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
730            final int count = filters.size();
731            if (DEBUG_DOMAIN_VERIFICATION) {
732                Slog.i(TAG, "Received verification response " + verificationId
733                        + " for " + count + " filters, verified=" + verified);
734            }
735            for (int n=0; n<count; n++) {
736                PackageParser.ActivityIntentInfo filter = filters.get(n);
737                filter.setVerified(verified);
738
739                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
740                        + " verified with result:" + verified + " and hosts:"
741                        + ivs.getHostsString());
742            }
743
744            mIntentFilterVerificationStates.remove(verificationId);
745
746            final String packageName = ivs.getPackageName();
747            IntentFilterVerificationInfo ivi = null;
748
749            synchronized (mPackages) {
750                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
751            }
752            if (ivi == null) {
753                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
754                        + verificationId + " packageName:" + packageName);
755                return;
756            }
757            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
758                    "Updating IntentFilterVerificationInfo for package " + packageName
759                            +" verificationId:" + verificationId);
760
761            synchronized (mPackages) {
762                if (verified) {
763                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
764                } else {
765                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
766                }
767                scheduleWriteSettingsLocked();
768
769                final int userId = ivs.getUserId();
770                if (userId != UserHandle.USER_ALL) {
771                    final int userStatus =
772                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
773
774                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
775                    boolean needUpdate = false;
776
777                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
778                    // already been set by the User thru the Disambiguation dialog
779                    switch (userStatus) {
780                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
781                            if (verified) {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
783                            } else {
784                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
785                            }
786                            needUpdate = true;
787                            break;
788
789                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
790                            if (verified) {
791                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
792                                needUpdate = true;
793                            }
794                            break;
795
796                        default:
797                            // Nothing to do
798                    }
799
800                    if (needUpdate) {
801                        mSettings.updateIntentFilterVerificationStatusLPw(
802                                packageName, updatedStatus, userId);
803                        scheduleWritePackageRestrictionsLocked(userId);
804                    }
805                }
806            }
807        }
808
809        @Override
810        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
811                    ActivityIntentInfo filter, String packageName) {
812            if (!hasValidDomains(filter)) {
813                return false;
814            }
815            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
816            if (ivs == null) {
817                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
818                        packageName);
819            }
820            if (DEBUG_DOMAIN_VERIFICATION) {
821                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
822            }
823            ivs.addFilter(filter);
824            return true;
825        }
826
827        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
828                int userId, int verificationId, String packageName) {
829            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
830                    verifierUid, userId, packageName);
831            ivs.setPendingState();
832            synchronized (mPackages) {
833                mIntentFilterVerificationStates.append(verificationId, ivs);
834                mCurrentIntentFilterVerifications.add(verificationId);
835            }
836            return ivs;
837        }
838    }
839
840    private static boolean hasValidDomains(ActivityIntentInfo filter) {
841        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
842                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
843                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
844    }
845
846    // Set of pending broadcasts for aggregating enable/disable of components.
847    static class PendingPackageBroadcasts {
848        // for each user id, a map of <package name -> components within that package>
849        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
850
851        public PendingPackageBroadcasts() {
852            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
853        }
854
855        public ArrayList<String> get(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
857            return packages.get(packageName);
858        }
859
860        public void put(int userId, String packageName, ArrayList<String> components) {
861            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
862            packages.put(packageName, components);
863        }
864
865        public void remove(int userId, String packageName) {
866            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
867            if (packages != null) {
868                packages.remove(packageName);
869            }
870        }
871
872        public void remove(int userId) {
873            mUidMap.remove(userId);
874        }
875
876        public int userIdCount() {
877            return mUidMap.size();
878        }
879
880        public int userIdAt(int n) {
881            return mUidMap.keyAt(n);
882        }
883
884        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
885            return mUidMap.get(userId);
886        }
887
888        public int size() {
889            // total number of pending broadcast entries across all userIds
890            int num = 0;
891            for (int i = 0; i< mUidMap.size(); i++) {
892                num += mUidMap.valueAt(i).size();
893            }
894            return num;
895        }
896
897        public void clear() {
898            mUidMap.clear();
899        }
900
901        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
902            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
903            if (map == null) {
904                map = new ArrayMap<String, ArrayList<String>>();
905                mUidMap.put(userId, map);
906            }
907            return map;
908        }
909    }
910    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
911
912    // Service Connection to remote media container service to copy
913    // package uri's from external media onto secure containers
914    // or internal storage.
915    private IMediaContainerService mContainerService = null;
916
917    static final int SEND_PENDING_BROADCAST = 1;
918    static final int MCS_BOUND = 3;
919    static final int END_COPY = 4;
920    static final int INIT_COPY = 5;
921    static final int MCS_UNBIND = 6;
922    static final int START_CLEANING_PACKAGE = 7;
923    static final int FIND_INSTALL_LOC = 8;
924    static final int POST_INSTALL = 9;
925    static final int MCS_RECONNECT = 10;
926    static final int MCS_GIVE_UP = 11;
927    static final int UPDATED_MEDIA_STATUS = 12;
928    static final int WRITE_SETTINGS = 13;
929    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
930    static final int PACKAGE_VERIFIED = 15;
931    static final int CHECK_PENDING_VERIFICATION = 16;
932    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
933    static final int INTENT_FILTER_VERIFIED = 18;
934
935    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
936
937    // Delay time in millisecs
938    static final int BROADCAST_DELAY = 10 * 1000;
939
940    static UserManagerService sUserManager;
941
942    // Stores a list of users whose package restrictions file needs to be updated
943    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
944
945    final private DefaultContainerConnection mDefContainerConn =
946            new DefaultContainerConnection();
947    class DefaultContainerConnection implements ServiceConnection {
948        public void onServiceConnected(ComponentName name, IBinder service) {
949            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
950            IMediaContainerService imcs =
951                IMediaContainerService.Stub.asInterface(service);
952            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
953        }
954
955        public void onServiceDisconnected(ComponentName name) {
956            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
957        }
958    }
959
960    // Recordkeeping of restore-after-install operations that are currently in flight
961    // between the Package Manager and the Backup Manager
962    static class PostInstallData {
963        public InstallArgs args;
964        public PackageInstalledInfo res;
965
966        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
967            args = _a;
968            res = _r;
969        }
970    }
971
972    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
973    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
974
975    // XML tags for backup/restore of various bits of state
976    private static final String TAG_PREFERRED_BACKUP = "pa";
977    private static final String TAG_DEFAULT_APPS = "da";
978    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
979
980    final @Nullable String mRequiredVerifierPackage;
981    final @Nullable String mRequiredInstallerPackage;
982
983    private final PackageUsage mPackageUsage = new PackageUsage();
984
985    private class PackageUsage {
986        private static final int WRITE_INTERVAL
987            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
988
989        private final Object mFileLock = new Object();
990        private final AtomicLong mLastWritten = new AtomicLong(0);
991        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
992
993        private boolean mIsHistoricalPackageUsageAvailable = true;
994
995        boolean isHistoricalPackageUsageAvailable() {
996            return mIsHistoricalPackageUsageAvailable;
997        }
998
999        void write(boolean force) {
1000            if (force) {
1001                writeInternal();
1002                return;
1003            }
1004            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1005                && !DEBUG_DEXOPT) {
1006                return;
1007            }
1008            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1009                new Thread("PackageUsage_DiskWriter") {
1010                    @Override
1011                    public void run() {
1012                        try {
1013                            writeInternal();
1014                        } finally {
1015                            mBackgroundWriteRunning.set(false);
1016                        }
1017                    }
1018                }.start();
1019            }
1020        }
1021
1022        private void writeInternal() {
1023            synchronized (mPackages) {
1024                synchronized (mFileLock) {
1025                    AtomicFile file = getFile();
1026                    FileOutputStream f = null;
1027                    try {
1028                        f = file.startWrite();
1029                        BufferedOutputStream out = new BufferedOutputStream(f);
1030                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1031                        StringBuilder sb = new StringBuilder();
1032                        for (PackageParser.Package pkg : mPackages.values()) {
1033                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1034                                continue;
1035                            }
1036                            sb.setLength(0);
1037                            sb.append(pkg.packageName);
1038                            sb.append(' ');
1039                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1040                            sb.append('\n');
1041                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1042                        }
1043                        out.flush();
1044                        file.finishWrite(f);
1045                    } catch (IOException e) {
1046                        if (f != null) {
1047                            file.failWrite(f);
1048                        }
1049                        Log.e(TAG, "Failed to write package usage times", e);
1050                    }
1051                }
1052            }
1053            mLastWritten.set(SystemClock.elapsedRealtime());
1054        }
1055
1056        void readLP() {
1057            synchronized (mFileLock) {
1058                AtomicFile file = getFile();
1059                BufferedInputStream in = null;
1060                try {
1061                    in = new BufferedInputStream(file.openRead());
1062                    StringBuffer sb = new StringBuffer();
1063                    while (true) {
1064                        String packageName = readToken(in, sb, ' ');
1065                        if (packageName == null) {
1066                            break;
1067                        }
1068                        String timeInMillisString = readToken(in, sb, '\n');
1069                        if (timeInMillisString == null) {
1070                            throw new IOException("Failed to find last usage time for package "
1071                                                  + packageName);
1072                        }
1073                        PackageParser.Package pkg = mPackages.get(packageName);
1074                        if (pkg == null) {
1075                            continue;
1076                        }
1077                        long timeInMillis;
1078                        try {
1079                            timeInMillis = Long.parseLong(timeInMillisString);
1080                        } catch (NumberFormatException e) {
1081                            throw new IOException("Failed to parse " + timeInMillisString
1082                                                  + " as a long.", e);
1083                        }
1084                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1085                    }
1086                } catch (FileNotFoundException expected) {
1087                    mIsHistoricalPackageUsageAvailable = false;
1088                } catch (IOException e) {
1089                    Log.w(TAG, "Failed to read package usage times", e);
1090                } finally {
1091                    IoUtils.closeQuietly(in);
1092                }
1093            }
1094            mLastWritten.set(SystemClock.elapsedRealtime());
1095        }
1096
1097        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1098                throws IOException {
1099            sb.setLength(0);
1100            while (true) {
1101                int ch = in.read();
1102                if (ch == -1) {
1103                    if (sb.length() == 0) {
1104                        return null;
1105                    }
1106                    throw new IOException("Unexpected EOF");
1107                }
1108                if (ch == endOfToken) {
1109                    return sb.toString();
1110                }
1111                sb.append((char)ch);
1112            }
1113        }
1114
1115        private AtomicFile getFile() {
1116            File dataDir = Environment.getDataDirectory();
1117            File systemDir = new File(dataDir, "system");
1118            File fname = new File(systemDir, "package-usage.list");
1119            return new AtomicFile(fname);
1120        }
1121    }
1122
1123    class PackageHandler extends Handler {
1124        private boolean mBound = false;
1125        final ArrayList<HandlerParams> mPendingInstalls =
1126            new ArrayList<HandlerParams>();
1127
1128        private boolean connectToService() {
1129            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1130                    " DefaultContainerService");
1131            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1132            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1133            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1134                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1135                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136                mBound = true;
1137                return true;
1138            }
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140            return false;
1141        }
1142
1143        private void disconnectService() {
1144            mContainerService = null;
1145            mBound = false;
1146            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1147            mContext.unbindService(mDefContainerConn);
1148            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1149        }
1150
1151        PackageHandler(Looper looper) {
1152            super(looper);
1153        }
1154
1155        public void handleMessage(Message msg) {
1156            try {
1157                doHandleMessage(msg);
1158            } finally {
1159                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1160            }
1161        }
1162
1163        void doHandleMessage(Message msg) {
1164            switch (msg.what) {
1165                case INIT_COPY: {
1166                    HandlerParams params = (HandlerParams) msg.obj;
1167                    int idx = mPendingInstalls.size();
1168                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1169                    // If a bind was already initiated we dont really
1170                    // need to do anything. The pending install
1171                    // will be processed later on.
1172                    if (!mBound) {
1173                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1174                                System.identityHashCode(mHandler));
1175                        // If this is the only one pending we might
1176                        // have to bind to the service again.
1177                        if (!connectToService()) {
1178                            Slog.e(TAG, "Failed to bind to media container service");
1179                            params.serviceError();
1180                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1181                                    System.identityHashCode(mHandler));
1182                            if (params.traceMethod != null) {
1183                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1184                                        params.traceCookie);
1185                            }
1186                            return;
1187                        } else {
1188                            // Once we bind to the service, the first
1189                            // pending request will be processed.
1190                            mPendingInstalls.add(idx, params);
1191                        }
1192                    } else {
1193                        mPendingInstalls.add(idx, params);
1194                        // Already bound to the service. Just make
1195                        // sure we trigger off processing the first request.
1196                        if (idx == 0) {
1197                            mHandler.sendEmptyMessage(MCS_BOUND);
1198                        }
1199                    }
1200                    break;
1201                }
1202                case MCS_BOUND: {
1203                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1204                    if (msg.obj != null) {
1205                        mContainerService = (IMediaContainerService) msg.obj;
1206                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1207                                System.identityHashCode(mHandler));
1208                    }
1209                    if (mContainerService == null) {
1210                        if (!mBound) {
1211                            // Something seriously wrong since we are not bound and we are not
1212                            // waiting for connection. Bail out.
1213                            Slog.e(TAG, "Cannot bind to media container service");
1214                            for (HandlerParams params : mPendingInstalls) {
1215                                // Indicate service bind error
1216                                params.serviceError();
1217                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1218                                        System.identityHashCode(params));
1219                                if (params.traceMethod != null) {
1220                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1221                                            params.traceMethod, params.traceCookie);
1222                                }
1223                                return;
1224                            }
1225                            mPendingInstalls.clear();
1226                        } else {
1227                            Slog.w(TAG, "Waiting to connect to media container service");
1228                        }
1229                    } else if (mPendingInstalls.size() > 0) {
1230                        HandlerParams params = mPendingInstalls.get(0);
1231                        if (params != null) {
1232                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1233                                    System.identityHashCode(params));
1234                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1235                            if (params.startCopy()) {
1236                                // We are done...  look for more work or to
1237                                // go idle.
1238                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1239                                        "Checking for more work or unbind...");
1240                                // Delete pending install
1241                                if (mPendingInstalls.size() > 0) {
1242                                    mPendingInstalls.remove(0);
1243                                }
1244                                if (mPendingInstalls.size() == 0) {
1245                                    if (mBound) {
1246                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1247                                                "Posting delayed MCS_UNBIND");
1248                                        removeMessages(MCS_UNBIND);
1249                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1250                                        // Unbind after a little delay, to avoid
1251                                        // continual thrashing.
1252                                        sendMessageDelayed(ubmsg, 10000);
1253                                    }
1254                                } else {
1255                                    // There are more pending requests in queue.
1256                                    // Just post MCS_BOUND message to trigger processing
1257                                    // of next pending install.
1258                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1259                                            "Posting MCS_BOUND for next work");
1260                                    mHandler.sendEmptyMessage(MCS_BOUND);
1261                                }
1262                            }
1263                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1264                        }
1265                    } else {
1266                        // Should never happen ideally.
1267                        Slog.w(TAG, "Empty queue");
1268                    }
1269                    break;
1270                }
1271                case MCS_RECONNECT: {
1272                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1273                    if (mPendingInstalls.size() > 0) {
1274                        if (mBound) {
1275                            disconnectService();
1276                        }
1277                        if (!connectToService()) {
1278                            Slog.e(TAG, "Failed to bind to media container service");
1279                            for (HandlerParams params : mPendingInstalls) {
1280                                // Indicate service bind error
1281                                params.serviceError();
1282                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1283                                        System.identityHashCode(params));
1284                            }
1285                            mPendingInstalls.clear();
1286                        }
1287                    }
1288                    break;
1289                }
1290                case MCS_UNBIND: {
1291                    // If there is no actual work left, then time to unbind.
1292                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1293
1294                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1295                        if (mBound) {
1296                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1297
1298                            disconnectService();
1299                        }
1300                    } else if (mPendingInstalls.size() > 0) {
1301                        // There are more pending requests in queue.
1302                        // Just post MCS_BOUND message to trigger processing
1303                        // of next pending install.
1304                        mHandler.sendEmptyMessage(MCS_BOUND);
1305                    }
1306
1307                    break;
1308                }
1309                case MCS_GIVE_UP: {
1310                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1311                    HandlerParams params = mPendingInstalls.remove(0);
1312                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1313                            System.identityHashCode(params));
1314                    break;
1315                }
1316                case SEND_PENDING_BROADCAST: {
1317                    String packages[];
1318                    ArrayList<String> components[];
1319                    int size = 0;
1320                    int uids[];
1321                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1322                    synchronized (mPackages) {
1323                        if (mPendingBroadcasts == null) {
1324                            return;
1325                        }
1326                        size = mPendingBroadcasts.size();
1327                        if (size <= 0) {
1328                            // Nothing to be done. Just return
1329                            return;
1330                        }
1331                        packages = new String[size];
1332                        components = new ArrayList[size];
1333                        uids = new int[size];
1334                        int i = 0;  // filling out the above arrays
1335
1336                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1337                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1338                            Iterator<Map.Entry<String, ArrayList<String>>> it
1339                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1340                                            .entrySet().iterator();
1341                            while (it.hasNext() && i < size) {
1342                                Map.Entry<String, ArrayList<String>> ent = it.next();
1343                                packages[i] = ent.getKey();
1344                                components[i] = ent.getValue();
1345                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1346                                uids[i] = (ps != null)
1347                                        ? UserHandle.getUid(packageUserId, ps.appId)
1348                                        : -1;
1349                                i++;
1350                            }
1351                        }
1352                        size = i;
1353                        mPendingBroadcasts.clear();
1354                    }
1355                    // Send broadcasts
1356                    for (int i = 0; i < size; i++) {
1357                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1358                    }
1359                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1360                    break;
1361                }
1362                case START_CLEANING_PACKAGE: {
1363                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1364                    final String packageName = (String)msg.obj;
1365                    final int userId = msg.arg1;
1366                    final boolean andCode = msg.arg2 != 0;
1367                    synchronized (mPackages) {
1368                        if (userId == UserHandle.USER_ALL) {
1369                            int[] users = sUserManager.getUserIds();
1370                            for (int user : users) {
1371                                mSettings.addPackageToCleanLPw(
1372                                        new PackageCleanItem(user, packageName, andCode));
1373                            }
1374                        } else {
1375                            mSettings.addPackageToCleanLPw(
1376                                    new PackageCleanItem(userId, packageName, andCode));
1377                        }
1378                    }
1379                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1380                    startCleaningPackages();
1381                } break;
1382                case POST_INSTALL: {
1383                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1384
1385                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1386                    mRunningInstalls.delete(msg.arg1);
1387                    boolean deleteOld = false;
1388
1389                    if (data != null) {
1390                        InstallArgs args = data.args;
1391                        PackageInstalledInfo res = data.res;
1392
1393                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1394                            final String packageName = res.pkg.applicationInfo.packageName;
1395                            res.removedInfo.sendBroadcast(false, true, false);
1396                            Bundle extras = new Bundle(1);
1397                            extras.putInt(Intent.EXTRA_UID, res.uid);
1398
1399                            // Now that we successfully installed the package, grant runtime
1400                            // permissions if requested before broadcasting the install.
1401                            if ((args.installFlags
1402                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1403                                    && res.pkg.applicationInfo.targetSdkVersion
1404                                            >= Build.VERSION_CODES.M) {
1405                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1406                                        args.installGrantPermissions);
1407                            }
1408
1409                            synchronized (mPackages) {
1410                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1411                            }
1412
1413                            // Determine the set of users who are adding this
1414                            // package for the first time vs. those who are seeing
1415                            // an update.
1416                            int[] firstUsers;
1417                            int[] updateUsers = new int[0];
1418                            if (res.origUsers == null || res.origUsers.length == 0) {
1419                                firstUsers = res.newUsers;
1420                            } else {
1421                                firstUsers = new int[0];
1422                                for (int i=0; i<res.newUsers.length; i++) {
1423                                    int user = res.newUsers[i];
1424                                    boolean isNew = true;
1425                                    for (int j=0; j<res.origUsers.length; j++) {
1426                                        if (res.origUsers[j] == user) {
1427                                            isNew = false;
1428                                            break;
1429                                        }
1430                                    }
1431                                    if (isNew) {
1432                                        int[] newFirst = new int[firstUsers.length+1];
1433                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1434                                                firstUsers.length);
1435                                        newFirst[firstUsers.length] = user;
1436                                        firstUsers = newFirst;
1437                                    } else {
1438                                        int[] newUpdate = new int[updateUsers.length+1];
1439                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1440                                                updateUsers.length);
1441                                        newUpdate[updateUsers.length] = user;
1442                                        updateUsers = newUpdate;
1443                                    }
1444                                }
1445                            }
1446                            // don't broadcast for ephemeral installs/updates
1447                            final boolean isEphemeral = isEphemeral(res.pkg);
1448                            if (!isEphemeral) {
1449                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1450                                        extras, 0 /*flags*/, null /*targetPackage*/,
1451                                        null /*finishedReceiver*/, firstUsers);
1452                            }
1453                            final boolean update = res.removedInfo.removedPackage != null;
1454                            if (update) {
1455                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1456                            }
1457                            if (!isEphemeral) {
1458                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1459                                        extras, 0 /*flags*/, null /*targetPackage*/,
1460                                        null /*finishedReceiver*/, updateUsers);
1461                            }
1462                            if (update) {
1463                                if (!isEphemeral) {
1464                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1465                                            packageName, extras, 0 /*flags*/,
1466                                            null /*targetPackage*/, null /*finishedReceiver*/,
1467                                            updateUsers);
1468                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1469                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1470                                            packageName /*targetPackage*/,
1471                                            null /*finishedReceiver*/, updateUsers);
1472                                }
1473
1474                                // treat asec-hosted packages like removable media on upgrade
1475                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1476                                    if (DEBUG_INSTALL) {
1477                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1478                                                + " is ASEC-hosted -> AVAILABLE");
1479                                    }
1480                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1481                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1482                                    pkgList.add(packageName);
1483                                    sendResourcesChangedBroadcast(true, true,
1484                                            pkgList,uidArray, null);
1485                                }
1486                            }
1487                            if (res.removedInfo.args != null) {
1488                                // Remove the replaced package's older resources safely now
1489                                deleteOld = true;
1490                            }
1491
1492                            // If this app is a browser and it's newly-installed for some
1493                            // users, clear any default-browser state in those users
1494                            if (firstUsers.length > 0) {
1495                                // the app's nature doesn't depend on the user, so we can just
1496                                // check its browser nature in any user and generalize.
1497                                if (packageIsBrowser(packageName, firstUsers[0])) {
1498                                    synchronized (mPackages) {
1499                                        for (int userId : firstUsers) {
1500                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1501                                        }
1502                                    }
1503                                }
1504                            }
1505                            // Log current value of "unknown sources" setting
1506                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1507                                getUnknownSourcesSettings());
1508                        }
1509                        // Force a gc to clear up things
1510                        Runtime.getRuntime().gc();
1511                        // We delete after a gc for applications  on sdcard.
1512                        if (deleteOld) {
1513                            synchronized (mInstallLock) {
1514                                res.removedInfo.args.doPostDeleteLI(true);
1515                            }
1516                        }
1517                        if (args.observer != null) {
1518                            try {
1519                                Bundle extras = extrasForInstallResult(res);
1520                                args.observer.onPackageInstalled(res.name, res.returnCode,
1521                                        res.returnMsg, extras);
1522                            } catch (RemoteException e) {
1523                                Slog.i(TAG, "Observer no longer exists.");
1524                            }
1525                        }
1526                        if (args.traceMethod != null) {
1527                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1528                                    args.traceCookie);
1529                        }
1530                        return;
1531                    } else {
1532                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1533                    }
1534
1535                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1536                } break;
1537                case UPDATED_MEDIA_STATUS: {
1538                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1539                    boolean reportStatus = msg.arg1 == 1;
1540                    boolean doGc = msg.arg2 == 1;
1541                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1542                    if (doGc) {
1543                        // Force a gc to clear up stale containers.
1544                        Runtime.getRuntime().gc();
1545                    }
1546                    if (msg.obj != null) {
1547                        @SuppressWarnings("unchecked")
1548                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1549                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1550                        // Unload containers
1551                        unloadAllContainers(args);
1552                    }
1553                    if (reportStatus) {
1554                        try {
1555                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1556                            PackageHelper.getMountService().finishMediaUpdate();
1557                        } catch (RemoteException e) {
1558                            Log.e(TAG, "MountService not running?");
1559                        }
1560                    }
1561                } break;
1562                case WRITE_SETTINGS: {
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1564                    synchronized (mPackages) {
1565                        removeMessages(WRITE_SETTINGS);
1566                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1567                        mSettings.writeLPr();
1568                        mDirtyUsers.clear();
1569                    }
1570                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1571                } break;
1572                case WRITE_PACKAGE_RESTRICTIONS: {
1573                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1574                    synchronized (mPackages) {
1575                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1576                        for (int userId : mDirtyUsers) {
1577                            mSettings.writePackageRestrictionsLPr(userId);
1578                        }
1579                        mDirtyUsers.clear();
1580                    }
1581                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1582                } break;
1583                case CHECK_PENDING_VERIFICATION: {
1584                    final int verificationId = msg.arg1;
1585                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1586
1587                    if ((state != null) && !state.timeoutExtended()) {
1588                        final InstallArgs args = state.getInstallArgs();
1589                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1590
1591                        Slog.i(TAG, "Verification timed out for " + originUri);
1592                        mPendingVerification.remove(verificationId);
1593
1594                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1595
1596                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1597                            Slog.i(TAG, "Continuing with installation of " + originUri);
1598                            state.setVerifierResponse(Binder.getCallingUid(),
1599                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1600                            broadcastPackageVerified(verificationId, originUri,
1601                                    PackageManager.VERIFICATION_ALLOW,
1602                                    state.getInstallArgs().getUser());
1603                            try {
1604                                ret = args.copyApk(mContainerService, true);
1605                            } catch (RemoteException e) {
1606                                Slog.e(TAG, "Could not contact the ContainerService");
1607                            }
1608                        } else {
1609                            broadcastPackageVerified(verificationId, originUri,
1610                                    PackageManager.VERIFICATION_REJECT,
1611                                    state.getInstallArgs().getUser());
1612                        }
1613
1614                        Trace.asyncTraceEnd(
1615                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1616
1617                        processPendingInstall(args, ret);
1618                        mHandler.sendEmptyMessage(MCS_UNBIND);
1619                    }
1620                    break;
1621                }
1622                case PACKAGE_VERIFIED: {
1623                    final int verificationId = msg.arg1;
1624
1625                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1626                    if (state == null) {
1627                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1628                        break;
1629                    }
1630
1631                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1632
1633                    state.setVerifierResponse(response.callerUid, response.code);
1634
1635                    if (state.isVerificationComplete()) {
1636                        mPendingVerification.remove(verificationId);
1637
1638                        final InstallArgs args = state.getInstallArgs();
1639                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1640
1641                        int ret;
1642                        if (state.isInstallAllowed()) {
1643                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1644                            broadcastPackageVerified(verificationId, originUri,
1645                                    response.code, state.getInstallArgs().getUser());
1646                            try {
1647                                ret = args.copyApk(mContainerService, true);
1648                            } catch (RemoteException e) {
1649                                Slog.e(TAG, "Could not contact the ContainerService");
1650                            }
1651                        } else {
1652                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1653                        }
1654
1655                        Trace.asyncTraceEnd(
1656                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1657
1658                        processPendingInstall(args, ret);
1659                        mHandler.sendEmptyMessage(MCS_UNBIND);
1660                    }
1661
1662                    break;
1663                }
1664                case START_INTENT_FILTER_VERIFICATIONS: {
1665                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1666                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1667                            params.replacing, params.pkg);
1668                    break;
1669                }
1670                case INTENT_FILTER_VERIFIED: {
1671                    final int verificationId = msg.arg1;
1672
1673                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1674                            verificationId);
1675                    if (state == null) {
1676                        Slog.w(TAG, "Invalid IntentFilter verification token "
1677                                + verificationId + " received");
1678                        break;
1679                    }
1680
1681                    final int userId = state.getUserId();
1682
1683                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1684                            "Processing IntentFilter verification with token:"
1685                            + verificationId + " and userId:" + userId);
1686
1687                    final IntentFilterVerificationResponse response =
1688                            (IntentFilterVerificationResponse) msg.obj;
1689
1690                    state.setVerifierResponse(response.callerUid, response.code);
1691
1692                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1693                            "IntentFilter verification with token:" + verificationId
1694                            + " and userId:" + userId
1695                            + " is settings verifier response with response code:"
1696                            + response.code);
1697
1698                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1699                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1700                                + response.getFailedDomainsString());
1701                    }
1702
1703                    if (state.isVerificationComplete()) {
1704                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1705                    } else {
1706                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1707                                "IntentFilter verification with token:" + verificationId
1708                                + " was not said to be complete");
1709                    }
1710
1711                    break;
1712                }
1713            }
1714        }
1715    }
1716
1717    private StorageEventListener mStorageListener = new StorageEventListener() {
1718        @Override
1719        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1720            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1721                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1722                    final String volumeUuid = vol.getFsUuid();
1723
1724                    // Clean up any users or apps that were removed or recreated
1725                    // while this volume was missing
1726                    reconcileUsers(volumeUuid);
1727                    reconcileApps(volumeUuid);
1728
1729                    // Clean up any install sessions that expired or were
1730                    // cancelled while this volume was missing
1731                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1732
1733                    loadPrivatePackages(vol);
1734
1735                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1736                    unloadPrivatePackages(vol);
1737                }
1738            }
1739
1740            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1741                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1742                    updateExternalMediaStatus(true, false);
1743                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1744                    updateExternalMediaStatus(false, false);
1745                }
1746            }
1747        }
1748
1749        @Override
1750        public void onVolumeForgotten(String fsUuid) {
1751            if (TextUtils.isEmpty(fsUuid)) {
1752                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1753                return;
1754            }
1755
1756            // Remove any apps installed on the forgotten volume
1757            synchronized (mPackages) {
1758                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1759                for (PackageSetting ps : packages) {
1760                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1761                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1762                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1763                }
1764
1765                mSettings.onVolumeForgotten(fsUuid);
1766                mSettings.writeLPr();
1767            }
1768        }
1769    };
1770
1771    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1772            String[] grantedPermissions) {
1773        if (userId >= UserHandle.USER_SYSTEM) {
1774            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1775        } else if (userId == UserHandle.USER_ALL) {
1776            final int[] userIds;
1777            synchronized (mPackages) {
1778                userIds = UserManagerService.getInstance().getUserIds();
1779            }
1780            for (int someUserId : userIds) {
1781                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1782            }
1783        }
1784
1785        // We could have touched GID membership, so flush out packages.list
1786        synchronized (mPackages) {
1787            mSettings.writePackageListLPr();
1788        }
1789    }
1790
1791    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1792            String[] grantedPermissions) {
1793        SettingBase sb = (SettingBase) pkg.mExtras;
1794        if (sb == null) {
1795            return;
1796        }
1797
1798        PermissionsState permissionsState = sb.getPermissionsState();
1799
1800        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1801                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1802
1803        synchronized (mPackages) {
1804            for (String permission : pkg.requestedPermissions) {
1805                BasePermission bp = mSettings.mPermissions.get(permission);
1806                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1807                        && (grantedPermissions == null
1808                               || ArrayUtils.contains(grantedPermissions, permission))) {
1809                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1810                    // Installer cannot change immutable permissions.
1811                    if ((flags & immutableFlags) == 0) {
1812                        grantRuntimePermission(pkg.packageName, permission, userId);
1813                    }
1814                }
1815            }
1816        }
1817    }
1818
1819    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1820        Bundle extras = null;
1821        switch (res.returnCode) {
1822            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1823                extras = new Bundle();
1824                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1825                        res.origPermission);
1826                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1827                        res.origPackage);
1828                break;
1829            }
1830            case PackageManager.INSTALL_SUCCEEDED: {
1831                extras = new Bundle();
1832                extras.putBoolean(Intent.EXTRA_REPLACING,
1833                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1834                break;
1835            }
1836        }
1837        return extras;
1838    }
1839
1840    void scheduleWriteSettingsLocked() {
1841        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1842            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1843        }
1844    }
1845
1846    void scheduleWritePackageRestrictionsLocked(int userId) {
1847        if (!sUserManager.exists(userId)) return;
1848        mDirtyUsers.add(userId);
1849        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1850            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1851        }
1852    }
1853
1854    public static PackageManagerService main(Context context, Installer installer,
1855            boolean factoryTest, boolean onlyCore) {
1856        PackageManagerService m = new PackageManagerService(context, installer,
1857                factoryTest, onlyCore);
1858        m.enableSystemUserPackages();
1859        ServiceManager.addService("package", m);
1860        return m;
1861    }
1862
1863    private void enableSystemUserPackages() {
1864        if (!UserManager.isSplitSystemUser()) {
1865            return;
1866        }
1867        // For system user, enable apps based on the following conditions:
1868        // - app is whitelisted or belong to one of these groups:
1869        //   -- system app which has no launcher icons
1870        //   -- system app which has INTERACT_ACROSS_USERS permission
1871        //   -- system IME app
1872        // - app is not in the blacklist
1873        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1874        Set<String> enableApps = new ArraySet<>();
1875        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1876                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1877                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1878        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1879        enableApps.addAll(wlApps);
1880        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1881                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1882        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1883        enableApps.removeAll(blApps);
1884        Log.i(TAG, "Applications installed for system user: " + enableApps);
1885        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1886                UserHandle.SYSTEM);
1887        final int allAppsSize = allAps.size();
1888        synchronized (mPackages) {
1889            for (int i = 0; i < allAppsSize; i++) {
1890                String pName = allAps.get(i);
1891                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1892                // Should not happen, but we shouldn't be failing if it does
1893                if (pkgSetting == null) {
1894                    continue;
1895                }
1896                boolean install = enableApps.contains(pName);
1897                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1898                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1899                            + " for system user");
1900                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1901                }
1902            }
1903        }
1904    }
1905
1906    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1907        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1908                Context.DISPLAY_SERVICE);
1909        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1910    }
1911
1912    public PackageManagerService(Context context, Installer installer,
1913            boolean factoryTest, boolean onlyCore) {
1914        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1915                SystemClock.uptimeMillis());
1916
1917        if (mSdkVersion <= 0) {
1918            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1919        }
1920
1921        mContext = context;
1922        mFactoryTest = factoryTest;
1923        mOnlyCore = onlyCore;
1924        mMetrics = new DisplayMetrics();
1925        mSettings = new Settings(mPackages);
1926        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1929                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1930        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1931                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1932        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1933                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1934        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1935                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1936        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1937                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1938
1939        String separateProcesses = SystemProperties.get("debug.separate_processes");
1940        if (separateProcesses != null && separateProcesses.length() > 0) {
1941            if ("*".equals(separateProcesses)) {
1942                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1943                mSeparateProcesses = null;
1944                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1945            } else {
1946                mDefParseFlags = 0;
1947                mSeparateProcesses = separateProcesses.split(",");
1948                Slog.w(TAG, "Running with debug.separate_processes: "
1949                        + separateProcesses);
1950            }
1951        } else {
1952            mDefParseFlags = 0;
1953            mSeparateProcesses = null;
1954        }
1955
1956        mInstaller = installer;
1957        mPackageDexOptimizer = new PackageDexOptimizer(this);
1958        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1959
1960        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1961                FgThread.get().getLooper());
1962
1963        getDefaultDisplayMetrics(context, mMetrics);
1964
1965        SystemConfig systemConfig = SystemConfig.getInstance();
1966        mGlobalGids = systemConfig.getGlobalGids();
1967        mSystemPermissions = systemConfig.getSystemPermissions();
1968        mAvailableFeatures = systemConfig.getAvailableFeatures();
1969
1970        synchronized (mInstallLock) {
1971        // writer
1972        synchronized (mPackages) {
1973            mHandlerThread = new ServiceThread(TAG,
1974                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1975            mHandlerThread.start();
1976            mHandler = new PackageHandler(mHandlerThread.getLooper());
1977            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1978
1979            File dataDir = Environment.getDataDirectory();
1980            mAppInstallDir = new File(dataDir, "app");
1981            mAppLib32InstallDir = new File(dataDir, "app-lib");
1982            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1983            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1984            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1985
1986            sUserManager = new UserManagerService(context, this, mPackages);
1987
1988            // Propagate permission configuration in to package manager.
1989            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1990                    = systemConfig.getPermissions();
1991            for (int i=0; i<permConfig.size(); i++) {
1992                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1993                BasePermission bp = mSettings.mPermissions.get(perm.name);
1994                if (bp == null) {
1995                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1996                    mSettings.mPermissions.put(perm.name, bp);
1997                }
1998                if (perm.gids != null) {
1999                    bp.setGids(perm.gids, perm.perUser);
2000                }
2001            }
2002
2003            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2004            for (int i=0; i<libConfig.size(); i++) {
2005                mSharedLibraries.put(libConfig.keyAt(i),
2006                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2007            }
2008
2009            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2010
2011            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2012
2013            String customResolverActivity = Resources.getSystem().getString(
2014                    R.string.config_customResolverActivity);
2015            if (TextUtils.isEmpty(customResolverActivity)) {
2016                customResolverActivity = null;
2017            } else {
2018                mCustomResolverComponentName = ComponentName.unflattenFromString(
2019                        customResolverActivity);
2020            }
2021
2022            long startTime = SystemClock.uptimeMillis();
2023
2024            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2025                    startTime);
2026
2027            // Set flag to monitor and not change apk file paths when
2028            // scanning install directories.
2029            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2030
2031            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2032            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2033
2034            if (bootClassPath == null) {
2035                Slog.w(TAG, "No BOOTCLASSPATH found!");
2036            }
2037
2038            if (systemServerClassPath == null) {
2039                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2040            }
2041
2042            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2043            final String[] dexCodeInstructionSets =
2044                    getDexCodeInstructionSets(
2045                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2046
2047            /**
2048             * Ensure all external libraries have had dexopt run on them.
2049             */
2050            if (mSharedLibraries.size() > 0) {
2051                // NOTE: For now, we're compiling these system "shared libraries"
2052                // (and framework jars) into all available architectures. It's possible
2053                // to compile them only when we come across an app that uses them (there's
2054                // already logic for that in scanPackageLI) but that adds some complexity.
2055                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2056                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2057                        final String lib = libEntry.path;
2058                        if (lib == null) {
2059                            continue;
2060                        }
2061
2062                        try {
2063                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2064                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2065                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2066                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2067                            }
2068                        } catch (FileNotFoundException e) {
2069                            Slog.w(TAG, "Library not found: " + lib);
2070                        } catch (IOException e) {
2071                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2072                                    + e.getMessage());
2073                        }
2074                    }
2075                }
2076            }
2077
2078            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2079
2080            final VersionInfo ver = mSettings.getInternalVersion();
2081            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2082            // when upgrading from pre-M, promote system app permissions from install to runtime
2083            mPromoteSystemApps =
2084                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2085
2086            // save off the names of pre-existing system packages prior to scanning; we don't
2087            // want to automatically grant runtime permissions for new system apps
2088            if (mPromoteSystemApps) {
2089                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2090                while (pkgSettingIter.hasNext()) {
2091                    PackageSetting ps = pkgSettingIter.next();
2092                    if (isSystemApp(ps)) {
2093                        mExistingSystemPackages.add(ps.name);
2094                    }
2095                }
2096            }
2097
2098            // Collect vendor overlay packages.
2099            // (Do this before scanning any apps.)
2100            // For security and version matching reason, only consider
2101            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2102            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2103            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2104                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2105
2106            // Find base frameworks (resource packages without code).
2107            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2108                    | PackageParser.PARSE_IS_SYSTEM_DIR
2109                    | PackageParser.PARSE_IS_PRIVILEGED,
2110                    scanFlags | SCAN_NO_DEX, 0);
2111
2112            // Collected privileged system packages.
2113            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2114            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2115                    | PackageParser.PARSE_IS_SYSTEM_DIR
2116                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2117
2118            // Collect ordinary system packages.
2119            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2120            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2121                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2122
2123            // Collect all vendor packages.
2124            File vendorAppDir = new File("/vendor/app");
2125            try {
2126                vendorAppDir = vendorAppDir.getCanonicalFile();
2127            } catch (IOException e) {
2128                // failed to look up canonical path, continue with original one
2129            }
2130            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2131                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2132
2133            // Collect all OEM packages.
2134            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2135            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2136                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2137
2138            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2139            mInstaller.moveFiles();
2140
2141            // Prune any system packages that no longer exist.
2142            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2143            if (!mOnlyCore) {
2144                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2145                while (psit.hasNext()) {
2146                    PackageSetting ps = psit.next();
2147
2148                    /*
2149                     * If this is not a system app, it can't be a
2150                     * disable system app.
2151                     */
2152                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2153                        continue;
2154                    }
2155
2156                    /*
2157                     * If the package is scanned, it's not erased.
2158                     */
2159                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2160                    if (scannedPkg != null) {
2161                        /*
2162                         * If the system app is both scanned and in the
2163                         * disabled packages list, then it must have been
2164                         * added via OTA. Remove it from the currently
2165                         * scanned package so the previously user-installed
2166                         * application can be scanned.
2167                         */
2168                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2169                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2170                                    + ps.name + "; removing system app.  Last known codePath="
2171                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2172                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2173                                    + scannedPkg.mVersionCode);
2174                            removePackageLI(ps, true);
2175                            mExpectingBetter.put(ps.name, ps.codePath);
2176                        }
2177
2178                        continue;
2179                    }
2180
2181                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2182                        psit.remove();
2183                        logCriticalInfo(Log.WARN, "System package " + ps.name
2184                                + " no longer exists; wiping its data");
2185                        removeDataDirsLI(null, ps.name);
2186                    } else {
2187                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2188                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2189                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2190                        }
2191                    }
2192                }
2193            }
2194
2195            //look for any incomplete package installations
2196            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2197            //clean up list
2198            for(int i = 0; i < deletePkgsList.size(); i++) {
2199                //clean up here
2200                cleanupInstallFailedPackage(deletePkgsList.get(i));
2201            }
2202            //delete tmp files
2203            deleteTempPackageFiles();
2204
2205            // Remove any shared userIDs that have no associated packages
2206            mSettings.pruneSharedUsersLPw();
2207
2208            if (!mOnlyCore) {
2209                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2210                        SystemClock.uptimeMillis());
2211                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2212
2213                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2214                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2215
2216                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2217                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2218
2219                /**
2220                 * Remove disable package settings for any updated system
2221                 * apps that were removed via an OTA. If they're not a
2222                 * previously-updated app, remove them completely.
2223                 * Otherwise, just revoke their system-level permissions.
2224                 */
2225                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2226                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2227                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2228
2229                    String msg;
2230                    if (deletedPkg == null) {
2231                        msg = "Updated system package " + deletedAppName
2232                                + " no longer exists; wiping its data";
2233                        removeDataDirsLI(null, deletedAppName);
2234                    } else {
2235                        msg = "Updated system app + " + deletedAppName
2236                                + " no longer present; removing system privileges for "
2237                                + deletedAppName;
2238
2239                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2240
2241                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2242                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2243                    }
2244                    logCriticalInfo(Log.WARN, msg);
2245                }
2246
2247                /**
2248                 * Make sure all system apps that we expected to appear on
2249                 * the userdata partition actually showed up. If they never
2250                 * appeared, crawl back and revive the system version.
2251                 */
2252                for (int i = 0; i < mExpectingBetter.size(); i++) {
2253                    final String packageName = mExpectingBetter.keyAt(i);
2254                    if (!mPackages.containsKey(packageName)) {
2255                        final File scanFile = mExpectingBetter.valueAt(i);
2256
2257                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2258                                + " but never showed up; reverting to system");
2259
2260                        final int reparseFlags;
2261                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2262                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2263                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2264                                    | PackageParser.PARSE_IS_PRIVILEGED;
2265                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2268                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2269                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2270                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2271                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2272                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2273                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2274                        } else {
2275                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2276                            continue;
2277                        }
2278
2279                        mSettings.enableSystemPackageLPw(packageName);
2280
2281                        try {
2282                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2283                        } catch (PackageManagerException e) {
2284                            Slog.e(TAG, "Failed to parse original system package: "
2285                                    + e.getMessage());
2286                        }
2287                    }
2288                }
2289            }
2290            mExpectingBetter.clear();
2291
2292            // Now that we know all of the shared libraries, update all clients to have
2293            // the correct library paths.
2294            updateAllSharedLibrariesLPw();
2295
2296            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2297                // NOTE: We ignore potential failures here during a system scan (like
2298                // the rest of the commands above) because there's precious little we
2299                // can do about it. A settings error is reported, though.
2300                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2301                        false /* boot complete */);
2302            }
2303
2304            // Now that we know all the packages we are keeping,
2305            // read and update their last usage times.
2306            mPackageUsage.readLP();
2307
2308            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2309                    SystemClock.uptimeMillis());
2310            Slog.i(TAG, "Time to scan packages: "
2311                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2312                    + " seconds");
2313
2314            // If the platform SDK has changed since the last time we booted,
2315            // we need to re-grant app permission to catch any new ones that
2316            // appear.  This is really a hack, and means that apps can in some
2317            // cases get permissions that the user didn't initially explicitly
2318            // allow...  it would be nice to have some better way to handle
2319            // this situation.
2320            int updateFlags = UPDATE_PERMISSIONS_ALL;
2321            if (ver.sdkVersion != mSdkVersion) {
2322                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2323                        + mSdkVersion + "; regranting permissions for internal storage");
2324                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2325            }
2326            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2327            ver.sdkVersion = mSdkVersion;
2328
2329            // If this is the first boot or an update from pre-M, and it is a normal
2330            // boot, then we need to initialize the default preferred apps across
2331            // all defined users.
2332            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2333                for (UserInfo user : sUserManager.getUsers(true)) {
2334                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2335                    applyFactoryDefaultBrowserLPw(user.id);
2336                    primeDomainVerificationsLPw(user.id);
2337                }
2338            }
2339
2340            // If this is first boot after an OTA, and a normal boot, then
2341            // we need to clear code cache directories.
2342            if (mIsUpgrade && !onlyCore) {
2343                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2344                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2345                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2346                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2347                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2348                    }
2349                }
2350                ver.fingerprint = Build.FINGERPRINT;
2351            }
2352
2353            checkDefaultBrowser();
2354
2355            // clear only after permissions and other defaults have been updated
2356            mExistingSystemPackages.clear();
2357            mPromoteSystemApps = false;
2358
2359            // All the changes are done during package scanning.
2360            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2361
2362            // can downgrade to reader
2363            mSettings.writeLPr();
2364
2365            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2366                    SystemClock.uptimeMillis());
2367
2368            if (!mOnlyCore) {
2369                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2370                mRequiredInstallerPackage = getRequiredInstallerLPr();
2371                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2372                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2373                        mIntentFilterVerifierComponent);
2374            } else {
2375                mRequiredVerifierPackage = null;
2376                mRequiredInstallerPackage = null;
2377                mIntentFilterVerifierComponent = null;
2378                mIntentFilterVerifier = null;
2379            }
2380
2381            mInstallerService = new PackageInstallerService(context, this);
2382
2383            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2384            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2385            // both the installer and resolver must be present to enable ephemeral
2386            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2387                if (DEBUG_EPHEMERAL) {
2388                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2389                            + " installer:" + ephemeralInstallerComponent);
2390                }
2391                mEphemeralResolverComponent = ephemeralResolverComponent;
2392                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2393                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2394                mEphemeralResolverConnection =
2395                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2396            } else {
2397                if (DEBUG_EPHEMERAL) {
2398                    final String missingComponent =
2399                            (ephemeralResolverComponent == null)
2400                            ? (ephemeralInstallerComponent == null)
2401                                    ? "resolver and installer"
2402                                    : "resolver"
2403                            : "installer";
2404                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2405                }
2406                mEphemeralResolverComponent = null;
2407                mEphemeralInstallerComponent = null;
2408                mEphemeralResolverConnection = null;
2409            }
2410
2411            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2412        } // synchronized (mPackages)
2413        } // synchronized (mInstallLock)
2414
2415        // Now after opening every single application zip, make sure they
2416        // are all flushed.  Not really needed, but keeps things nice and
2417        // tidy.
2418        Runtime.getRuntime().gc();
2419
2420        // The initial scanning above does many calls into installd while
2421        // holding the mPackages lock, but we're mostly interested in yelling
2422        // once we have a booted system.
2423        mInstaller.setWarnIfHeld(mPackages);
2424
2425        // Expose private service for system components to use.
2426        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2427    }
2428
2429    @Override
2430    public boolean isFirstBoot() {
2431        return !mRestoredSettings;
2432    }
2433
2434    @Override
2435    public boolean isOnlyCoreApps() {
2436        return mOnlyCore;
2437    }
2438
2439    @Override
2440    public boolean isUpgrade() {
2441        return mIsUpgrade;
2442    }
2443
2444    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2445        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2446
2447        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2448                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2449        if (matches.size() == 1) {
2450            return matches.get(0).getComponentInfo().packageName;
2451        } else {
2452            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2453            return null;
2454        }
2455    }
2456
2457    private @NonNull String getRequiredInstallerLPr() {
2458        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2459        intent.addCategory(Intent.CATEGORY_DEFAULT);
2460        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2461
2462        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2463                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2464        if (matches.size() == 1) {
2465            return matches.get(0).getComponentInfo().packageName;
2466        } else {
2467            throw new RuntimeException("There must be exactly one installer; found " + matches);
2468        }
2469    }
2470
2471    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2472        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2473
2474        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2475                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2476        ResolveInfo best = null;
2477        final int N = matches.size();
2478        for (int i = 0; i < N; i++) {
2479            final ResolveInfo cur = matches.get(i);
2480            final String packageName = cur.getComponentInfo().packageName;
2481            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2482                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2483                continue;
2484            }
2485
2486            if (best == null || cur.priority > best.priority) {
2487                best = cur;
2488            }
2489        }
2490
2491        if (best != null) {
2492            return best.getComponentInfo().getComponentName();
2493        } else {
2494            throw new RuntimeException("There must be at least one intent filter verifier");
2495        }
2496    }
2497
2498    private @Nullable ComponentName getEphemeralResolverLPr() {
2499        final String[] packageArray =
2500                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2501        if (packageArray.length == 0) {
2502            if (DEBUG_EPHEMERAL) {
2503                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2504            }
2505            return null;
2506        }
2507
2508        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2509        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2510                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2511
2512        final int N = resolvers.size();
2513        if (N == 0) {
2514            if (DEBUG_EPHEMERAL) {
2515                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2516            }
2517            return null;
2518        }
2519
2520        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2521        for (int i = 0; i < N; i++) {
2522            final ResolveInfo info = resolvers.get(i);
2523
2524            if (info.serviceInfo == null) {
2525                continue;
2526            }
2527
2528            final String packageName = info.serviceInfo.packageName;
2529            if (!possiblePackages.contains(packageName)) {
2530                if (DEBUG_EPHEMERAL) {
2531                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2532                            + " pkg: " + packageName + ", info:" + info);
2533                }
2534                continue;
2535            }
2536
2537            if (DEBUG_EPHEMERAL) {
2538                Slog.v(TAG, "Ephemeral resolver found;"
2539                        + " pkg: " + packageName + ", info:" + info);
2540            }
2541            return new ComponentName(packageName, info.serviceInfo.name);
2542        }
2543        if (DEBUG_EPHEMERAL) {
2544            Slog.v(TAG, "Ephemeral resolver NOT found");
2545        }
2546        return null;
2547    }
2548
2549    private @Nullable ComponentName getEphemeralInstallerLPr() {
2550        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2551        intent.addCategory(Intent.CATEGORY_DEFAULT);
2552        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2553
2554        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2555                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2556        if (matches.size() == 0) {
2557            return null;
2558        } else if (matches.size() == 1) {
2559            return matches.get(0).getComponentInfo().getComponentName();
2560        } else {
2561            throw new RuntimeException(
2562                    "There must be at most one ephemeral installer; found " + matches);
2563        }
2564    }
2565
2566    private void primeDomainVerificationsLPw(int userId) {
2567        if (DEBUG_DOMAIN_VERIFICATION) {
2568            Slog.d(TAG, "Priming domain verifications in user " + userId);
2569        }
2570
2571        SystemConfig systemConfig = SystemConfig.getInstance();
2572        ArraySet<String> packages = systemConfig.getLinkedApps();
2573        ArraySet<String> domains = new ArraySet<String>();
2574
2575        for (String packageName : packages) {
2576            PackageParser.Package pkg = mPackages.get(packageName);
2577            if (pkg != null) {
2578                if (!pkg.isSystemApp()) {
2579                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2580                    continue;
2581                }
2582
2583                domains.clear();
2584                for (PackageParser.Activity a : pkg.activities) {
2585                    for (ActivityIntentInfo filter : a.intents) {
2586                        if (hasValidDomains(filter)) {
2587                            domains.addAll(filter.getHostsList());
2588                        }
2589                    }
2590                }
2591
2592                if (domains.size() > 0) {
2593                    if (DEBUG_DOMAIN_VERIFICATION) {
2594                        Slog.v(TAG, "      + " + packageName);
2595                    }
2596                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2597                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2598                    // and then 'always' in the per-user state actually used for intent resolution.
2599                    final IntentFilterVerificationInfo ivi;
2600                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2601                            new ArrayList<String>(domains));
2602                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2603                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2604                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2605                } else {
2606                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2607                            + "' does not handle web links");
2608                }
2609            } else {
2610                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2611            }
2612        }
2613
2614        scheduleWritePackageRestrictionsLocked(userId);
2615        scheduleWriteSettingsLocked();
2616    }
2617
2618    private void applyFactoryDefaultBrowserLPw(int userId) {
2619        // The default browser app's package name is stored in a string resource,
2620        // with a product-specific overlay used for vendor customization.
2621        String browserPkg = mContext.getResources().getString(
2622                com.android.internal.R.string.default_browser);
2623        if (!TextUtils.isEmpty(browserPkg)) {
2624            // non-empty string => required to be a known package
2625            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2626            if (ps == null) {
2627                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2628                browserPkg = null;
2629            } else {
2630                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2631            }
2632        }
2633
2634        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2635        // default.  If there's more than one, just leave everything alone.
2636        if (browserPkg == null) {
2637            calculateDefaultBrowserLPw(userId);
2638        }
2639    }
2640
2641    private void calculateDefaultBrowserLPw(int userId) {
2642        List<String> allBrowsers = resolveAllBrowserApps(userId);
2643        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2644        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2645    }
2646
2647    private List<String> resolveAllBrowserApps(int userId) {
2648        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2649        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2650                PackageManager.MATCH_ALL, userId);
2651
2652        final int count = list.size();
2653        List<String> result = new ArrayList<String>(count);
2654        for (int i=0; i<count; i++) {
2655            ResolveInfo info = list.get(i);
2656            if (info.activityInfo == null
2657                    || !info.handleAllWebDataURI
2658                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2659                    || result.contains(info.activityInfo.packageName)) {
2660                continue;
2661            }
2662            result.add(info.activityInfo.packageName);
2663        }
2664
2665        return result;
2666    }
2667
2668    private boolean packageIsBrowser(String packageName, int userId) {
2669        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2670                PackageManager.MATCH_ALL, userId);
2671        final int N = list.size();
2672        for (int i = 0; i < N; i++) {
2673            ResolveInfo info = list.get(i);
2674            if (packageName.equals(info.activityInfo.packageName)) {
2675                return true;
2676            }
2677        }
2678        return false;
2679    }
2680
2681    private void checkDefaultBrowser() {
2682        final int myUserId = UserHandle.myUserId();
2683        final String packageName = getDefaultBrowserPackageName(myUserId);
2684        if (packageName != null) {
2685            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2686            if (info == null) {
2687                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2688                synchronized (mPackages) {
2689                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2690                }
2691            }
2692        }
2693    }
2694
2695    @Override
2696    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2697            throws RemoteException {
2698        try {
2699            return super.onTransact(code, data, reply, flags);
2700        } catch (RuntimeException e) {
2701            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2702                Slog.wtf(TAG, "Package Manager Crash", e);
2703            }
2704            throw e;
2705        }
2706    }
2707
2708    void cleanupInstallFailedPackage(PackageSetting ps) {
2709        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2710
2711        removeDataDirsLI(ps.volumeUuid, ps.name);
2712        if (ps.codePath != null) {
2713            if (ps.codePath.isDirectory()) {
2714                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2715            } else {
2716                ps.codePath.delete();
2717            }
2718        }
2719        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2720            if (ps.resourcePath.isDirectory()) {
2721                FileUtils.deleteContents(ps.resourcePath);
2722            }
2723            ps.resourcePath.delete();
2724        }
2725        mSettings.removePackageLPw(ps.name);
2726    }
2727
2728    static int[] appendInts(int[] cur, int[] add) {
2729        if (add == null) return cur;
2730        if (cur == null) return add;
2731        final int N = add.length;
2732        for (int i=0; i<N; i++) {
2733            cur = appendInt(cur, add[i]);
2734        }
2735        return cur;
2736    }
2737
2738    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2739        if (!sUserManager.exists(userId)) return null;
2740        final PackageSetting ps = (PackageSetting) p.mExtras;
2741        if (ps == null) {
2742            return null;
2743        }
2744
2745        final PermissionsState permissionsState = ps.getPermissionsState();
2746
2747        final int[] gids = permissionsState.computeGids(userId);
2748        final Set<String> permissions = permissionsState.getPermissions(userId);
2749        final PackageUserState state = ps.readUserState(userId);
2750
2751        return PackageParser.generatePackageInfo(p, gids, flags,
2752                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2753    }
2754
2755    @Override
2756    public void checkPackageStartable(String packageName, int userId) {
2757        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2758
2759        synchronized (mPackages) {
2760            final PackageSetting ps = mSettings.mPackages.get(packageName);
2761            if (ps == null) {
2762                throw new SecurityException("Package " + packageName + " was not found!");
2763            }
2764
2765            if (ps.frozen) {
2766                throw new SecurityException("Package " + packageName + " is currently frozen!");
2767            }
2768
2769            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2770                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2771                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2772            }
2773        }
2774    }
2775
2776    @Override
2777    public boolean isPackageAvailable(String packageName, int userId) {
2778        if (!sUserManager.exists(userId)) return false;
2779        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2780        synchronized (mPackages) {
2781            PackageParser.Package p = mPackages.get(packageName);
2782            if (p != null) {
2783                final PackageSetting ps = (PackageSetting) p.mExtras;
2784                if (ps != null) {
2785                    final PackageUserState state = ps.readUserState(userId);
2786                    if (state != null) {
2787                        return PackageParser.isAvailable(state);
2788                    }
2789                }
2790            }
2791        }
2792        return false;
2793    }
2794
2795    @Override
2796    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2797        if (!sUserManager.exists(userId)) return null;
2798        flags = updateFlagsForPackage(flags, userId, packageName);
2799        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2800        // reader
2801        synchronized (mPackages) {
2802            PackageParser.Package p = mPackages.get(packageName);
2803            if (DEBUG_PACKAGE_INFO)
2804                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2805            if (p != null) {
2806                return generatePackageInfo(p, flags, userId);
2807            }
2808            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2809                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2810            }
2811        }
2812        return null;
2813    }
2814
2815    @Override
2816    public String[] currentToCanonicalPackageNames(String[] names) {
2817        String[] out = new String[names.length];
2818        // reader
2819        synchronized (mPackages) {
2820            for (int i=names.length-1; i>=0; i--) {
2821                PackageSetting ps = mSettings.mPackages.get(names[i]);
2822                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2823            }
2824        }
2825        return out;
2826    }
2827
2828    @Override
2829    public String[] canonicalToCurrentPackageNames(String[] names) {
2830        String[] out = new String[names.length];
2831        // reader
2832        synchronized (mPackages) {
2833            for (int i=names.length-1; i>=0; i--) {
2834                String cur = mSettings.mRenamedPackages.get(names[i]);
2835                out[i] = cur != null ? cur : names[i];
2836            }
2837        }
2838        return out;
2839    }
2840
2841    @Override
2842    public int getPackageUid(String packageName, int flags, int userId) {
2843        if (!sUserManager.exists(userId)) return -1;
2844        flags = updateFlagsForPackage(flags, userId, packageName);
2845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2846
2847        // reader
2848        synchronized (mPackages) {
2849            final PackageParser.Package p = mPackages.get(packageName);
2850            if (p != null && p.isMatch(flags)) {
2851                return UserHandle.getUid(userId, p.applicationInfo.uid);
2852            }
2853            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2854                final PackageSetting ps = mSettings.mPackages.get(packageName);
2855                if (ps != null && ps.isMatch(flags)) {
2856                    return UserHandle.getUid(userId, ps.appId);
2857                }
2858            }
2859        }
2860
2861        return -1;
2862    }
2863
2864    @Override
2865    public int[] getPackageGids(String packageName, int flags, int userId) {
2866        if (!sUserManager.exists(userId)) return null;
2867        flags = updateFlagsForPackage(flags, userId, packageName);
2868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2869                "getPackageGids");
2870
2871        // reader
2872        synchronized (mPackages) {
2873            final PackageParser.Package p = mPackages.get(packageName);
2874            if (p != null && p.isMatch(flags)) {
2875                PackageSetting ps = (PackageSetting) p.mExtras;
2876                return ps.getPermissionsState().computeGids(userId);
2877            }
2878            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2879                final PackageSetting ps = mSettings.mPackages.get(packageName);
2880                if (ps != null && ps.isMatch(flags)) {
2881                    return ps.getPermissionsState().computeGids(userId);
2882                }
2883            }
2884        }
2885
2886        return null;
2887    }
2888
2889    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2890        if (bp.perm != null) {
2891            return PackageParser.generatePermissionInfo(bp.perm, flags);
2892        }
2893        PermissionInfo pi = new PermissionInfo();
2894        pi.name = bp.name;
2895        pi.packageName = bp.sourcePackage;
2896        pi.nonLocalizedLabel = bp.name;
2897        pi.protectionLevel = bp.protectionLevel;
2898        return pi;
2899    }
2900
2901    @Override
2902    public PermissionInfo getPermissionInfo(String name, int flags) {
2903        // reader
2904        synchronized (mPackages) {
2905            final BasePermission p = mSettings.mPermissions.get(name);
2906            if (p != null) {
2907                return generatePermissionInfo(p, flags);
2908            }
2909            return null;
2910        }
2911    }
2912
2913    @Override
2914    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2915        // reader
2916        synchronized (mPackages) {
2917            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2918            for (BasePermission p : mSettings.mPermissions.values()) {
2919                if (group == null) {
2920                    if (p.perm == null || p.perm.info.group == null) {
2921                        out.add(generatePermissionInfo(p, flags));
2922                    }
2923                } else {
2924                    if (p.perm != null && group.equals(p.perm.info.group)) {
2925                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2926                    }
2927                }
2928            }
2929
2930            if (out.size() > 0) {
2931                return out;
2932            }
2933            return mPermissionGroups.containsKey(group) ? out : null;
2934        }
2935    }
2936
2937    @Override
2938    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2939        // reader
2940        synchronized (mPackages) {
2941            return PackageParser.generatePermissionGroupInfo(
2942                    mPermissionGroups.get(name), flags);
2943        }
2944    }
2945
2946    @Override
2947    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2948        // reader
2949        synchronized (mPackages) {
2950            final int N = mPermissionGroups.size();
2951            ArrayList<PermissionGroupInfo> out
2952                    = new ArrayList<PermissionGroupInfo>(N);
2953            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2954                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2955            }
2956            return out;
2957        }
2958    }
2959
2960    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2961            int userId) {
2962        if (!sUserManager.exists(userId)) return null;
2963        PackageSetting ps = mSettings.mPackages.get(packageName);
2964        if (ps != null) {
2965            if (ps.pkg == null) {
2966                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2967                        flags, userId);
2968                if (pInfo != null) {
2969                    return pInfo.applicationInfo;
2970                }
2971                return null;
2972            }
2973            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2974                    ps.readUserState(userId), userId);
2975        }
2976        return null;
2977    }
2978
2979    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2980            int userId) {
2981        if (!sUserManager.exists(userId)) return null;
2982        PackageSetting ps = mSettings.mPackages.get(packageName);
2983        if (ps != null) {
2984            PackageParser.Package pkg = ps.pkg;
2985            if (pkg == null) {
2986                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2987                    return null;
2988                }
2989                // Only data remains, so we aren't worried about code paths
2990                pkg = new PackageParser.Package(packageName);
2991                pkg.applicationInfo.packageName = packageName;
2992                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2993                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2994                pkg.applicationInfo.uid = ps.appId;
2995                pkg.applicationInfo.initForUser(userId);
2996                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2997                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2998            }
2999            return generatePackageInfo(pkg, flags, userId);
3000        }
3001        return null;
3002    }
3003
3004    @Override
3005    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        flags = updateFlagsForApplication(flags, userId, packageName);
3008        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3009        // writer
3010        synchronized (mPackages) {
3011            PackageParser.Package p = mPackages.get(packageName);
3012            if (DEBUG_PACKAGE_INFO) Log.v(
3013                    TAG, "getApplicationInfo " + packageName
3014                    + ": " + p);
3015            if (p != null) {
3016                PackageSetting ps = mSettings.mPackages.get(packageName);
3017                if (ps == null) return null;
3018                // Note: isEnabledLP() does not apply here - always return info
3019                return PackageParser.generateApplicationInfo(
3020                        p, flags, ps.readUserState(userId), userId);
3021            }
3022            if ("android".equals(packageName)||"system".equals(packageName)) {
3023                return mAndroidApplication;
3024            }
3025            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3026                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3027            }
3028        }
3029        return null;
3030    }
3031
3032    @Override
3033    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3034            final IPackageDataObserver observer) {
3035        mContext.enforceCallingOrSelfPermission(
3036                android.Manifest.permission.CLEAR_APP_CACHE, null);
3037        // Queue up an async operation since clearing cache may take a little while.
3038        mHandler.post(new Runnable() {
3039            public void run() {
3040                mHandler.removeCallbacks(this);
3041                int retCode = -1;
3042                synchronized (mInstallLock) {
3043                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3044                    if (retCode < 0) {
3045                        Slog.w(TAG, "Couldn't clear application caches");
3046                    }
3047                }
3048                if (observer != null) {
3049                    try {
3050                        observer.onRemoveCompleted(null, (retCode >= 0));
3051                    } catch (RemoteException e) {
3052                        Slog.w(TAG, "RemoveException when invoking call back");
3053                    }
3054                }
3055            }
3056        });
3057    }
3058
3059    @Override
3060    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3061            final IntentSender pi) {
3062        mContext.enforceCallingOrSelfPermission(
3063                android.Manifest.permission.CLEAR_APP_CACHE, null);
3064        // Queue up an async operation since clearing cache may take a little while.
3065        mHandler.post(new Runnable() {
3066            public void run() {
3067                mHandler.removeCallbacks(this);
3068                int retCode = -1;
3069                synchronized (mInstallLock) {
3070                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3071                    if (retCode < 0) {
3072                        Slog.w(TAG, "Couldn't clear application caches");
3073                    }
3074                }
3075                if(pi != null) {
3076                    try {
3077                        // Callback via pending intent
3078                        int code = (retCode >= 0) ? 1 : 0;
3079                        pi.sendIntent(null, code, null,
3080                                null, null);
3081                    } catch (SendIntentException e1) {
3082                        Slog.i(TAG, "Failed to send pending intent");
3083                    }
3084                }
3085            }
3086        });
3087    }
3088
3089    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3090        synchronized (mInstallLock) {
3091            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3092                throw new IOException("Failed to free enough space");
3093            }
3094        }
3095    }
3096
3097    /**
3098     * Return if the user key is currently unlocked.
3099     */
3100    private boolean isUserKeyUnlocked(int userId) {
3101        if (StorageManager.isFileBasedEncryptionEnabled()) {
3102            final IMountService mount = IMountService.Stub
3103                    .asInterface(ServiceManager.getService("mount"));
3104            if (mount == null) {
3105                Slog.w(TAG, "Early during boot, assuming locked");
3106                return false;
3107            }
3108            final long token = Binder.clearCallingIdentity();
3109            try {
3110                return mount.isUserKeyUnlocked(userId);
3111            } catch (RemoteException e) {
3112                throw e.rethrowAsRuntimeException();
3113            } finally {
3114                Binder.restoreCallingIdentity(token);
3115            }
3116        } else {
3117            return true;
3118        }
3119    }
3120
3121    /**
3122     * Update given flags based on encryption status of current user.
3123     */
3124    private int updateFlagsForEncryption(int flags, int userId) {
3125        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3126                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3127            // Caller expressed an explicit opinion about what encryption
3128            // aware/unaware components they want to see, so fall through and
3129            // give them what they want
3130        } else {
3131            // Caller expressed no opinion, so match based on user state
3132            if (isUserKeyUnlocked(userId)) {
3133                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3134            } else {
3135                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3136            }
3137        }
3138        return flags;
3139    }
3140
3141    /**
3142     * Update given flags when being used to request {@link PackageInfo}.
3143     */
3144    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3145        boolean triaged = true;
3146        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3147                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3148            // Caller is asking for component details, so they'd better be
3149            // asking for specific encryption matching behavior, or be triaged
3150            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3151                    | PackageManager.MATCH_ENCRYPTION_AWARE
3152                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3153                triaged = false;
3154            }
3155        }
3156        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3157                | PackageManager.MATCH_SYSTEM_ONLY
3158                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3159            triaged = false;
3160        }
3161        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3162            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3163                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3164        }
3165        return updateFlagsForEncryption(flags, userId);
3166    }
3167
3168    /**
3169     * Update given flags when being used to request {@link ApplicationInfo}.
3170     */
3171    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3172        return updateFlagsForPackage(flags, userId, cookie);
3173    }
3174
3175    /**
3176     * Update given flags when being used to request {@link ComponentInfo}.
3177     */
3178    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3179        if (cookie instanceof Intent) {
3180            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3181                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3182            }
3183        }
3184
3185        boolean triaged = true;
3186        // Caller is asking for component details, so they'd better be
3187        // asking for specific encryption matching behavior, or be triaged
3188        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3189                | PackageManager.MATCH_ENCRYPTION_AWARE
3190                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3191            triaged = false;
3192        }
3193        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3194            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3195                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3196        }
3197        return updateFlagsForEncryption(flags, userId);
3198    }
3199
3200    /**
3201     * Update given flags when being used to request {@link ResolveInfo}.
3202     */
3203    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3204        return updateFlagsForComponent(flags, userId, cookie);
3205    }
3206
3207    @Override
3208    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3209        if (!sUserManager.exists(userId)) return null;
3210        flags = updateFlagsForComponent(flags, userId, component);
3211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3212        synchronized (mPackages) {
3213            PackageParser.Activity a = mActivities.mActivities.get(component);
3214
3215            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3216            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3218                if (ps == null) return null;
3219                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3220                        userId);
3221            }
3222            if (mResolveComponentName.equals(component)) {
3223                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3224                        new PackageUserState(), userId);
3225            }
3226        }
3227        return null;
3228    }
3229
3230    @Override
3231    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3232            String resolvedType) {
3233        synchronized (mPackages) {
3234            if (component.equals(mResolveComponentName)) {
3235                // The resolver supports EVERYTHING!
3236                return true;
3237            }
3238            PackageParser.Activity a = mActivities.mActivities.get(component);
3239            if (a == null) {
3240                return false;
3241            }
3242            for (int i=0; i<a.intents.size(); i++) {
3243                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3244                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3245                    return true;
3246                }
3247            }
3248            return false;
3249        }
3250    }
3251
3252    @Override
3253    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3254        if (!sUserManager.exists(userId)) return null;
3255        flags = updateFlagsForComponent(flags, userId, component);
3256        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3257        synchronized (mPackages) {
3258            PackageParser.Activity a = mReceivers.mActivities.get(component);
3259            if (DEBUG_PACKAGE_INFO) Log.v(
3260                TAG, "getReceiverInfo " + component + ": " + a);
3261            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3262                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3263                if (ps == null) return null;
3264                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3265                        userId);
3266            }
3267        }
3268        return null;
3269    }
3270
3271    @Override
3272    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3273        if (!sUserManager.exists(userId)) return null;
3274        flags = updateFlagsForComponent(flags, userId, component);
3275        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3276        synchronized (mPackages) {
3277            PackageParser.Service s = mServices.mServices.get(component);
3278            if (DEBUG_PACKAGE_INFO) Log.v(
3279                TAG, "getServiceInfo " + component + ": " + s);
3280            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3281                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3282                if (ps == null) return null;
3283                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3284                        userId);
3285            }
3286        }
3287        return null;
3288    }
3289
3290    @Override
3291    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3292        if (!sUserManager.exists(userId)) return null;
3293        flags = updateFlagsForComponent(flags, userId, component);
3294        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3295        synchronized (mPackages) {
3296            PackageParser.Provider p = mProviders.mProviders.get(component);
3297            if (DEBUG_PACKAGE_INFO) Log.v(
3298                TAG, "getProviderInfo " + component + ": " + p);
3299            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3300                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3301                if (ps == null) return null;
3302                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3303                        userId);
3304            }
3305        }
3306        return null;
3307    }
3308
3309    @Override
3310    public String[] getSystemSharedLibraryNames() {
3311        Set<String> libSet;
3312        synchronized (mPackages) {
3313            libSet = mSharedLibraries.keySet();
3314            int size = libSet.size();
3315            if (size > 0) {
3316                String[] libs = new String[size];
3317                libSet.toArray(libs);
3318                return libs;
3319            }
3320        }
3321        return null;
3322    }
3323
3324    /**
3325     * @hide
3326     */
3327    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3328        synchronized (mPackages) {
3329            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3330            if (lib != null && lib.apk != null) {
3331                return mPackages.get(lib.apk);
3332            }
3333        }
3334        return null;
3335    }
3336
3337    @Override
3338    public FeatureInfo[] getSystemAvailableFeatures() {
3339        Collection<FeatureInfo> featSet;
3340        synchronized (mPackages) {
3341            featSet = mAvailableFeatures.values();
3342            int size = featSet.size();
3343            if (size > 0) {
3344                FeatureInfo[] features = new FeatureInfo[size+1];
3345                featSet.toArray(features);
3346                FeatureInfo fi = new FeatureInfo();
3347                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3348                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3349                features[size] = fi;
3350                return features;
3351            }
3352        }
3353        return null;
3354    }
3355
3356    @Override
3357    public boolean hasSystemFeature(String name) {
3358        synchronized (mPackages) {
3359            return mAvailableFeatures.containsKey(name);
3360        }
3361    }
3362
3363    @Override
3364    public int checkPermission(String permName, String pkgName, int userId) {
3365        if (!sUserManager.exists(userId)) {
3366            return PackageManager.PERMISSION_DENIED;
3367        }
3368
3369        synchronized (mPackages) {
3370            final PackageParser.Package p = mPackages.get(pkgName);
3371            if (p != null && p.mExtras != null) {
3372                final PackageSetting ps = (PackageSetting) p.mExtras;
3373                final PermissionsState permissionsState = ps.getPermissionsState();
3374                if (permissionsState.hasPermission(permName, userId)) {
3375                    return PackageManager.PERMISSION_GRANTED;
3376                }
3377                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3378                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3379                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3380                    return PackageManager.PERMISSION_GRANTED;
3381                }
3382            }
3383        }
3384
3385        return PackageManager.PERMISSION_DENIED;
3386    }
3387
3388    @Override
3389    public int checkUidPermission(String permName, int uid) {
3390        final int userId = UserHandle.getUserId(uid);
3391
3392        if (!sUserManager.exists(userId)) {
3393            return PackageManager.PERMISSION_DENIED;
3394        }
3395
3396        synchronized (mPackages) {
3397            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3398            if (obj != null) {
3399                final SettingBase ps = (SettingBase) obj;
3400                final PermissionsState permissionsState = ps.getPermissionsState();
3401                if (permissionsState.hasPermission(permName, userId)) {
3402                    return PackageManager.PERMISSION_GRANTED;
3403                }
3404                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3405                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3406                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3407                    return PackageManager.PERMISSION_GRANTED;
3408                }
3409            } else {
3410                ArraySet<String> perms = mSystemPermissions.get(uid);
3411                if (perms != null) {
3412                    if (perms.contains(permName)) {
3413                        return PackageManager.PERMISSION_GRANTED;
3414                    }
3415                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3416                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3417                        return PackageManager.PERMISSION_GRANTED;
3418                    }
3419                }
3420            }
3421        }
3422
3423        return PackageManager.PERMISSION_DENIED;
3424    }
3425
3426    @Override
3427    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3428        if (UserHandle.getCallingUserId() != userId) {
3429            mContext.enforceCallingPermission(
3430                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3431                    "isPermissionRevokedByPolicy for user " + userId);
3432        }
3433
3434        if (checkPermission(permission, packageName, userId)
3435                == PackageManager.PERMISSION_GRANTED) {
3436            return false;
3437        }
3438
3439        final long identity = Binder.clearCallingIdentity();
3440        try {
3441            final int flags = getPermissionFlags(permission, packageName, userId);
3442            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3443        } finally {
3444            Binder.restoreCallingIdentity(identity);
3445        }
3446    }
3447
3448    @Override
3449    public String getPermissionControllerPackageName() {
3450        synchronized (mPackages) {
3451            return mRequiredInstallerPackage;
3452        }
3453    }
3454
3455    /**
3456     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3457     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3458     * @param checkShell TODO(yamasani):
3459     * @param message the message to log on security exception
3460     */
3461    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3462            boolean checkShell, String message) {
3463        if (userId < 0) {
3464            throw new IllegalArgumentException("Invalid userId " + userId);
3465        }
3466        if (checkShell) {
3467            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3468        }
3469        if (userId == UserHandle.getUserId(callingUid)) return;
3470        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3471            if (requireFullPermission) {
3472                mContext.enforceCallingOrSelfPermission(
3473                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3474            } else {
3475                try {
3476                    mContext.enforceCallingOrSelfPermission(
3477                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3478                } catch (SecurityException se) {
3479                    mContext.enforceCallingOrSelfPermission(
3480                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3481                }
3482            }
3483        }
3484    }
3485
3486    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3487        if (callingUid == Process.SHELL_UID) {
3488            if (userHandle >= 0
3489                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3490                throw new SecurityException("Shell does not have permission to access user "
3491                        + userHandle);
3492            } else if (userHandle < 0) {
3493                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3494                        + Debug.getCallers(3));
3495            }
3496        }
3497    }
3498
3499    private BasePermission findPermissionTreeLP(String permName) {
3500        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3501            if (permName.startsWith(bp.name) &&
3502                    permName.length() > bp.name.length() &&
3503                    permName.charAt(bp.name.length()) == '.') {
3504                return bp;
3505            }
3506        }
3507        return null;
3508    }
3509
3510    private BasePermission checkPermissionTreeLP(String permName) {
3511        if (permName != null) {
3512            BasePermission bp = findPermissionTreeLP(permName);
3513            if (bp != null) {
3514                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3515                    return bp;
3516                }
3517                throw new SecurityException("Calling uid "
3518                        + Binder.getCallingUid()
3519                        + " is not allowed to add to permission tree "
3520                        + bp.name + " owned by uid " + bp.uid);
3521            }
3522        }
3523        throw new SecurityException("No permission tree found for " + permName);
3524    }
3525
3526    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3527        if (s1 == null) {
3528            return s2 == null;
3529        }
3530        if (s2 == null) {
3531            return false;
3532        }
3533        if (s1.getClass() != s2.getClass()) {
3534            return false;
3535        }
3536        return s1.equals(s2);
3537    }
3538
3539    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3540        if (pi1.icon != pi2.icon) return false;
3541        if (pi1.logo != pi2.logo) return false;
3542        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3543        if (!compareStrings(pi1.name, pi2.name)) return false;
3544        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3545        // We'll take care of setting this one.
3546        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3547        // These are not currently stored in settings.
3548        //if (!compareStrings(pi1.group, pi2.group)) return false;
3549        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3550        //if (pi1.labelRes != pi2.labelRes) return false;
3551        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3552        return true;
3553    }
3554
3555    int permissionInfoFootprint(PermissionInfo info) {
3556        int size = info.name.length();
3557        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3558        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3559        return size;
3560    }
3561
3562    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3563        int size = 0;
3564        for (BasePermission perm : mSettings.mPermissions.values()) {
3565            if (perm.uid == tree.uid) {
3566                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3567            }
3568        }
3569        return size;
3570    }
3571
3572    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3573        // We calculate the max size of permissions defined by this uid and throw
3574        // if that plus the size of 'info' would exceed our stated maximum.
3575        if (tree.uid != Process.SYSTEM_UID) {
3576            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3577            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3578                throw new SecurityException("Permission tree size cap exceeded");
3579            }
3580        }
3581    }
3582
3583    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3584        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3585            throw new SecurityException("Label must be specified in permission");
3586        }
3587        BasePermission tree = checkPermissionTreeLP(info.name);
3588        BasePermission bp = mSettings.mPermissions.get(info.name);
3589        boolean added = bp == null;
3590        boolean changed = true;
3591        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3592        if (added) {
3593            enforcePermissionCapLocked(info, tree);
3594            bp = new BasePermission(info.name, tree.sourcePackage,
3595                    BasePermission.TYPE_DYNAMIC);
3596        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3597            throw new SecurityException(
3598                    "Not allowed to modify non-dynamic permission "
3599                    + info.name);
3600        } else {
3601            if (bp.protectionLevel == fixedLevel
3602                    && bp.perm.owner.equals(tree.perm.owner)
3603                    && bp.uid == tree.uid
3604                    && comparePermissionInfos(bp.perm.info, info)) {
3605                changed = false;
3606            }
3607        }
3608        bp.protectionLevel = fixedLevel;
3609        info = new PermissionInfo(info);
3610        info.protectionLevel = fixedLevel;
3611        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3612        bp.perm.info.packageName = tree.perm.info.packageName;
3613        bp.uid = tree.uid;
3614        if (added) {
3615            mSettings.mPermissions.put(info.name, bp);
3616        }
3617        if (changed) {
3618            if (!async) {
3619                mSettings.writeLPr();
3620            } else {
3621                scheduleWriteSettingsLocked();
3622            }
3623        }
3624        return added;
3625    }
3626
3627    @Override
3628    public boolean addPermission(PermissionInfo info) {
3629        synchronized (mPackages) {
3630            return addPermissionLocked(info, false);
3631        }
3632    }
3633
3634    @Override
3635    public boolean addPermissionAsync(PermissionInfo info) {
3636        synchronized (mPackages) {
3637            return addPermissionLocked(info, true);
3638        }
3639    }
3640
3641    @Override
3642    public void removePermission(String name) {
3643        synchronized (mPackages) {
3644            checkPermissionTreeLP(name);
3645            BasePermission bp = mSettings.mPermissions.get(name);
3646            if (bp != null) {
3647                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3648                    throw new SecurityException(
3649                            "Not allowed to modify non-dynamic permission "
3650                            + name);
3651                }
3652                mSettings.mPermissions.remove(name);
3653                mSettings.writeLPr();
3654            }
3655        }
3656    }
3657
3658    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3659            BasePermission bp) {
3660        int index = pkg.requestedPermissions.indexOf(bp.name);
3661        if (index == -1) {
3662            throw new SecurityException("Package " + pkg.packageName
3663                    + " has not requested permission " + bp.name);
3664        }
3665        if (!bp.isRuntime() && !bp.isDevelopment()) {
3666            throw new SecurityException("Permission " + bp.name
3667                    + " is not a changeable permission type");
3668        }
3669    }
3670
3671    @Override
3672    public void grantRuntimePermission(String packageName, String name, final int userId) {
3673        if (!sUserManager.exists(userId)) {
3674            Log.e(TAG, "No such user:" + userId);
3675            return;
3676        }
3677
3678        mContext.enforceCallingOrSelfPermission(
3679                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3680                "grantRuntimePermission");
3681
3682        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3683                "grantRuntimePermission");
3684
3685        final int uid;
3686        final SettingBase sb;
3687
3688        synchronized (mPackages) {
3689            final PackageParser.Package pkg = mPackages.get(packageName);
3690            if (pkg == null) {
3691                throw new IllegalArgumentException("Unknown package: " + packageName);
3692            }
3693
3694            final BasePermission bp = mSettings.mPermissions.get(name);
3695            if (bp == null) {
3696                throw new IllegalArgumentException("Unknown permission: " + name);
3697            }
3698
3699            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3700
3701            // If a permission review is required for legacy apps we represent
3702            // their permissions as always granted runtime ones since we need
3703            // to keep the review required permission flag per user while an
3704            // install permission's state is shared across all users.
3705            if (Build.PERMISSIONS_REVIEW_REQUIRED
3706                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3707                    && bp.isRuntime()) {
3708                return;
3709            }
3710
3711            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3712            sb = (SettingBase) pkg.mExtras;
3713            if (sb == null) {
3714                throw new IllegalArgumentException("Unknown package: " + packageName);
3715            }
3716
3717            final PermissionsState permissionsState = sb.getPermissionsState();
3718
3719            final int flags = permissionsState.getPermissionFlags(name, userId);
3720            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3721                throw new SecurityException("Cannot grant system fixed permission "
3722                        + name + " for package " + packageName);
3723            }
3724
3725            if (bp.isDevelopment()) {
3726                // Development permissions must be handled specially, since they are not
3727                // normal runtime permissions.  For now they apply to all users.
3728                if (permissionsState.grantInstallPermission(bp) !=
3729                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3730                    scheduleWriteSettingsLocked();
3731                }
3732                return;
3733            }
3734
3735            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3736                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3737                return;
3738            }
3739
3740            final int result = permissionsState.grantRuntimePermission(bp, userId);
3741            switch (result) {
3742                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3743                    return;
3744                }
3745
3746                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3747                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3748                    mHandler.post(new Runnable() {
3749                        @Override
3750                        public void run() {
3751                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3752                        }
3753                    });
3754                }
3755                break;
3756            }
3757
3758            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3759
3760            // Not critical if that is lost - app has to request again.
3761            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3762        }
3763
3764        // Only need to do this if user is initialized. Otherwise it's a new user
3765        // and there are no processes running as the user yet and there's no need
3766        // to make an expensive call to remount processes for the changed permissions.
3767        if (READ_EXTERNAL_STORAGE.equals(name)
3768                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3769            final long token = Binder.clearCallingIdentity();
3770            try {
3771                if (sUserManager.isInitialized(userId)) {
3772                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3773                            MountServiceInternal.class);
3774                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3775                }
3776            } finally {
3777                Binder.restoreCallingIdentity(token);
3778            }
3779        }
3780    }
3781
3782    @Override
3783    public void revokeRuntimePermission(String packageName, String name, int userId) {
3784        if (!sUserManager.exists(userId)) {
3785            Log.e(TAG, "No such user:" + userId);
3786            return;
3787        }
3788
3789        mContext.enforceCallingOrSelfPermission(
3790                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3791                "revokeRuntimePermission");
3792
3793        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3794                "revokeRuntimePermission");
3795
3796        final int appId;
3797
3798        synchronized (mPackages) {
3799            final PackageParser.Package pkg = mPackages.get(packageName);
3800            if (pkg == null) {
3801                throw new IllegalArgumentException("Unknown package: " + packageName);
3802            }
3803
3804            final BasePermission bp = mSettings.mPermissions.get(name);
3805            if (bp == null) {
3806                throw new IllegalArgumentException("Unknown permission: " + name);
3807            }
3808
3809            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3810
3811            // If a permission review is required for legacy apps we represent
3812            // their permissions as always granted runtime ones since we need
3813            // to keep the review required permission flag per user while an
3814            // install permission's state is shared across all users.
3815            if (Build.PERMISSIONS_REVIEW_REQUIRED
3816                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3817                    && bp.isRuntime()) {
3818                return;
3819            }
3820
3821            SettingBase sb = (SettingBase) pkg.mExtras;
3822            if (sb == null) {
3823                throw new IllegalArgumentException("Unknown package: " + packageName);
3824            }
3825
3826            final PermissionsState permissionsState = sb.getPermissionsState();
3827
3828            final int flags = permissionsState.getPermissionFlags(name, userId);
3829            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3830                throw new SecurityException("Cannot revoke system fixed permission "
3831                        + name + " for package " + packageName);
3832            }
3833
3834            if (bp.isDevelopment()) {
3835                // Development permissions must be handled specially, since they are not
3836                // normal runtime permissions.  For now they apply to all users.
3837                if (permissionsState.revokeInstallPermission(bp) !=
3838                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3839                    scheduleWriteSettingsLocked();
3840                }
3841                return;
3842            }
3843
3844            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3845                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3846                return;
3847            }
3848
3849            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3850
3851            // Critical, after this call app should never have the permission.
3852            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3853
3854            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3855        }
3856
3857        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3858    }
3859
3860    @Override
3861    public void resetRuntimePermissions() {
3862        mContext.enforceCallingOrSelfPermission(
3863                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3864                "revokeRuntimePermission");
3865
3866        int callingUid = Binder.getCallingUid();
3867        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3868            mContext.enforceCallingOrSelfPermission(
3869                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3870                    "resetRuntimePermissions");
3871        }
3872
3873        synchronized (mPackages) {
3874            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3875            for (int userId : UserManagerService.getInstance().getUserIds()) {
3876                final int packageCount = mPackages.size();
3877                for (int i = 0; i < packageCount; i++) {
3878                    PackageParser.Package pkg = mPackages.valueAt(i);
3879                    if (!(pkg.mExtras instanceof PackageSetting)) {
3880                        continue;
3881                    }
3882                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3883                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3884                }
3885            }
3886        }
3887    }
3888
3889    @Override
3890    public int getPermissionFlags(String name, String packageName, int userId) {
3891        if (!sUserManager.exists(userId)) {
3892            return 0;
3893        }
3894
3895        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3896
3897        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3898                "getPermissionFlags");
3899
3900        synchronized (mPackages) {
3901            final PackageParser.Package pkg = mPackages.get(packageName);
3902            if (pkg == null) {
3903                throw new IllegalArgumentException("Unknown package: " + packageName);
3904            }
3905
3906            final BasePermission bp = mSettings.mPermissions.get(name);
3907            if (bp == null) {
3908                throw new IllegalArgumentException("Unknown permission: " + name);
3909            }
3910
3911            SettingBase sb = (SettingBase) pkg.mExtras;
3912            if (sb == null) {
3913                throw new IllegalArgumentException("Unknown package: " + packageName);
3914            }
3915
3916            PermissionsState permissionsState = sb.getPermissionsState();
3917            return permissionsState.getPermissionFlags(name, userId);
3918        }
3919    }
3920
3921    @Override
3922    public void updatePermissionFlags(String name, String packageName, int flagMask,
3923            int flagValues, int userId) {
3924        if (!sUserManager.exists(userId)) {
3925            return;
3926        }
3927
3928        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3929
3930        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3931                "updatePermissionFlags");
3932
3933        // Only the system can change these flags and nothing else.
3934        if (getCallingUid() != Process.SYSTEM_UID) {
3935            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3936            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3937            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3938            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3939            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3940        }
3941
3942        synchronized (mPackages) {
3943            final PackageParser.Package pkg = mPackages.get(packageName);
3944            if (pkg == null) {
3945                throw new IllegalArgumentException("Unknown package: " + packageName);
3946            }
3947
3948            final BasePermission bp = mSettings.mPermissions.get(name);
3949            if (bp == null) {
3950                throw new IllegalArgumentException("Unknown permission: " + name);
3951            }
3952
3953            SettingBase sb = (SettingBase) pkg.mExtras;
3954            if (sb == null) {
3955                throw new IllegalArgumentException("Unknown package: " + packageName);
3956            }
3957
3958            PermissionsState permissionsState = sb.getPermissionsState();
3959
3960            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3961
3962            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3963                // Install and runtime permissions are stored in different places,
3964                // so figure out what permission changed and persist the change.
3965                if (permissionsState.getInstallPermissionState(name) != null) {
3966                    scheduleWriteSettingsLocked();
3967                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3968                        || hadState) {
3969                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3970                }
3971            }
3972        }
3973    }
3974
3975    /**
3976     * Update the permission flags for all packages and runtime permissions of a user in order
3977     * to allow device or profile owner to remove POLICY_FIXED.
3978     */
3979    @Override
3980    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3981        if (!sUserManager.exists(userId)) {
3982            return;
3983        }
3984
3985        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3986
3987        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3988                "updatePermissionFlagsForAllApps");
3989
3990        // Only the system can change system fixed flags.
3991        if (getCallingUid() != Process.SYSTEM_UID) {
3992            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3993            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3994        }
3995
3996        synchronized (mPackages) {
3997            boolean changed = false;
3998            final int packageCount = mPackages.size();
3999            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4000                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4001                SettingBase sb = (SettingBase) pkg.mExtras;
4002                if (sb == null) {
4003                    continue;
4004                }
4005                PermissionsState permissionsState = sb.getPermissionsState();
4006                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4007                        userId, flagMask, flagValues);
4008            }
4009            if (changed) {
4010                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4011            }
4012        }
4013    }
4014
4015    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4016        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4017                != PackageManager.PERMISSION_GRANTED
4018            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4019                != PackageManager.PERMISSION_GRANTED) {
4020            throw new SecurityException(message + " requires "
4021                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4022                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4023        }
4024    }
4025
4026    @Override
4027    public boolean shouldShowRequestPermissionRationale(String permissionName,
4028            String packageName, int userId) {
4029        if (UserHandle.getCallingUserId() != userId) {
4030            mContext.enforceCallingPermission(
4031                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4032                    "canShowRequestPermissionRationale for user " + userId);
4033        }
4034
4035        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4036        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4037            return false;
4038        }
4039
4040        if (checkPermission(permissionName, packageName, userId)
4041                == PackageManager.PERMISSION_GRANTED) {
4042            return false;
4043        }
4044
4045        final int flags;
4046
4047        final long identity = Binder.clearCallingIdentity();
4048        try {
4049            flags = getPermissionFlags(permissionName,
4050                    packageName, userId);
4051        } finally {
4052            Binder.restoreCallingIdentity(identity);
4053        }
4054
4055        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4056                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4057                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4058
4059        if ((flags & fixedFlags) != 0) {
4060            return false;
4061        }
4062
4063        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4064    }
4065
4066    @Override
4067    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4068        mContext.enforceCallingOrSelfPermission(
4069                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4070                "addOnPermissionsChangeListener");
4071
4072        synchronized (mPackages) {
4073            mOnPermissionChangeListeners.addListenerLocked(listener);
4074        }
4075    }
4076
4077    @Override
4078    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4079        synchronized (mPackages) {
4080            mOnPermissionChangeListeners.removeListenerLocked(listener);
4081        }
4082    }
4083
4084    @Override
4085    public boolean isProtectedBroadcast(String actionName) {
4086        synchronized (mPackages) {
4087            if (mProtectedBroadcasts.contains(actionName)) {
4088                return true;
4089            } else if (actionName != null) {
4090                // TODO: remove these terrible hacks
4091                if (actionName.startsWith("android.net.netmon.lingerExpired")
4092                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4093                    return true;
4094                }
4095            }
4096        }
4097        return false;
4098    }
4099
4100    @Override
4101    public int checkSignatures(String pkg1, String pkg2) {
4102        synchronized (mPackages) {
4103            final PackageParser.Package p1 = mPackages.get(pkg1);
4104            final PackageParser.Package p2 = mPackages.get(pkg2);
4105            if (p1 == null || p1.mExtras == null
4106                    || p2 == null || p2.mExtras == null) {
4107                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4108            }
4109            return compareSignatures(p1.mSignatures, p2.mSignatures);
4110        }
4111    }
4112
4113    @Override
4114    public int checkUidSignatures(int uid1, int uid2) {
4115        // Map to base uids.
4116        uid1 = UserHandle.getAppId(uid1);
4117        uid2 = UserHandle.getAppId(uid2);
4118        // reader
4119        synchronized (mPackages) {
4120            Signature[] s1;
4121            Signature[] s2;
4122            Object obj = mSettings.getUserIdLPr(uid1);
4123            if (obj != null) {
4124                if (obj instanceof SharedUserSetting) {
4125                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4126                } else if (obj instanceof PackageSetting) {
4127                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4128                } else {
4129                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4130                }
4131            } else {
4132                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4133            }
4134            obj = mSettings.getUserIdLPr(uid2);
4135            if (obj != null) {
4136                if (obj instanceof SharedUserSetting) {
4137                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4138                } else if (obj instanceof PackageSetting) {
4139                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4140                } else {
4141                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4142                }
4143            } else {
4144                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4145            }
4146            return compareSignatures(s1, s2);
4147        }
4148    }
4149
4150    private void killUid(int appId, int userId, String reason) {
4151        final long identity = Binder.clearCallingIdentity();
4152        try {
4153            IActivityManager am = ActivityManagerNative.getDefault();
4154            if (am != null) {
4155                try {
4156                    am.killUid(appId, userId, reason);
4157                } catch (RemoteException e) {
4158                    /* ignore - same process */
4159                }
4160            }
4161        } finally {
4162            Binder.restoreCallingIdentity(identity);
4163        }
4164    }
4165
4166    /**
4167     * Compares two sets of signatures. Returns:
4168     * <br />
4169     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4170     * <br />
4171     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4172     * <br />
4173     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4174     * <br />
4175     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4176     * <br />
4177     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4178     */
4179    static int compareSignatures(Signature[] s1, Signature[] s2) {
4180        if (s1 == null) {
4181            return s2 == null
4182                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4183                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4184        }
4185
4186        if (s2 == null) {
4187            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4188        }
4189
4190        if (s1.length != s2.length) {
4191            return PackageManager.SIGNATURE_NO_MATCH;
4192        }
4193
4194        // Since both signature sets are of size 1, we can compare without HashSets.
4195        if (s1.length == 1) {
4196            return s1[0].equals(s2[0]) ?
4197                    PackageManager.SIGNATURE_MATCH :
4198                    PackageManager.SIGNATURE_NO_MATCH;
4199        }
4200
4201        ArraySet<Signature> set1 = new ArraySet<Signature>();
4202        for (Signature sig : s1) {
4203            set1.add(sig);
4204        }
4205        ArraySet<Signature> set2 = new ArraySet<Signature>();
4206        for (Signature sig : s2) {
4207            set2.add(sig);
4208        }
4209        // Make sure s2 contains all signatures in s1.
4210        if (set1.equals(set2)) {
4211            return PackageManager.SIGNATURE_MATCH;
4212        }
4213        return PackageManager.SIGNATURE_NO_MATCH;
4214    }
4215
4216    /**
4217     * If the database version for this type of package (internal storage or
4218     * external storage) is less than the version where package signatures
4219     * were updated, return true.
4220     */
4221    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4222        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4223        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4224    }
4225
4226    /**
4227     * Used for backward compatibility to make sure any packages with
4228     * certificate chains get upgraded to the new style. {@code existingSigs}
4229     * will be in the old format (since they were stored on disk from before the
4230     * system upgrade) and {@code scannedSigs} will be in the newer format.
4231     */
4232    private int compareSignaturesCompat(PackageSignatures existingSigs,
4233            PackageParser.Package scannedPkg) {
4234        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4235            return PackageManager.SIGNATURE_NO_MATCH;
4236        }
4237
4238        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4239        for (Signature sig : existingSigs.mSignatures) {
4240            existingSet.add(sig);
4241        }
4242        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4243        for (Signature sig : scannedPkg.mSignatures) {
4244            try {
4245                Signature[] chainSignatures = sig.getChainSignatures();
4246                for (Signature chainSig : chainSignatures) {
4247                    scannedCompatSet.add(chainSig);
4248                }
4249            } catch (CertificateEncodingException e) {
4250                scannedCompatSet.add(sig);
4251            }
4252        }
4253        /*
4254         * Make sure the expanded scanned set contains all signatures in the
4255         * existing one.
4256         */
4257        if (scannedCompatSet.equals(existingSet)) {
4258            // Migrate the old signatures to the new scheme.
4259            existingSigs.assignSignatures(scannedPkg.mSignatures);
4260            // The new KeySets will be re-added later in the scanning process.
4261            synchronized (mPackages) {
4262                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4263            }
4264            return PackageManager.SIGNATURE_MATCH;
4265        }
4266        return PackageManager.SIGNATURE_NO_MATCH;
4267    }
4268
4269    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4270        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4271        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4272    }
4273
4274    private int compareSignaturesRecover(PackageSignatures existingSigs,
4275            PackageParser.Package scannedPkg) {
4276        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4277            return PackageManager.SIGNATURE_NO_MATCH;
4278        }
4279
4280        String msg = null;
4281        try {
4282            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4283                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4284                        + scannedPkg.packageName);
4285                return PackageManager.SIGNATURE_MATCH;
4286            }
4287        } catch (CertificateException e) {
4288            msg = e.getMessage();
4289        }
4290
4291        logCriticalInfo(Log.INFO,
4292                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4293        return PackageManager.SIGNATURE_NO_MATCH;
4294    }
4295
4296    @Override
4297    public String[] getPackagesForUid(int uid) {
4298        uid = UserHandle.getAppId(uid);
4299        // reader
4300        synchronized (mPackages) {
4301            Object obj = mSettings.getUserIdLPr(uid);
4302            if (obj instanceof SharedUserSetting) {
4303                final SharedUserSetting sus = (SharedUserSetting) obj;
4304                final int N = sus.packages.size();
4305                final String[] res = new String[N];
4306                final Iterator<PackageSetting> it = sus.packages.iterator();
4307                int i = 0;
4308                while (it.hasNext()) {
4309                    res[i++] = it.next().name;
4310                }
4311                return res;
4312            } else if (obj instanceof PackageSetting) {
4313                final PackageSetting ps = (PackageSetting) obj;
4314                return new String[] { ps.name };
4315            }
4316        }
4317        return null;
4318    }
4319
4320    @Override
4321    public String getNameForUid(int uid) {
4322        // reader
4323        synchronized (mPackages) {
4324            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4325            if (obj instanceof SharedUserSetting) {
4326                final SharedUserSetting sus = (SharedUserSetting) obj;
4327                return sus.name + ":" + sus.userId;
4328            } else if (obj instanceof PackageSetting) {
4329                final PackageSetting ps = (PackageSetting) obj;
4330                return ps.name;
4331            }
4332        }
4333        return null;
4334    }
4335
4336    @Override
4337    public int getUidForSharedUser(String sharedUserName) {
4338        if(sharedUserName == null) {
4339            return -1;
4340        }
4341        // reader
4342        synchronized (mPackages) {
4343            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4344            if (suid == null) {
4345                return -1;
4346            }
4347            return suid.userId;
4348        }
4349    }
4350
4351    @Override
4352    public int getFlagsForUid(int uid) {
4353        synchronized (mPackages) {
4354            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4355            if (obj instanceof SharedUserSetting) {
4356                final SharedUserSetting sus = (SharedUserSetting) obj;
4357                return sus.pkgFlags;
4358            } else if (obj instanceof PackageSetting) {
4359                final PackageSetting ps = (PackageSetting) obj;
4360                return ps.pkgFlags;
4361            }
4362        }
4363        return 0;
4364    }
4365
4366    @Override
4367    public int getPrivateFlagsForUid(int uid) {
4368        synchronized (mPackages) {
4369            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4370            if (obj instanceof SharedUserSetting) {
4371                final SharedUserSetting sus = (SharedUserSetting) obj;
4372                return sus.pkgPrivateFlags;
4373            } else if (obj instanceof PackageSetting) {
4374                final PackageSetting ps = (PackageSetting) obj;
4375                return ps.pkgPrivateFlags;
4376            }
4377        }
4378        return 0;
4379    }
4380
4381    @Override
4382    public boolean isUidPrivileged(int uid) {
4383        uid = UserHandle.getAppId(uid);
4384        // reader
4385        synchronized (mPackages) {
4386            Object obj = mSettings.getUserIdLPr(uid);
4387            if (obj instanceof SharedUserSetting) {
4388                final SharedUserSetting sus = (SharedUserSetting) obj;
4389                final Iterator<PackageSetting> it = sus.packages.iterator();
4390                while (it.hasNext()) {
4391                    if (it.next().isPrivileged()) {
4392                        return true;
4393                    }
4394                }
4395            } else if (obj instanceof PackageSetting) {
4396                final PackageSetting ps = (PackageSetting) obj;
4397                return ps.isPrivileged();
4398            }
4399        }
4400        return false;
4401    }
4402
4403    @Override
4404    public String[] getAppOpPermissionPackages(String permissionName) {
4405        synchronized (mPackages) {
4406            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4407            if (pkgs == null) {
4408                return null;
4409            }
4410            return pkgs.toArray(new String[pkgs.size()]);
4411        }
4412    }
4413
4414    @Override
4415    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4416            int flags, int userId) {
4417        if (!sUserManager.exists(userId)) return null;
4418        flags = updateFlagsForResolve(flags, userId, intent);
4419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4420        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4421        final ResolveInfo bestChoice =
4422                chooseBestActivity(intent, resolvedType, flags, query, userId);
4423
4424        if (isEphemeralAllowed(intent, query, userId)) {
4425            final EphemeralResolveInfo ai =
4426                    getEphemeralResolveInfo(intent, resolvedType, userId);
4427            if (ai != null) {
4428                if (DEBUG_EPHEMERAL) {
4429                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4430                }
4431                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4432                bestChoice.ephemeralResolveInfo = ai;
4433            }
4434        }
4435        return bestChoice;
4436    }
4437
4438    @Override
4439    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4440            IntentFilter filter, int match, ComponentName activity) {
4441        final int userId = UserHandle.getCallingUserId();
4442        if (DEBUG_PREFERRED) {
4443            Log.v(TAG, "setLastChosenActivity intent=" + intent
4444                + " resolvedType=" + resolvedType
4445                + " flags=" + flags
4446                + " filter=" + filter
4447                + " match=" + match
4448                + " activity=" + activity);
4449            filter.dump(new PrintStreamPrinter(System.out), "    ");
4450        }
4451        intent.setComponent(null);
4452        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4453        // Find any earlier preferred or last chosen entries and nuke them
4454        findPreferredActivity(intent, resolvedType,
4455                flags, query, 0, false, true, false, userId);
4456        // Add the new activity as the last chosen for this filter
4457        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4458                "Setting last chosen");
4459    }
4460
4461    @Override
4462    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4463        final int userId = UserHandle.getCallingUserId();
4464        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4465        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4466        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4467                false, false, false, userId);
4468    }
4469
4470
4471    private boolean isEphemeralAllowed(
4472            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4473        // Short circuit and return early if possible.
4474        if (DISABLE_EPHEMERAL_APPS) {
4475            return false;
4476        }
4477        final int callingUser = UserHandle.getCallingUserId();
4478        if (callingUser != UserHandle.USER_SYSTEM) {
4479            return false;
4480        }
4481        if (mEphemeralResolverConnection == null) {
4482            return false;
4483        }
4484        if (intent.getComponent() != null) {
4485            return false;
4486        }
4487        if (intent.getPackage() != null) {
4488            return false;
4489        }
4490        final boolean isWebUri = hasWebURI(intent);
4491        if (!isWebUri) {
4492            return false;
4493        }
4494        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4495        synchronized (mPackages) {
4496            final int count = resolvedActivites.size();
4497            for (int n = 0; n < count; n++) {
4498                ResolveInfo info = resolvedActivites.get(n);
4499                String packageName = info.activityInfo.packageName;
4500                PackageSetting ps = mSettings.mPackages.get(packageName);
4501                if (ps != null) {
4502                    // Try to get the status from User settings first
4503                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4504                    int status = (int) (packedStatus >> 32);
4505                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4506                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4507                        if (DEBUG_EPHEMERAL) {
4508                            Slog.v(TAG, "DENY ephemeral apps;"
4509                                + " pkg: " + packageName + ", status: " + status);
4510                        }
4511                        return false;
4512                    }
4513                }
4514            }
4515        }
4516        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4517        return true;
4518    }
4519
4520    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4521            int userId) {
4522        MessageDigest digest = null;
4523        try {
4524            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4525        } catch (NoSuchAlgorithmException e) {
4526            // If we can't create a digest, ignore ephemeral apps.
4527            return null;
4528        }
4529
4530        final byte[] hostBytes = intent.getData().getHost().getBytes();
4531        final byte[] digestBytes = digest.digest(hostBytes);
4532        int shaPrefix =
4533                digestBytes[0] << 24
4534                | digestBytes[1] << 16
4535                | digestBytes[2] << 8
4536                | digestBytes[3] << 0;
4537        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4538                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4539        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4540            // No hash prefix match; there are no ephemeral apps for this domain.
4541            return null;
4542        }
4543        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4544            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4545            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4546                continue;
4547            }
4548            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4549            // No filters; this should never happen.
4550            if (filters.isEmpty()) {
4551                continue;
4552            }
4553            // We have a domain match; resolve the filters to see if anything matches.
4554            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4555            for (int j = filters.size() - 1; j >= 0; --j) {
4556                final EphemeralResolveIntentInfo intentInfo =
4557                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4558                ephemeralResolver.addFilter(intentInfo);
4559            }
4560            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4561                    intent, resolvedType, false /*defaultOnly*/, userId);
4562            if (!matchedResolveInfoList.isEmpty()) {
4563                return matchedResolveInfoList.get(0);
4564            }
4565        }
4566        // Hash or filter mis-match; no ephemeral apps for this domain.
4567        return null;
4568    }
4569
4570    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4571            int flags, List<ResolveInfo> query, int userId) {
4572        if (query != null) {
4573            final int N = query.size();
4574            if (N == 1) {
4575                return query.get(0);
4576            } else if (N > 1) {
4577                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4578                // If there is more than one activity with the same priority,
4579                // then let the user decide between them.
4580                ResolveInfo r0 = query.get(0);
4581                ResolveInfo r1 = query.get(1);
4582                if (DEBUG_INTENT_MATCHING || debug) {
4583                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4584                            + r1.activityInfo.name + "=" + r1.priority);
4585                }
4586                // If the first activity has a higher priority, or a different
4587                // default, then it is always desirable to pick it.
4588                if (r0.priority != r1.priority
4589                        || r0.preferredOrder != r1.preferredOrder
4590                        || r0.isDefault != r1.isDefault) {
4591                    return query.get(0);
4592                }
4593                // If we have saved a preference for a preferred activity for
4594                // this Intent, use that.
4595                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4596                        flags, query, r0.priority, true, false, debug, userId);
4597                if (ri != null) {
4598                    return ri;
4599                }
4600                ri = new ResolveInfo(mResolveInfo);
4601                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4602                ri.activityInfo.applicationInfo = new ApplicationInfo(
4603                        ri.activityInfo.applicationInfo);
4604                if (userId != 0) {
4605                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4606                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4607                }
4608                // Make sure that the resolver is displayable in car mode
4609                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4610                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4611                return ri;
4612            }
4613        }
4614        return null;
4615    }
4616
4617    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4618            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4619        final int N = query.size();
4620        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4621                .get(userId);
4622        // Get the list of persistent preferred activities that handle the intent
4623        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4624        List<PersistentPreferredActivity> pprefs = ppir != null
4625                ? ppir.queryIntent(intent, resolvedType,
4626                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4627                : null;
4628        if (pprefs != null && pprefs.size() > 0) {
4629            final int M = pprefs.size();
4630            for (int i=0; i<M; i++) {
4631                final PersistentPreferredActivity ppa = pprefs.get(i);
4632                if (DEBUG_PREFERRED || debug) {
4633                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4634                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4635                            + "\n  component=" + ppa.mComponent);
4636                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4637                }
4638                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4639                        flags | MATCH_DISABLED_COMPONENTS, userId);
4640                if (DEBUG_PREFERRED || debug) {
4641                    Slog.v(TAG, "Found persistent preferred activity:");
4642                    if (ai != null) {
4643                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4644                    } else {
4645                        Slog.v(TAG, "  null");
4646                    }
4647                }
4648                if (ai == null) {
4649                    // This previously registered persistent preferred activity
4650                    // component is no longer known. Ignore it and do NOT remove it.
4651                    continue;
4652                }
4653                for (int j=0; j<N; j++) {
4654                    final ResolveInfo ri = query.get(j);
4655                    if (!ri.activityInfo.applicationInfo.packageName
4656                            .equals(ai.applicationInfo.packageName)) {
4657                        continue;
4658                    }
4659                    if (!ri.activityInfo.name.equals(ai.name)) {
4660                        continue;
4661                    }
4662                    //  Found a persistent preference that can handle the intent.
4663                    if (DEBUG_PREFERRED || debug) {
4664                        Slog.v(TAG, "Returning persistent preferred activity: " +
4665                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4666                    }
4667                    return ri;
4668                }
4669            }
4670        }
4671        return null;
4672    }
4673
4674    // TODO: handle preferred activities missing while user has amnesia
4675    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4676            List<ResolveInfo> query, int priority, boolean always,
4677            boolean removeMatches, boolean debug, int userId) {
4678        if (!sUserManager.exists(userId)) return null;
4679        flags = updateFlagsForResolve(flags, userId, intent);
4680        // writer
4681        synchronized (mPackages) {
4682            if (intent.getSelector() != null) {
4683                intent = intent.getSelector();
4684            }
4685            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4686
4687            // Try to find a matching persistent preferred activity.
4688            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4689                    debug, userId);
4690
4691            // If a persistent preferred activity matched, use it.
4692            if (pri != null) {
4693                return pri;
4694            }
4695
4696            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4697            // Get the list of preferred activities that handle the intent
4698            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4699            List<PreferredActivity> prefs = pir != null
4700                    ? pir.queryIntent(intent, resolvedType,
4701                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4702                    : null;
4703            if (prefs != null && prefs.size() > 0) {
4704                boolean changed = false;
4705                try {
4706                    // First figure out how good the original match set is.
4707                    // We will only allow preferred activities that came
4708                    // from the same match quality.
4709                    int match = 0;
4710
4711                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4712
4713                    final int N = query.size();
4714                    for (int j=0; j<N; j++) {
4715                        final ResolveInfo ri = query.get(j);
4716                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4717                                + ": 0x" + Integer.toHexString(match));
4718                        if (ri.match > match) {
4719                            match = ri.match;
4720                        }
4721                    }
4722
4723                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4724                            + Integer.toHexString(match));
4725
4726                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4727                    final int M = prefs.size();
4728                    for (int i=0; i<M; i++) {
4729                        final PreferredActivity pa = prefs.get(i);
4730                        if (DEBUG_PREFERRED || debug) {
4731                            Slog.v(TAG, "Checking PreferredActivity ds="
4732                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4733                                    + "\n  component=" + pa.mPref.mComponent);
4734                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4735                        }
4736                        if (pa.mPref.mMatch != match) {
4737                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4738                                    + Integer.toHexString(pa.mPref.mMatch));
4739                            continue;
4740                        }
4741                        // If it's not an "always" type preferred activity and that's what we're
4742                        // looking for, skip it.
4743                        if (always && !pa.mPref.mAlways) {
4744                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4745                            continue;
4746                        }
4747                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4748                                flags | MATCH_DISABLED_COMPONENTS, userId);
4749                        if (DEBUG_PREFERRED || debug) {
4750                            Slog.v(TAG, "Found preferred activity:");
4751                            if (ai != null) {
4752                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4753                            } else {
4754                                Slog.v(TAG, "  null");
4755                            }
4756                        }
4757                        if (ai == null) {
4758                            // This previously registered preferred activity
4759                            // component is no longer known.  Most likely an update
4760                            // to the app was installed and in the new version this
4761                            // component no longer exists.  Clean it up by removing
4762                            // it from the preferred activities list, and skip it.
4763                            Slog.w(TAG, "Removing dangling preferred activity: "
4764                                    + pa.mPref.mComponent);
4765                            pir.removeFilter(pa);
4766                            changed = true;
4767                            continue;
4768                        }
4769                        for (int j=0; j<N; j++) {
4770                            final ResolveInfo ri = query.get(j);
4771                            if (!ri.activityInfo.applicationInfo.packageName
4772                                    .equals(ai.applicationInfo.packageName)) {
4773                                continue;
4774                            }
4775                            if (!ri.activityInfo.name.equals(ai.name)) {
4776                                continue;
4777                            }
4778
4779                            if (removeMatches) {
4780                                pir.removeFilter(pa);
4781                                changed = true;
4782                                if (DEBUG_PREFERRED) {
4783                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4784                                }
4785                                break;
4786                            }
4787
4788                            // Okay we found a previously set preferred or last chosen app.
4789                            // If the result set is different from when this
4790                            // was created, we need to clear it and re-ask the
4791                            // user their preference, if we're looking for an "always" type entry.
4792                            if (always && !pa.mPref.sameSet(query)) {
4793                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4794                                        + intent + " type " + resolvedType);
4795                                if (DEBUG_PREFERRED) {
4796                                    Slog.v(TAG, "Removing preferred activity since set changed "
4797                                            + pa.mPref.mComponent);
4798                                }
4799                                pir.removeFilter(pa);
4800                                // Re-add the filter as a "last chosen" entry (!always)
4801                                PreferredActivity lastChosen = new PreferredActivity(
4802                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4803                                pir.addFilter(lastChosen);
4804                                changed = true;
4805                                return null;
4806                            }
4807
4808                            // Yay! Either the set matched or we're looking for the last chosen
4809                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4810                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4811                            return ri;
4812                        }
4813                    }
4814                } finally {
4815                    if (changed) {
4816                        if (DEBUG_PREFERRED) {
4817                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4818                        }
4819                        scheduleWritePackageRestrictionsLocked(userId);
4820                    }
4821                }
4822            }
4823        }
4824        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4825        return null;
4826    }
4827
4828    /*
4829     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4830     */
4831    @Override
4832    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4833            int targetUserId) {
4834        mContext.enforceCallingOrSelfPermission(
4835                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4836        List<CrossProfileIntentFilter> matches =
4837                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4838        if (matches != null) {
4839            int size = matches.size();
4840            for (int i = 0; i < size; i++) {
4841                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4842            }
4843        }
4844        if (hasWebURI(intent)) {
4845            // cross-profile app linking works only towards the parent.
4846            final UserInfo parent = getProfileParent(sourceUserId);
4847            synchronized(mPackages) {
4848                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4849                        intent, resolvedType, 0, sourceUserId, parent.id);
4850                return xpDomainInfo != null;
4851            }
4852        }
4853        return false;
4854    }
4855
4856    private UserInfo getProfileParent(int userId) {
4857        final long identity = Binder.clearCallingIdentity();
4858        try {
4859            return sUserManager.getProfileParent(userId);
4860        } finally {
4861            Binder.restoreCallingIdentity(identity);
4862        }
4863    }
4864
4865    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4866            String resolvedType, int userId) {
4867        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4868        if (resolver != null) {
4869            return resolver.queryIntent(intent, resolvedType, false, userId);
4870        }
4871        return null;
4872    }
4873
4874    @Override
4875    public List<ResolveInfo> queryIntentActivities(Intent intent,
4876            String resolvedType, int flags, int userId) {
4877        if (!sUserManager.exists(userId)) return Collections.emptyList();
4878        flags = updateFlagsForResolve(flags, userId, intent);
4879        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4880        ComponentName comp = intent.getComponent();
4881        if (comp == null) {
4882            if (intent.getSelector() != null) {
4883                intent = intent.getSelector();
4884                comp = intent.getComponent();
4885            }
4886        }
4887
4888        if (comp != null) {
4889            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4890            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4891            if (ai != null) {
4892                final ResolveInfo ri = new ResolveInfo();
4893                ri.activityInfo = ai;
4894                list.add(ri);
4895            }
4896            return list;
4897        }
4898
4899        // reader
4900        synchronized (mPackages) {
4901            final String pkgName = intent.getPackage();
4902            if (pkgName == null) {
4903                List<CrossProfileIntentFilter> matchingFilters =
4904                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4905                // Check for results that need to skip the current profile.
4906                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4907                        resolvedType, flags, userId);
4908                if (xpResolveInfo != null) {
4909                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4910                    result.add(xpResolveInfo);
4911                    return filterIfNotSystemUser(result, userId);
4912                }
4913
4914                // Check for results in the current profile.
4915                List<ResolveInfo> result = mActivities.queryIntent(
4916                        intent, resolvedType, flags, userId);
4917                result = filterIfNotSystemUser(result, userId);
4918
4919                // Check for cross profile results.
4920                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4921                xpResolveInfo = queryCrossProfileIntents(
4922                        matchingFilters, intent, resolvedType, flags, userId,
4923                        hasNonNegativePriorityResult);
4924                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4925                    boolean isVisibleToUser = filterIfNotSystemUser(
4926                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4927                    if (isVisibleToUser) {
4928                        result.add(xpResolveInfo);
4929                        Collections.sort(result, mResolvePrioritySorter);
4930                    }
4931                }
4932                if (hasWebURI(intent)) {
4933                    CrossProfileDomainInfo xpDomainInfo = null;
4934                    final UserInfo parent = getProfileParent(userId);
4935                    if (parent != null) {
4936                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4937                                flags, userId, parent.id);
4938                    }
4939                    if (xpDomainInfo != null) {
4940                        if (xpResolveInfo != null) {
4941                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4942                            // in the result.
4943                            result.remove(xpResolveInfo);
4944                        }
4945                        if (result.size() == 0) {
4946                            result.add(xpDomainInfo.resolveInfo);
4947                            return result;
4948                        }
4949                    } else if (result.size() <= 1) {
4950                        return result;
4951                    }
4952                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4953                            xpDomainInfo, userId);
4954                    Collections.sort(result, mResolvePrioritySorter);
4955                }
4956                return result;
4957            }
4958            final PackageParser.Package pkg = mPackages.get(pkgName);
4959            if (pkg != null) {
4960                return filterIfNotSystemUser(
4961                        mActivities.queryIntentForPackage(
4962                                intent, resolvedType, flags, pkg.activities, userId),
4963                        userId);
4964            }
4965            return new ArrayList<ResolveInfo>();
4966        }
4967    }
4968
4969    private static class CrossProfileDomainInfo {
4970        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4971        ResolveInfo resolveInfo;
4972        /* Best domain verification status of the activities found in the other profile */
4973        int bestDomainVerificationStatus;
4974    }
4975
4976    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4977            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4978        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4979                sourceUserId)) {
4980            return null;
4981        }
4982        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4983                resolvedType, flags, parentUserId);
4984
4985        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4986            return null;
4987        }
4988        CrossProfileDomainInfo result = null;
4989        int size = resultTargetUser.size();
4990        for (int i = 0; i < size; i++) {
4991            ResolveInfo riTargetUser = resultTargetUser.get(i);
4992            // Intent filter verification is only for filters that specify a host. So don't return
4993            // those that handle all web uris.
4994            if (riTargetUser.handleAllWebDataURI) {
4995                continue;
4996            }
4997            String packageName = riTargetUser.activityInfo.packageName;
4998            PackageSetting ps = mSettings.mPackages.get(packageName);
4999            if (ps == null) {
5000                continue;
5001            }
5002            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5003            int status = (int)(verificationState >> 32);
5004            if (result == null) {
5005                result = new CrossProfileDomainInfo();
5006                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5007                        sourceUserId, parentUserId);
5008                result.bestDomainVerificationStatus = status;
5009            } else {
5010                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5011                        result.bestDomainVerificationStatus);
5012            }
5013        }
5014        // Don't consider matches with status NEVER across profiles.
5015        if (result != null && result.bestDomainVerificationStatus
5016                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5017            return null;
5018        }
5019        return result;
5020    }
5021
5022    /**
5023     * Verification statuses are ordered from the worse to the best, except for
5024     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5025     */
5026    private int bestDomainVerificationStatus(int status1, int status2) {
5027        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5028            return status2;
5029        }
5030        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5031            return status1;
5032        }
5033        return (int) MathUtils.max(status1, status2);
5034    }
5035
5036    private boolean isUserEnabled(int userId) {
5037        long callingId = Binder.clearCallingIdentity();
5038        try {
5039            UserInfo userInfo = sUserManager.getUserInfo(userId);
5040            return userInfo != null && userInfo.isEnabled();
5041        } finally {
5042            Binder.restoreCallingIdentity(callingId);
5043        }
5044    }
5045
5046    /**
5047     * Filter out activities with systemUserOnly flag set, when current user is not System.
5048     *
5049     * @return filtered list
5050     */
5051    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5052        if (userId == UserHandle.USER_SYSTEM) {
5053            return resolveInfos;
5054        }
5055        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5056            ResolveInfo info = resolveInfos.get(i);
5057            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5058                resolveInfos.remove(i);
5059            }
5060        }
5061        return resolveInfos;
5062    }
5063
5064    /**
5065     * @param resolveInfos list of resolve infos in descending priority order
5066     * @return if the list contains a resolve info with non-negative priority
5067     */
5068    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5069        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5070    }
5071
5072    private static boolean hasWebURI(Intent intent) {
5073        if (intent.getData() == null) {
5074            return false;
5075        }
5076        final String scheme = intent.getScheme();
5077        if (TextUtils.isEmpty(scheme)) {
5078            return false;
5079        }
5080        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5081    }
5082
5083    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5084            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5085            int userId) {
5086        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5087
5088        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5089            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5090                    candidates.size());
5091        }
5092
5093        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5094        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5095        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5096        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5097        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5098        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5099
5100        synchronized (mPackages) {
5101            final int count = candidates.size();
5102            // First, try to use linked apps. Partition the candidates into four lists:
5103            // one for the final results, one for the "do not use ever", one for "undefined status"
5104            // and finally one for "browser app type".
5105            for (int n=0; n<count; n++) {
5106                ResolveInfo info = candidates.get(n);
5107                String packageName = info.activityInfo.packageName;
5108                PackageSetting ps = mSettings.mPackages.get(packageName);
5109                if (ps != null) {
5110                    // Add to the special match all list (Browser use case)
5111                    if (info.handleAllWebDataURI) {
5112                        matchAllList.add(info);
5113                        continue;
5114                    }
5115                    // Try to get the status from User settings first
5116                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5117                    int status = (int)(packedStatus >> 32);
5118                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5119                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5120                        if (DEBUG_DOMAIN_VERIFICATION) {
5121                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5122                                    + " : linkgen=" + linkGeneration);
5123                        }
5124                        // Use link-enabled generation as preferredOrder, i.e.
5125                        // prefer newly-enabled over earlier-enabled.
5126                        info.preferredOrder = linkGeneration;
5127                        alwaysList.add(info);
5128                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5129                        if (DEBUG_DOMAIN_VERIFICATION) {
5130                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5131                        }
5132                        neverList.add(info);
5133                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5134                        if (DEBUG_DOMAIN_VERIFICATION) {
5135                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5136                        }
5137                        alwaysAskList.add(info);
5138                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5139                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5140                        if (DEBUG_DOMAIN_VERIFICATION) {
5141                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5142                        }
5143                        undefinedList.add(info);
5144                    }
5145                }
5146            }
5147
5148            // We'll want to include browser possibilities in a few cases
5149            boolean includeBrowser = false;
5150
5151            // First try to add the "always" resolution(s) for the current user, if any
5152            if (alwaysList.size() > 0) {
5153                result.addAll(alwaysList);
5154            } else {
5155                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5156                result.addAll(undefinedList);
5157                // Maybe add one for the other profile.
5158                if (xpDomainInfo != null && (
5159                        xpDomainInfo.bestDomainVerificationStatus
5160                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5161                    result.add(xpDomainInfo.resolveInfo);
5162                }
5163                includeBrowser = true;
5164            }
5165
5166            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5167            // If there were 'always' entries their preferred order has been set, so we also
5168            // back that off to make the alternatives equivalent
5169            if (alwaysAskList.size() > 0) {
5170                for (ResolveInfo i : result) {
5171                    i.preferredOrder = 0;
5172                }
5173                result.addAll(alwaysAskList);
5174                includeBrowser = true;
5175            }
5176
5177            if (includeBrowser) {
5178                // Also add browsers (all of them or only the default one)
5179                if (DEBUG_DOMAIN_VERIFICATION) {
5180                    Slog.v(TAG, "   ...including browsers in candidate set");
5181                }
5182                if ((matchFlags & MATCH_ALL) != 0) {
5183                    result.addAll(matchAllList);
5184                } else {
5185                    // Browser/generic handling case.  If there's a default browser, go straight
5186                    // to that (but only if there is no other higher-priority match).
5187                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5188                    int maxMatchPrio = 0;
5189                    ResolveInfo defaultBrowserMatch = null;
5190                    final int numCandidates = matchAllList.size();
5191                    for (int n = 0; n < numCandidates; n++) {
5192                        ResolveInfo info = matchAllList.get(n);
5193                        // track the highest overall match priority...
5194                        if (info.priority > maxMatchPrio) {
5195                            maxMatchPrio = info.priority;
5196                        }
5197                        // ...and the highest-priority default browser match
5198                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5199                            if (defaultBrowserMatch == null
5200                                    || (defaultBrowserMatch.priority < info.priority)) {
5201                                if (debug) {
5202                                    Slog.v(TAG, "Considering default browser match " + info);
5203                                }
5204                                defaultBrowserMatch = info;
5205                            }
5206                        }
5207                    }
5208                    if (defaultBrowserMatch != null
5209                            && defaultBrowserMatch.priority >= maxMatchPrio
5210                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5211                    {
5212                        if (debug) {
5213                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5214                        }
5215                        result.add(defaultBrowserMatch);
5216                    } else {
5217                        result.addAll(matchAllList);
5218                    }
5219                }
5220
5221                // If there is nothing selected, add all candidates and remove the ones that the user
5222                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5223                if (result.size() == 0) {
5224                    result.addAll(candidates);
5225                    result.removeAll(neverList);
5226                }
5227            }
5228        }
5229        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5230            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5231                    result.size());
5232            for (ResolveInfo info : result) {
5233                Slog.v(TAG, "  + " + info.activityInfo);
5234            }
5235        }
5236        return result;
5237    }
5238
5239    // Returns a packed value as a long:
5240    //
5241    // high 'int'-sized word: link status: undefined/ask/never/always.
5242    // low 'int'-sized word: relative priority among 'always' results.
5243    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5244        long result = ps.getDomainVerificationStatusForUser(userId);
5245        // if none available, get the master status
5246        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5247            if (ps.getIntentFilterVerificationInfo() != null) {
5248                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5249            }
5250        }
5251        return result;
5252    }
5253
5254    private ResolveInfo querySkipCurrentProfileIntents(
5255            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5256            int flags, int sourceUserId) {
5257        if (matchingFilters != null) {
5258            int size = matchingFilters.size();
5259            for (int i = 0; i < size; i ++) {
5260                CrossProfileIntentFilter filter = matchingFilters.get(i);
5261                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5262                    // Checking if there are activities in the target user that can handle the
5263                    // intent.
5264                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5265                            resolvedType, flags, sourceUserId);
5266                    if (resolveInfo != null) {
5267                        return resolveInfo;
5268                    }
5269                }
5270            }
5271        }
5272        return null;
5273    }
5274
5275    // Return matching ResolveInfo in target user if any.
5276    private ResolveInfo queryCrossProfileIntents(
5277            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5278            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5279        if (matchingFilters != null) {
5280            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5281            // match the same intent. For performance reasons, it is better not to
5282            // run queryIntent twice for the same userId
5283            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5284            int size = matchingFilters.size();
5285            for (int i = 0; i < size; i++) {
5286                CrossProfileIntentFilter filter = matchingFilters.get(i);
5287                int targetUserId = filter.getTargetUserId();
5288                boolean skipCurrentProfile =
5289                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5290                boolean skipCurrentProfileIfNoMatchFound =
5291                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5292                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5293                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5294                    // Checking if there are activities in the target user that can handle the
5295                    // intent.
5296                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5297                            resolvedType, flags, sourceUserId);
5298                    if (resolveInfo != null) return resolveInfo;
5299                    alreadyTriedUserIds.put(targetUserId, true);
5300                }
5301            }
5302        }
5303        return null;
5304    }
5305
5306    /**
5307     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5308     * will forward the intent to the filter's target user.
5309     * Otherwise, returns null.
5310     */
5311    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5312            String resolvedType, int flags, int sourceUserId) {
5313        int targetUserId = filter.getTargetUserId();
5314        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5315                resolvedType, flags, targetUserId);
5316        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5317                && isUserEnabled(targetUserId)) {
5318            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5319        }
5320        return null;
5321    }
5322
5323    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5324            int sourceUserId, int targetUserId) {
5325        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5326        long ident = Binder.clearCallingIdentity();
5327        boolean targetIsProfile;
5328        try {
5329            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5330        } finally {
5331            Binder.restoreCallingIdentity(ident);
5332        }
5333        String className;
5334        if (targetIsProfile) {
5335            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5336        } else {
5337            className = FORWARD_INTENT_TO_PARENT;
5338        }
5339        ComponentName forwardingActivityComponentName = new ComponentName(
5340                mAndroidApplication.packageName, className);
5341        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5342                sourceUserId);
5343        if (!targetIsProfile) {
5344            forwardingActivityInfo.showUserIcon = targetUserId;
5345            forwardingResolveInfo.noResourceId = true;
5346        }
5347        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5348        forwardingResolveInfo.priority = 0;
5349        forwardingResolveInfo.preferredOrder = 0;
5350        forwardingResolveInfo.match = 0;
5351        forwardingResolveInfo.isDefault = true;
5352        forwardingResolveInfo.filter = filter;
5353        forwardingResolveInfo.targetUserId = targetUserId;
5354        return forwardingResolveInfo;
5355    }
5356
5357    @Override
5358    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5359            Intent[] specifics, String[] specificTypes, Intent intent,
5360            String resolvedType, int flags, int userId) {
5361        if (!sUserManager.exists(userId)) return Collections.emptyList();
5362        flags = updateFlagsForResolve(flags, userId, intent);
5363        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5364                false, "query intent activity options");
5365        final String resultsAction = intent.getAction();
5366
5367        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5368                | PackageManager.GET_RESOLVED_FILTER, userId);
5369
5370        if (DEBUG_INTENT_MATCHING) {
5371            Log.v(TAG, "Query " + intent + ": " + results);
5372        }
5373
5374        int specificsPos = 0;
5375        int N;
5376
5377        // todo: note that the algorithm used here is O(N^2).  This
5378        // isn't a problem in our current environment, but if we start running
5379        // into situations where we have more than 5 or 10 matches then this
5380        // should probably be changed to something smarter...
5381
5382        // First we go through and resolve each of the specific items
5383        // that were supplied, taking care of removing any corresponding
5384        // duplicate items in the generic resolve list.
5385        if (specifics != null) {
5386            for (int i=0; i<specifics.length; i++) {
5387                final Intent sintent = specifics[i];
5388                if (sintent == null) {
5389                    continue;
5390                }
5391
5392                if (DEBUG_INTENT_MATCHING) {
5393                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5394                }
5395
5396                String action = sintent.getAction();
5397                if (resultsAction != null && resultsAction.equals(action)) {
5398                    // If this action was explicitly requested, then don't
5399                    // remove things that have it.
5400                    action = null;
5401                }
5402
5403                ResolveInfo ri = null;
5404                ActivityInfo ai = null;
5405
5406                ComponentName comp = sintent.getComponent();
5407                if (comp == null) {
5408                    ri = resolveIntent(
5409                        sintent,
5410                        specificTypes != null ? specificTypes[i] : null,
5411                            flags, userId);
5412                    if (ri == null) {
5413                        continue;
5414                    }
5415                    if (ri == mResolveInfo) {
5416                        // ACK!  Must do something better with this.
5417                    }
5418                    ai = ri.activityInfo;
5419                    comp = new ComponentName(ai.applicationInfo.packageName,
5420                            ai.name);
5421                } else {
5422                    ai = getActivityInfo(comp, flags, userId);
5423                    if (ai == null) {
5424                        continue;
5425                    }
5426                }
5427
5428                // Look for any generic query activities that are duplicates
5429                // of this specific one, and remove them from the results.
5430                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5431                N = results.size();
5432                int j;
5433                for (j=specificsPos; j<N; j++) {
5434                    ResolveInfo sri = results.get(j);
5435                    if ((sri.activityInfo.name.equals(comp.getClassName())
5436                            && sri.activityInfo.applicationInfo.packageName.equals(
5437                                    comp.getPackageName()))
5438                        || (action != null && sri.filter.matchAction(action))) {
5439                        results.remove(j);
5440                        if (DEBUG_INTENT_MATCHING) Log.v(
5441                            TAG, "Removing duplicate item from " + j
5442                            + " due to specific " + specificsPos);
5443                        if (ri == null) {
5444                            ri = sri;
5445                        }
5446                        j--;
5447                        N--;
5448                    }
5449                }
5450
5451                // Add this specific item to its proper place.
5452                if (ri == null) {
5453                    ri = new ResolveInfo();
5454                    ri.activityInfo = ai;
5455                }
5456                results.add(specificsPos, ri);
5457                ri.specificIndex = i;
5458                specificsPos++;
5459            }
5460        }
5461
5462        // Now we go through the remaining generic results and remove any
5463        // duplicate actions that are found here.
5464        N = results.size();
5465        for (int i=specificsPos; i<N-1; i++) {
5466            final ResolveInfo rii = results.get(i);
5467            if (rii.filter == null) {
5468                continue;
5469            }
5470
5471            // Iterate over all of the actions of this result's intent
5472            // filter...  typically this should be just one.
5473            final Iterator<String> it = rii.filter.actionsIterator();
5474            if (it == null) {
5475                continue;
5476            }
5477            while (it.hasNext()) {
5478                final String action = it.next();
5479                if (resultsAction != null && resultsAction.equals(action)) {
5480                    // If this action was explicitly requested, then don't
5481                    // remove things that have it.
5482                    continue;
5483                }
5484                for (int j=i+1; j<N; j++) {
5485                    final ResolveInfo rij = results.get(j);
5486                    if (rij.filter != null && rij.filter.hasAction(action)) {
5487                        results.remove(j);
5488                        if (DEBUG_INTENT_MATCHING) Log.v(
5489                            TAG, "Removing duplicate item from " + j
5490                            + " due to action " + action + " at " + i);
5491                        j--;
5492                        N--;
5493                    }
5494                }
5495            }
5496
5497            // If the caller didn't request filter information, drop it now
5498            // so we don't have to marshall/unmarshall it.
5499            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5500                rii.filter = null;
5501            }
5502        }
5503
5504        // Filter out the caller activity if so requested.
5505        if (caller != null) {
5506            N = results.size();
5507            for (int i=0; i<N; i++) {
5508                ActivityInfo ainfo = results.get(i).activityInfo;
5509                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5510                        && caller.getClassName().equals(ainfo.name)) {
5511                    results.remove(i);
5512                    break;
5513                }
5514            }
5515        }
5516
5517        // If the caller didn't request filter information,
5518        // drop them now so we don't have to
5519        // marshall/unmarshall it.
5520        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5521            N = results.size();
5522            for (int i=0; i<N; i++) {
5523                results.get(i).filter = null;
5524            }
5525        }
5526
5527        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5528        return results;
5529    }
5530
5531    @Override
5532    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5533            int userId) {
5534        if (!sUserManager.exists(userId)) return Collections.emptyList();
5535        flags = updateFlagsForResolve(flags, userId, intent);
5536        ComponentName comp = intent.getComponent();
5537        if (comp == null) {
5538            if (intent.getSelector() != null) {
5539                intent = intent.getSelector();
5540                comp = intent.getComponent();
5541            }
5542        }
5543        if (comp != null) {
5544            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5545            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5546            if (ai != null) {
5547                ResolveInfo ri = new ResolveInfo();
5548                ri.activityInfo = ai;
5549                list.add(ri);
5550            }
5551            return list;
5552        }
5553
5554        // reader
5555        synchronized (mPackages) {
5556            String pkgName = intent.getPackage();
5557            if (pkgName == null) {
5558                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5559            }
5560            final PackageParser.Package pkg = mPackages.get(pkgName);
5561            if (pkg != null) {
5562                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5563                        userId);
5564            }
5565            return null;
5566        }
5567    }
5568
5569    @Override
5570    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5571        if (!sUserManager.exists(userId)) return null;
5572        flags = updateFlagsForResolve(flags, userId, intent);
5573        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5574        if (query != null) {
5575            if (query.size() >= 1) {
5576                // If there is more than one service with the same priority,
5577                // just arbitrarily pick the first one.
5578                return query.get(0);
5579            }
5580        }
5581        return null;
5582    }
5583
5584    @Override
5585    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5586            int userId) {
5587        if (!sUserManager.exists(userId)) return Collections.emptyList();
5588        flags = updateFlagsForResolve(flags, userId, intent);
5589        ComponentName comp = intent.getComponent();
5590        if (comp == null) {
5591            if (intent.getSelector() != null) {
5592                intent = intent.getSelector();
5593                comp = intent.getComponent();
5594            }
5595        }
5596        if (comp != null) {
5597            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5598            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5599            if (si != null) {
5600                final ResolveInfo ri = new ResolveInfo();
5601                ri.serviceInfo = si;
5602                list.add(ri);
5603            }
5604            return list;
5605        }
5606
5607        // reader
5608        synchronized (mPackages) {
5609            String pkgName = intent.getPackage();
5610            if (pkgName == null) {
5611                return mServices.queryIntent(intent, resolvedType, flags, userId);
5612            }
5613            final PackageParser.Package pkg = mPackages.get(pkgName);
5614            if (pkg != null) {
5615                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5616                        userId);
5617            }
5618            return null;
5619        }
5620    }
5621
5622    @Override
5623    public List<ResolveInfo> queryIntentContentProviders(
5624            Intent intent, String resolvedType, int flags, int userId) {
5625        if (!sUserManager.exists(userId)) return Collections.emptyList();
5626        flags = updateFlagsForResolve(flags, userId, intent);
5627        ComponentName comp = intent.getComponent();
5628        if (comp == null) {
5629            if (intent.getSelector() != null) {
5630                intent = intent.getSelector();
5631                comp = intent.getComponent();
5632            }
5633        }
5634        if (comp != null) {
5635            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5636            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5637            if (pi != null) {
5638                final ResolveInfo ri = new ResolveInfo();
5639                ri.providerInfo = pi;
5640                list.add(ri);
5641            }
5642            return list;
5643        }
5644
5645        // reader
5646        synchronized (mPackages) {
5647            String pkgName = intent.getPackage();
5648            if (pkgName == null) {
5649                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5650            }
5651            final PackageParser.Package pkg = mPackages.get(pkgName);
5652            if (pkg != null) {
5653                return mProviders.queryIntentForPackage(
5654                        intent, resolvedType, flags, pkg.providers, userId);
5655            }
5656            return null;
5657        }
5658    }
5659
5660    @Override
5661    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5662        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5663        flags = updateFlagsForPackage(flags, userId, null);
5664        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5665        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5666
5667        // writer
5668        synchronized (mPackages) {
5669            ArrayList<PackageInfo> list;
5670            if (listUninstalled) {
5671                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5672                for (PackageSetting ps : mSettings.mPackages.values()) {
5673                    PackageInfo pi;
5674                    if (ps.pkg != null) {
5675                        pi = generatePackageInfo(ps.pkg, flags, userId);
5676                    } else {
5677                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5678                    }
5679                    if (pi != null) {
5680                        list.add(pi);
5681                    }
5682                }
5683            } else {
5684                list = new ArrayList<PackageInfo>(mPackages.size());
5685                for (PackageParser.Package p : mPackages.values()) {
5686                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5687                    if (pi != null) {
5688                        list.add(pi);
5689                    }
5690                }
5691            }
5692
5693            return new ParceledListSlice<PackageInfo>(list);
5694        }
5695    }
5696
5697    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5698            String[] permissions, boolean[] tmp, int flags, int userId) {
5699        int numMatch = 0;
5700        final PermissionsState permissionsState = ps.getPermissionsState();
5701        for (int i=0; i<permissions.length; i++) {
5702            final String permission = permissions[i];
5703            if (permissionsState.hasPermission(permission, userId)) {
5704                tmp[i] = true;
5705                numMatch++;
5706            } else {
5707                tmp[i] = false;
5708            }
5709        }
5710        if (numMatch == 0) {
5711            return;
5712        }
5713        PackageInfo pi;
5714        if (ps.pkg != null) {
5715            pi = generatePackageInfo(ps.pkg, flags, userId);
5716        } else {
5717            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5718        }
5719        // The above might return null in cases of uninstalled apps or install-state
5720        // skew across users/profiles.
5721        if (pi != null) {
5722            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5723                if (numMatch == permissions.length) {
5724                    pi.requestedPermissions = permissions;
5725                } else {
5726                    pi.requestedPermissions = new String[numMatch];
5727                    numMatch = 0;
5728                    for (int i=0; i<permissions.length; i++) {
5729                        if (tmp[i]) {
5730                            pi.requestedPermissions[numMatch] = permissions[i];
5731                            numMatch++;
5732                        }
5733                    }
5734                }
5735            }
5736            list.add(pi);
5737        }
5738    }
5739
5740    @Override
5741    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5742            String[] permissions, int flags, int userId) {
5743        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5744        flags = updateFlagsForPackage(flags, userId, permissions);
5745        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5746
5747        // writer
5748        synchronized (mPackages) {
5749            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5750            boolean[] tmpBools = new boolean[permissions.length];
5751            if (listUninstalled) {
5752                for (PackageSetting ps : mSettings.mPackages.values()) {
5753                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5754                }
5755            } else {
5756                for (PackageParser.Package pkg : mPackages.values()) {
5757                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5758                    if (ps != null) {
5759                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5760                                userId);
5761                    }
5762                }
5763            }
5764
5765            return new ParceledListSlice<PackageInfo>(list);
5766        }
5767    }
5768
5769    @Override
5770    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5771        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5772        flags = updateFlagsForApplication(flags, userId, null);
5773        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5774
5775        // writer
5776        synchronized (mPackages) {
5777            ArrayList<ApplicationInfo> list;
5778            if (listUninstalled) {
5779                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5780                for (PackageSetting ps : mSettings.mPackages.values()) {
5781                    ApplicationInfo ai;
5782                    if (ps.pkg != null) {
5783                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5784                                ps.readUserState(userId), userId);
5785                    } else {
5786                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5787                    }
5788                    if (ai != null) {
5789                        list.add(ai);
5790                    }
5791                }
5792            } else {
5793                list = new ArrayList<ApplicationInfo>(mPackages.size());
5794                for (PackageParser.Package p : mPackages.values()) {
5795                    if (p.mExtras != null) {
5796                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5797                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5798                        if (ai != null) {
5799                            list.add(ai);
5800                        }
5801                    }
5802                }
5803            }
5804
5805            return new ParceledListSlice<ApplicationInfo>(list);
5806        }
5807    }
5808
5809    @Override
5810    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5811        if (DISABLE_EPHEMERAL_APPS) {
5812            return null;
5813        }
5814
5815        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5816                "getEphemeralApplications");
5817        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5818                "getEphemeralApplications");
5819        synchronized (mPackages) {
5820            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5821                    .getEphemeralApplicationsLPw(userId);
5822            if (ephemeralApps != null) {
5823                return new ParceledListSlice<>(ephemeralApps);
5824            }
5825        }
5826        return null;
5827    }
5828
5829    @Override
5830    public boolean isEphemeralApplication(String packageName, int userId) {
5831        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5832                "isEphemeral");
5833        if (DISABLE_EPHEMERAL_APPS) {
5834            return false;
5835        }
5836
5837        if (!isCallerSameApp(packageName)) {
5838            return false;
5839        }
5840        synchronized (mPackages) {
5841            PackageParser.Package pkg = mPackages.get(packageName);
5842            if (pkg != null) {
5843                return pkg.applicationInfo.isEphemeralApp();
5844            }
5845        }
5846        return false;
5847    }
5848
5849    @Override
5850    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5851        if (DISABLE_EPHEMERAL_APPS) {
5852            return null;
5853        }
5854
5855        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5856                "getCookie");
5857        if (!isCallerSameApp(packageName)) {
5858            return null;
5859        }
5860        synchronized (mPackages) {
5861            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5862                    packageName, userId);
5863        }
5864    }
5865
5866    @Override
5867    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5868        if (DISABLE_EPHEMERAL_APPS) {
5869            return true;
5870        }
5871
5872        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5873                "setCookie");
5874        if (!isCallerSameApp(packageName)) {
5875            return false;
5876        }
5877        synchronized (mPackages) {
5878            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5879                    packageName, cookie, userId);
5880        }
5881    }
5882
5883    @Override
5884    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5885        if (DISABLE_EPHEMERAL_APPS) {
5886            return null;
5887        }
5888
5889        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5890                "getEphemeralApplicationIcon");
5891        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5892                "getEphemeralApplicationIcon");
5893        synchronized (mPackages) {
5894            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5895                    packageName, userId);
5896        }
5897    }
5898
5899    private boolean isCallerSameApp(String packageName) {
5900        PackageParser.Package pkg = mPackages.get(packageName);
5901        return pkg != null
5902                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5903    }
5904
5905    public List<ApplicationInfo> getPersistentApplications(int flags) {
5906        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5907
5908        // reader
5909        synchronized (mPackages) {
5910            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5911            final int userId = UserHandle.getCallingUserId();
5912            while (i.hasNext()) {
5913                final PackageParser.Package p = i.next();
5914                if (p.applicationInfo != null
5915                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5916                        && (!mSafeMode || isSystemApp(p))) {
5917                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5918                    if (ps != null) {
5919                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5920                                ps.readUserState(userId), userId);
5921                        if (ai != null) {
5922                            finalList.add(ai);
5923                        }
5924                    }
5925                }
5926            }
5927        }
5928
5929        return finalList;
5930    }
5931
5932    @Override
5933    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5934        if (!sUserManager.exists(userId)) return null;
5935        flags = updateFlagsForComponent(flags, userId, name);
5936        // reader
5937        synchronized (mPackages) {
5938            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5939            PackageSetting ps = provider != null
5940                    ? mSettings.mPackages.get(provider.owner.packageName)
5941                    : null;
5942            return ps != null
5943                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5944                    && (!mSafeMode || (provider.info.applicationInfo.flags
5945                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5946                    ? PackageParser.generateProviderInfo(provider, flags,
5947                            ps.readUserState(userId), userId)
5948                    : null;
5949        }
5950    }
5951
5952    /**
5953     * @deprecated
5954     */
5955    @Deprecated
5956    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5957        // reader
5958        synchronized (mPackages) {
5959            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5960                    .entrySet().iterator();
5961            final int userId = UserHandle.getCallingUserId();
5962            while (i.hasNext()) {
5963                Map.Entry<String, PackageParser.Provider> entry = i.next();
5964                PackageParser.Provider p = entry.getValue();
5965                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5966
5967                if (ps != null && p.syncable
5968                        && (!mSafeMode || (p.info.applicationInfo.flags
5969                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5970                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5971                            ps.readUserState(userId), userId);
5972                    if (info != null) {
5973                        outNames.add(entry.getKey());
5974                        outInfo.add(info);
5975                    }
5976                }
5977            }
5978        }
5979    }
5980
5981    @Override
5982    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5983            int uid, int flags) {
5984        final int userId = processName != null ? UserHandle.getUserId(uid)
5985                : UserHandle.getCallingUserId();
5986        if (!sUserManager.exists(userId)) return null;
5987        flags = updateFlagsForComponent(flags, userId, processName);
5988
5989        ArrayList<ProviderInfo> finalList = null;
5990        // reader
5991        synchronized (mPackages) {
5992            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5993            while (i.hasNext()) {
5994                final PackageParser.Provider p = i.next();
5995                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5996                if (ps != null && p.info.authority != null
5997                        && (processName == null
5998                                || (p.info.processName.equals(processName)
5999                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6000                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
6001                        && (!mSafeMode
6002                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
6003                    if (finalList == null) {
6004                        finalList = new ArrayList<ProviderInfo>(3);
6005                    }
6006                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6007                            ps.readUserState(userId), userId);
6008                    if (info != null) {
6009                        finalList.add(info);
6010                    }
6011                }
6012            }
6013        }
6014
6015        if (finalList != null) {
6016            Collections.sort(finalList, mProviderInitOrderSorter);
6017            return new ParceledListSlice<ProviderInfo>(finalList);
6018        }
6019
6020        return null;
6021    }
6022
6023    @Override
6024    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6025        // reader
6026        synchronized (mPackages) {
6027            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6028            return PackageParser.generateInstrumentationInfo(i, flags);
6029        }
6030    }
6031
6032    @Override
6033    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6034            int flags) {
6035        ArrayList<InstrumentationInfo> finalList =
6036            new ArrayList<InstrumentationInfo>();
6037
6038        // reader
6039        synchronized (mPackages) {
6040            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6041            while (i.hasNext()) {
6042                final PackageParser.Instrumentation p = i.next();
6043                if (targetPackage == null
6044                        || targetPackage.equals(p.info.targetPackage)) {
6045                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6046                            flags);
6047                    if (ii != null) {
6048                        finalList.add(ii);
6049                    }
6050                }
6051            }
6052        }
6053
6054        return finalList;
6055    }
6056
6057    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6058        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6059        if (overlays == null) {
6060            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6061            return;
6062        }
6063        for (PackageParser.Package opkg : overlays.values()) {
6064            // Not much to do if idmap fails: we already logged the error
6065            // and we certainly don't want to abort installation of pkg simply
6066            // because an overlay didn't fit properly. For these reasons,
6067            // ignore the return value of createIdmapForPackagePairLI.
6068            createIdmapForPackagePairLI(pkg, opkg);
6069        }
6070    }
6071
6072    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6073            PackageParser.Package opkg) {
6074        if (!opkg.mTrustedOverlay) {
6075            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6076                    opkg.baseCodePath + ": overlay not trusted");
6077            return false;
6078        }
6079        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6080        if (overlaySet == null) {
6081            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6082                    opkg.baseCodePath + " but target package has no known overlays");
6083            return false;
6084        }
6085        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6086        // TODO: generate idmap for split APKs
6087        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6088            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6089                    + opkg.baseCodePath);
6090            return false;
6091        }
6092        PackageParser.Package[] overlayArray =
6093            overlaySet.values().toArray(new PackageParser.Package[0]);
6094        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6095            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6096                return p1.mOverlayPriority - p2.mOverlayPriority;
6097            }
6098        };
6099        Arrays.sort(overlayArray, cmp);
6100
6101        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6102        int i = 0;
6103        for (PackageParser.Package p : overlayArray) {
6104            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6105        }
6106        return true;
6107    }
6108
6109    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6110        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6111        try {
6112            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6113        } finally {
6114            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6115        }
6116    }
6117
6118    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6119        final File[] files = dir.listFiles();
6120        if (ArrayUtils.isEmpty(files)) {
6121            Log.d(TAG, "No files in app dir " + dir);
6122            return;
6123        }
6124
6125        if (DEBUG_PACKAGE_SCANNING) {
6126            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6127                    + " flags=0x" + Integer.toHexString(parseFlags));
6128        }
6129
6130        for (File file : files) {
6131            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6132                    && !PackageInstallerService.isStageName(file.getName());
6133            if (!isPackage) {
6134                // Ignore entries which are not packages
6135                continue;
6136            }
6137            try {
6138                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6139                        scanFlags, currentTime, null);
6140            } catch (PackageManagerException e) {
6141                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6142
6143                // Delete invalid userdata apps
6144                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6145                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6146                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6147                    if (file.isDirectory()) {
6148                        mInstaller.rmPackageDir(file.getAbsolutePath());
6149                    } else {
6150                        file.delete();
6151                    }
6152                }
6153            }
6154        }
6155    }
6156
6157    private static File getSettingsProblemFile() {
6158        File dataDir = Environment.getDataDirectory();
6159        File systemDir = new File(dataDir, "system");
6160        File fname = new File(systemDir, "uiderrors.txt");
6161        return fname;
6162    }
6163
6164    static void reportSettingsProblem(int priority, String msg) {
6165        logCriticalInfo(priority, msg);
6166    }
6167
6168    static void logCriticalInfo(int priority, String msg) {
6169        Slog.println(priority, TAG, msg);
6170        EventLogTags.writePmCriticalInfo(msg);
6171        try {
6172            File fname = getSettingsProblemFile();
6173            FileOutputStream out = new FileOutputStream(fname, true);
6174            PrintWriter pw = new FastPrintWriter(out);
6175            SimpleDateFormat formatter = new SimpleDateFormat();
6176            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6177            pw.println(dateString + ": " + msg);
6178            pw.close();
6179            FileUtils.setPermissions(
6180                    fname.toString(),
6181                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6182                    -1, -1);
6183        } catch (java.io.IOException e) {
6184        }
6185    }
6186
6187    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6188            PackageParser.Package pkg, File srcFile, int parseFlags)
6189            throws PackageManagerException {
6190        if (ps != null
6191                && ps.codePath.equals(srcFile)
6192                && ps.timeStamp == srcFile.lastModified()
6193                && !isCompatSignatureUpdateNeeded(pkg)
6194                && !isRecoverSignatureUpdateNeeded(pkg)) {
6195            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6196            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6197            ArraySet<PublicKey> signingKs;
6198            synchronized (mPackages) {
6199                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6200            }
6201            if (ps.signatures.mSignatures != null
6202                    && ps.signatures.mSignatures.length != 0
6203                    && signingKs != null) {
6204                // Optimization: reuse the existing cached certificates
6205                // if the package appears to be unchanged.
6206                pkg.mSignatures = ps.signatures.mSignatures;
6207                pkg.mSigningKeys = signingKs;
6208                return;
6209            }
6210
6211            Slog.w(TAG, "PackageSetting for " + ps.name
6212                    + " is missing signatures.  Collecting certs again to recover them.");
6213        } else {
6214            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6215        }
6216
6217        try {
6218            pp.collectCertificates(pkg, parseFlags);
6219        } catch (PackageParserException e) {
6220            throw PackageManagerException.from(e);
6221        }
6222    }
6223
6224    /**
6225     *  Traces a package scan.
6226     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6227     */
6228    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6229            long currentTime, UserHandle user) throws PackageManagerException {
6230        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6231        try {
6232            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6233        } finally {
6234            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6235        }
6236    }
6237
6238    /**
6239     *  Scans a package and returns the newly parsed package.
6240     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6241     */
6242    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6243            long currentTime, UserHandle user) throws PackageManagerException {
6244        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6245        parseFlags |= mDefParseFlags;
6246        PackageParser pp = new PackageParser();
6247        pp.setSeparateProcesses(mSeparateProcesses);
6248        pp.setOnlyCoreApps(mOnlyCore);
6249        pp.setDisplayMetrics(mMetrics);
6250
6251        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6252            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6253        }
6254
6255        final PackageParser.Package pkg;
6256        try {
6257            pkg = pp.parsePackage(scanFile, parseFlags);
6258        } catch (PackageParserException e) {
6259            throw PackageManagerException.from(e);
6260        }
6261
6262        PackageSetting ps = null;
6263        PackageSetting updatedPkg;
6264        // reader
6265        synchronized (mPackages) {
6266            // Look to see if we already know about this package.
6267            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6268            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6269                // This package has been renamed to its original name.  Let's
6270                // use that.
6271                ps = mSettings.peekPackageLPr(oldName);
6272            }
6273            // If there was no original package, see one for the real package name.
6274            if (ps == null) {
6275                ps = mSettings.peekPackageLPr(pkg.packageName);
6276            }
6277            // Check to see if this package could be hiding/updating a system
6278            // package.  Must look for it either under the original or real
6279            // package name depending on our state.
6280            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6281            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6282        }
6283        boolean updatedPkgBetter = false;
6284        // First check if this is a system package that may involve an update
6285        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6286            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6287            // it needs to drop FLAG_PRIVILEGED.
6288            if (locationIsPrivileged(scanFile)) {
6289                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6290            } else {
6291                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6292            }
6293
6294            if (ps != null && !ps.codePath.equals(scanFile)) {
6295                // The path has changed from what was last scanned...  check the
6296                // version of the new path against what we have stored to determine
6297                // what to do.
6298                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6299                if (pkg.mVersionCode <= ps.versionCode) {
6300                    // The system package has been updated and the code path does not match
6301                    // Ignore entry. Skip it.
6302                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6303                            + " ignored: updated version " + ps.versionCode
6304                            + " better than this " + pkg.mVersionCode);
6305                    if (!updatedPkg.codePath.equals(scanFile)) {
6306                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6307                                + ps.name + " changing from " + updatedPkg.codePathString
6308                                + " to " + scanFile);
6309                        updatedPkg.codePath = scanFile;
6310                        updatedPkg.codePathString = scanFile.toString();
6311                        updatedPkg.resourcePath = scanFile;
6312                        updatedPkg.resourcePathString = scanFile.toString();
6313                    }
6314                    updatedPkg.pkg = pkg;
6315                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6316                            "Package " + ps.name + " at " + scanFile
6317                                    + " ignored: updated version " + ps.versionCode
6318                                    + " better than this " + pkg.mVersionCode);
6319                } else {
6320                    // The current app on the system partition is better than
6321                    // what we have updated to on the data partition; switch
6322                    // back to the system partition version.
6323                    // At this point, its safely assumed that package installation for
6324                    // apps in system partition will go through. If not there won't be a working
6325                    // version of the app
6326                    // writer
6327                    synchronized (mPackages) {
6328                        // Just remove the loaded entries from package lists.
6329                        mPackages.remove(ps.name);
6330                    }
6331
6332                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6333                            + " reverting from " + ps.codePathString
6334                            + ": new version " + pkg.mVersionCode
6335                            + " better than installed " + ps.versionCode);
6336
6337                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6338                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6339                    synchronized (mInstallLock) {
6340                        args.cleanUpResourcesLI();
6341                    }
6342                    synchronized (mPackages) {
6343                        mSettings.enableSystemPackageLPw(ps.name);
6344                    }
6345                    updatedPkgBetter = true;
6346                }
6347            }
6348        }
6349
6350        if (updatedPkg != null) {
6351            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6352            // initially
6353            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6354
6355            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6356            // flag set initially
6357            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6358                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6359            }
6360        }
6361
6362        // Verify certificates against what was last scanned
6363        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6364
6365        /*
6366         * A new system app appeared, but we already had a non-system one of the
6367         * same name installed earlier.
6368         */
6369        boolean shouldHideSystemApp = false;
6370        if (updatedPkg == null && ps != null
6371                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6372            /*
6373             * Check to make sure the signatures match first. If they don't,
6374             * wipe the installed application and its data.
6375             */
6376            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6377                    != PackageManager.SIGNATURE_MATCH) {
6378                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6379                        + " signatures don't match existing userdata copy; removing");
6380                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6381                ps = null;
6382            } else {
6383                /*
6384                 * If the newly-added system app is an older version than the
6385                 * already installed version, hide it. It will be scanned later
6386                 * and re-added like an update.
6387                 */
6388                if (pkg.mVersionCode <= ps.versionCode) {
6389                    shouldHideSystemApp = true;
6390                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6391                            + " but new version " + pkg.mVersionCode + " better than installed "
6392                            + ps.versionCode + "; hiding system");
6393                } else {
6394                    /*
6395                     * The newly found system app is a newer version that the
6396                     * one previously installed. Simply remove the
6397                     * already-installed application and replace it with our own
6398                     * while keeping the application data.
6399                     */
6400                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6401                            + " reverting from " + ps.codePathString + ": new version "
6402                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6403                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6404                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6405                    synchronized (mInstallLock) {
6406                        args.cleanUpResourcesLI();
6407                    }
6408                }
6409            }
6410        }
6411
6412        // The apk is forward locked (not public) if its code and resources
6413        // are kept in different files. (except for app in either system or
6414        // vendor path).
6415        // TODO grab this value from PackageSettings
6416        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6417            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6418                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6419            }
6420        }
6421
6422        // TODO: extend to support forward-locked splits
6423        String resourcePath = null;
6424        String baseResourcePath = null;
6425        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6426            if (ps != null && ps.resourcePathString != null) {
6427                resourcePath = ps.resourcePathString;
6428                baseResourcePath = ps.resourcePathString;
6429            } else {
6430                // Should not happen at all. Just log an error.
6431                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6432            }
6433        } else {
6434            resourcePath = pkg.codePath;
6435            baseResourcePath = pkg.baseCodePath;
6436        }
6437
6438        // Set application objects path explicitly.
6439        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6440        pkg.applicationInfo.setCodePath(pkg.codePath);
6441        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6442        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6443        pkg.applicationInfo.setResourcePath(resourcePath);
6444        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6445        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6446
6447        // Note that we invoke the following method only if we are about to unpack an application
6448        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6449                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6450
6451        /*
6452         * If the system app should be overridden by a previously installed
6453         * data, hide the system app now and let the /data/app scan pick it up
6454         * again.
6455         */
6456        if (shouldHideSystemApp) {
6457            synchronized (mPackages) {
6458                mSettings.disableSystemPackageLPw(pkg.packageName);
6459            }
6460        }
6461
6462        return scannedPkg;
6463    }
6464
6465    private static String fixProcessName(String defProcessName,
6466            String processName, int uid) {
6467        if (processName == null) {
6468            return defProcessName;
6469        }
6470        return processName;
6471    }
6472
6473    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6474            throws PackageManagerException {
6475        if (pkgSetting.signatures.mSignatures != null) {
6476            // Already existing package. Make sure signatures match
6477            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6478                    == PackageManager.SIGNATURE_MATCH;
6479            if (!match) {
6480                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6481                        == PackageManager.SIGNATURE_MATCH;
6482            }
6483            if (!match) {
6484                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6485                        == PackageManager.SIGNATURE_MATCH;
6486            }
6487            if (!match) {
6488                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6489                        + pkg.packageName + " signatures do not match the "
6490                        + "previously installed version; ignoring!");
6491            }
6492        }
6493
6494        // Check for shared user signatures
6495        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6496            // Already existing package. Make sure signatures match
6497            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6498                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6499            if (!match) {
6500                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6501                        == PackageManager.SIGNATURE_MATCH;
6502            }
6503            if (!match) {
6504                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6505                        == PackageManager.SIGNATURE_MATCH;
6506            }
6507            if (!match) {
6508                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6509                        "Package " + pkg.packageName
6510                        + " has no signatures that match those in shared user "
6511                        + pkgSetting.sharedUser.name + "; ignoring!");
6512            }
6513        }
6514    }
6515
6516    /**
6517     * Enforces that only the system UID or root's UID can call a method exposed
6518     * via Binder.
6519     *
6520     * @param message used as message if SecurityException is thrown
6521     * @throws SecurityException if the caller is not system or root
6522     */
6523    private static final void enforceSystemOrRoot(String message) {
6524        final int uid = Binder.getCallingUid();
6525        if (uid != Process.SYSTEM_UID && uid != 0) {
6526            throw new SecurityException(message);
6527        }
6528    }
6529
6530    @Override
6531    public void performFstrimIfNeeded() {
6532        enforceSystemOrRoot("Only the system can request fstrim");
6533
6534        // Before everything else, see whether we need to fstrim.
6535        try {
6536            IMountService ms = PackageHelper.getMountService();
6537            if (ms != null) {
6538                final boolean isUpgrade = isUpgrade();
6539                boolean doTrim = isUpgrade;
6540                if (doTrim) {
6541                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6542                } else {
6543                    final long interval = android.provider.Settings.Global.getLong(
6544                            mContext.getContentResolver(),
6545                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6546                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6547                    if (interval > 0) {
6548                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6549                        if (timeSinceLast > interval) {
6550                            doTrim = true;
6551                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6552                                    + "; running immediately");
6553                        }
6554                    }
6555                }
6556                if (doTrim) {
6557                    if (!isFirstBoot()) {
6558                        try {
6559                            ActivityManagerNative.getDefault().showBootMessage(
6560                                    mContext.getResources().getString(
6561                                            R.string.android_upgrading_fstrim), true);
6562                        } catch (RemoteException e) {
6563                        }
6564                    }
6565                    ms.runMaintenance();
6566                }
6567            } else {
6568                Slog.e(TAG, "Mount service unavailable!");
6569            }
6570        } catch (RemoteException e) {
6571            // Can't happen; MountService is local
6572        }
6573    }
6574
6575    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6576        List<ResolveInfo> ris = null;
6577        try {
6578            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6579                    intent, null, 0, userId);
6580        } catch (RemoteException e) {
6581        }
6582        ArraySet<String> pkgNames = new ArraySet<String>();
6583        if (ris != null) {
6584            for (ResolveInfo ri : ris) {
6585                pkgNames.add(ri.activityInfo.packageName);
6586            }
6587        }
6588        return pkgNames;
6589    }
6590
6591    @Override
6592    public void notifyPackageUse(String packageName) {
6593        synchronized (mPackages) {
6594            PackageParser.Package p = mPackages.get(packageName);
6595            if (p == null) {
6596                return;
6597            }
6598            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6599        }
6600    }
6601
6602    @Override
6603    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6604        return performDexOptTraced(packageName, instructionSet);
6605    }
6606
6607    public boolean performDexOpt(String packageName, String instructionSet) {
6608        return performDexOptTraced(packageName, instructionSet);
6609    }
6610
6611    private boolean performDexOptTraced(String packageName, String instructionSet) {
6612        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6613        try {
6614            return performDexOptInternal(packageName, instructionSet);
6615        } finally {
6616            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6617        }
6618    }
6619
6620    private boolean performDexOptInternal(String packageName, String instructionSet) {
6621        PackageParser.Package p;
6622        final String targetInstructionSet;
6623        synchronized (mPackages) {
6624            p = mPackages.get(packageName);
6625            if (p == null) {
6626                return false;
6627            }
6628            mPackageUsage.write(false);
6629
6630            targetInstructionSet = instructionSet != null ? instructionSet :
6631                    getPrimaryInstructionSet(p.applicationInfo);
6632            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6633                return false;
6634            }
6635        }
6636        long callingId = Binder.clearCallingIdentity();
6637        try {
6638            synchronized (mInstallLock) {
6639                final String[] instructionSets = new String[] { targetInstructionSet };
6640                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6641                        true /* inclDependencies */);
6642                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6643            }
6644        } finally {
6645            Binder.restoreCallingIdentity(callingId);
6646        }
6647    }
6648
6649    public ArraySet<String> getPackagesThatNeedDexOpt() {
6650        ArraySet<String> pkgs = null;
6651        synchronized (mPackages) {
6652            for (PackageParser.Package p : mPackages.values()) {
6653                if (DEBUG_DEXOPT) {
6654                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6655                }
6656                if (!p.mDexOptPerformed.isEmpty()) {
6657                    continue;
6658                }
6659                if (pkgs == null) {
6660                    pkgs = new ArraySet<String>();
6661                }
6662                pkgs.add(p.packageName);
6663            }
6664        }
6665        return pkgs;
6666    }
6667
6668    public void shutdown() {
6669        mPackageUsage.write(true);
6670    }
6671
6672    @Override
6673    public void forceDexOpt(String packageName) {
6674        enforceSystemOrRoot("forceDexOpt");
6675
6676        PackageParser.Package pkg;
6677        synchronized (mPackages) {
6678            pkg = mPackages.get(packageName);
6679            if (pkg == null) {
6680                throw new IllegalArgumentException("Unknown package: " + packageName);
6681            }
6682        }
6683
6684        synchronized (mInstallLock) {
6685            final String[] instructionSets = new String[] {
6686                    getPrimaryInstructionSet(pkg.applicationInfo) };
6687
6688            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6689
6690            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6691                    true /* inclDependencies */);
6692
6693            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6694            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6695                throw new IllegalStateException("Failed to dexopt: " + res);
6696            }
6697        }
6698    }
6699
6700    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6701        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6702            Slog.w(TAG, "Unable to update from " + oldPkg.name
6703                    + " to " + newPkg.packageName
6704                    + ": old package not in system partition");
6705            return false;
6706        } else if (mPackages.get(oldPkg.name) != null) {
6707            Slog.w(TAG, "Unable to update from " + oldPkg.name
6708                    + " to " + newPkg.packageName
6709                    + ": old package still exists");
6710            return false;
6711        }
6712        return true;
6713    }
6714
6715    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6716            throws PackageManagerException {
6717        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6718        if (res != 0) {
6719            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6720                    "Failed to install " + packageName + ": " + res);
6721        }
6722
6723        final int[] users = sUserManager.getUserIds();
6724        for (int user : users) {
6725            if (user != 0) {
6726                res = mInstaller.createUserData(volumeUuid, packageName,
6727                        UserHandle.getUid(user, uid), user, seinfo);
6728                if (res != 0) {
6729                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6730                            "Failed to createUserData " + packageName + ": " + res);
6731                }
6732            }
6733        }
6734    }
6735
6736    private int removeDataDirsLI(String volumeUuid, String packageName) {
6737        int[] users = sUserManager.getUserIds();
6738        int res = 0;
6739        for (int user : users) {
6740            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6741            if (resInner < 0) {
6742                res = resInner;
6743            }
6744        }
6745
6746        return res;
6747    }
6748
6749    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6750        int[] users = sUserManager.getUserIds();
6751        int res = 0;
6752        for (int user : users) {
6753            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6754            if (resInner < 0) {
6755                res = resInner;
6756            }
6757        }
6758        return res;
6759    }
6760
6761    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6762            PackageParser.Package changingLib) {
6763        if (file.path != null) {
6764            usesLibraryFiles.add(file.path);
6765            return;
6766        }
6767        PackageParser.Package p = mPackages.get(file.apk);
6768        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6769            // If we are doing this while in the middle of updating a library apk,
6770            // then we need to make sure to use that new apk for determining the
6771            // dependencies here.  (We haven't yet finished committing the new apk
6772            // to the package manager state.)
6773            if (p == null || p.packageName.equals(changingLib.packageName)) {
6774                p = changingLib;
6775            }
6776        }
6777        if (p != null) {
6778            usesLibraryFiles.addAll(p.getAllCodePaths());
6779        }
6780    }
6781
6782    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6783            PackageParser.Package changingLib) throws PackageManagerException {
6784        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6785            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6786            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6787            for (int i=0; i<N; i++) {
6788                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6789                if (file == null) {
6790                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6791                            "Package " + pkg.packageName + " requires unavailable shared library "
6792                            + pkg.usesLibraries.get(i) + "; failing!");
6793                }
6794                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6795            }
6796            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6797            for (int i=0; i<N; i++) {
6798                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6799                if (file == null) {
6800                    Slog.w(TAG, "Package " + pkg.packageName
6801                            + " desires unavailable shared library "
6802                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6803                } else {
6804                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6805                }
6806            }
6807            N = usesLibraryFiles.size();
6808            if (N > 0) {
6809                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6810            } else {
6811                pkg.usesLibraryFiles = null;
6812            }
6813        }
6814    }
6815
6816    private static boolean hasString(List<String> list, List<String> which) {
6817        if (list == null) {
6818            return false;
6819        }
6820        for (int i=list.size()-1; i>=0; i--) {
6821            for (int j=which.size()-1; j>=0; j--) {
6822                if (which.get(j).equals(list.get(i))) {
6823                    return true;
6824                }
6825            }
6826        }
6827        return false;
6828    }
6829
6830    private void updateAllSharedLibrariesLPw() {
6831        for (PackageParser.Package pkg : mPackages.values()) {
6832            try {
6833                updateSharedLibrariesLPw(pkg, null);
6834            } catch (PackageManagerException e) {
6835                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6836            }
6837        }
6838    }
6839
6840    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6841            PackageParser.Package changingPkg) {
6842        ArrayList<PackageParser.Package> res = null;
6843        for (PackageParser.Package pkg : mPackages.values()) {
6844            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6845                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6846                if (res == null) {
6847                    res = new ArrayList<PackageParser.Package>();
6848                }
6849                res.add(pkg);
6850                try {
6851                    updateSharedLibrariesLPw(pkg, changingPkg);
6852                } catch (PackageManagerException e) {
6853                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6854                }
6855            }
6856        }
6857        return res;
6858    }
6859
6860    /**
6861     * Derive the value of the {@code cpuAbiOverride} based on the provided
6862     * value and an optional stored value from the package settings.
6863     */
6864    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6865        String cpuAbiOverride = null;
6866
6867        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6868            cpuAbiOverride = null;
6869        } else if (abiOverride != null) {
6870            cpuAbiOverride = abiOverride;
6871        } else if (settings != null) {
6872            cpuAbiOverride = settings.cpuAbiOverrideString;
6873        }
6874
6875        return cpuAbiOverride;
6876    }
6877
6878    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6879            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6880        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6881        try {
6882            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6883        } finally {
6884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6885        }
6886    }
6887
6888    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6889            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6890        boolean success = false;
6891        try {
6892            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6893                    currentTime, user);
6894            success = true;
6895            return res;
6896        } finally {
6897            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6898                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6899            }
6900        }
6901    }
6902
6903    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6904            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6905        final File scanFile = new File(pkg.codePath);
6906        if (pkg.applicationInfo.getCodePath() == null ||
6907                pkg.applicationInfo.getResourcePath() == null) {
6908            // Bail out. The resource and code paths haven't been set.
6909            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6910                    "Code and resource paths haven't been set correctly");
6911        }
6912
6913        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6914            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6915        } else {
6916            // Only allow system apps to be flagged as core apps.
6917            pkg.coreApp = false;
6918        }
6919
6920        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6921            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6922        }
6923
6924        if (mCustomResolverComponentName != null &&
6925                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6926            setUpCustomResolverActivity(pkg);
6927        }
6928
6929        if (pkg.packageName.equals("android")) {
6930            synchronized (mPackages) {
6931                if (mAndroidApplication != null) {
6932                    Slog.w(TAG, "*************************************************");
6933                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6934                    Slog.w(TAG, " file=" + scanFile);
6935                    Slog.w(TAG, "*************************************************");
6936                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6937                            "Core android package being redefined.  Skipping.");
6938                }
6939
6940                // Set up information for our fall-back user intent resolution activity.
6941                mPlatformPackage = pkg;
6942                pkg.mVersionCode = mSdkVersion;
6943                mAndroidApplication = pkg.applicationInfo;
6944
6945                if (!mResolverReplaced) {
6946                    mResolveActivity.applicationInfo = mAndroidApplication;
6947                    mResolveActivity.name = ResolverActivity.class.getName();
6948                    mResolveActivity.packageName = mAndroidApplication.packageName;
6949                    mResolveActivity.processName = "system:ui";
6950                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6951                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6952                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6953                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6954                    mResolveActivity.exported = true;
6955                    mResolveActivity.enabled = true;
6956                    mResolveInfo.activityInfo = mResolveActivity;
6957                    mResolveInfo.priority = 0;
6958                    mResolveInfo.preferredOrder = 0;
6959                    mResolveInfo.match = 0;
6960                    mResolveComponentName = new ComponentName(
6961                            mAndroidApplication.packageName, mResolveActivity.name);
6962                }
6963            }
6964        }
6965
6966        if (DEBUG_PACKAGE_SCANNING) {
6967            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6968                Log.d(TAG, "Scanning package " + pkg.packageName);
6969        }
6970
6971        if (mPackages.containsKey(pkg.packageName)
6972                || mSharedLibraries.containsKey(pkg.packageName)) {
6973            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6974                    "Application package " + pkg.packageName
6975                    + " already installed.  Skipping duplicate.");
6976        }
6977
6978        // If we're only installing presumed-existing packages, require that the
6979        // scanned APK is both already known and at the path previously established
6980        // for it.  Previously unknown packages we pick up normally, but if we have an
6981        // a priori expectation about this package's install presence, enforce it.
6982        // With a singular exception for new system packages. When an OTA contains
6983        // a new system package, we allow the codepath to change from a system location
6984        // to the user-installed location. If we don't allow this change, any newer,
6985        // user-installed version of the application will be ignored.
6986        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6987            if (mExpectingBetter.containsKey(pkg.packageName)) {
6988                logCriticalInfo(Log.WARN,
6989                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6990            } else {
6991                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6992                if (known != null) {
6993                    if (DEBUG_PACKAGE_SCANNING) {
6994                        Log.d(TAG, "Examining " + pkg.codePath
6995                                + " and requiring known paths " + known.codePathString
6996                                + " & " + known.resourcePathString);
6997                    }
6998                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6999                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7000                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7001                                "Application package " + pkg.packageName
7002                                + " found at " + pkg.applicationInfo.getCodePath()
7003                                + " but expected at " + known.codePathString + "; ignoring.");
7004                    }
7005                }
7006            }
7007        }
7008
7009        // Initialize package source and resource directories
7010        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7011        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7012
7013        SharedUserSetting suid = null;
7014        PackageSetting pkgSetting = null;
7015
7016        if (!isSystemApp(pkg)) {
7017            // Only system apps can use these features.
7018            pkg.mOriginalPackages = null;
7019            pkg.mRealPackage = null;
7020            pkg.mAdoptPermissions = null;
7021        }
7022
7023        // writer
7024        synchronized (mPackages) {
7025            if (pkg.mSharedUserId != null) {
7026                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7027                if (suid == null) {
7028                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7029                            "Creating application package " + pkg.packageName
7030                            + " for shared user failed");
7031                }
7032                if (DEBUG_PACKAGE_SCANNING) {
7033                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7034                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7035                                + "): packages=" + suid.packages);
7036                }
7037            }
7038
7039            // Check if we are renaming from an original package name.
7040            PackageSetting origPackage = null;
7041            String realName = null;
7042            if (pkg.mOriginalPackages != null) {
7043                // This package may need to be renamed to a previously
7044                // installed name.  Let's check on that...
7045                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7046                if (pkg.mOriginalPackages.contains(renamed)) {
7047                    // This package had originally been installed as the
7048                    // original name, and we have already taken care of
7049                    // transitioning to the new one.  Just update the new
7050                    // one to continue using the old name.
7051                    realName = pkg.mRealPackage;
7052                    if (!pkg.packageName.equals(renamed)) {
7053                        // Callers into this function may have already taken
7054                        // care of renaming the package; only do it here if
7055                        // it is not already done.
7056                        pkg.setPackageName(renamed);
7057                    }
7058
7059                } else {
7060                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7061                        if ((origPackage = mSettings.peekPackageLPr(
7062                                pkg.mOriginalPackages.get(i))) != null) {
7063                            // We do have the package already installed under its
7064                            // original name...  should we use it?
7065                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7066                                // New package is not compatible with original.
7067                                origPackage = null;
7068                                continue;
7069                            } else if (origPackage.sharedUser != null) {
7070                                // Make sure uid is compatible between packages.
7071                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7072                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7073                                            + " to " + pkg.packageName + ": old uid "
7074                                            + origPackage.sharedUser.name
7075                                            + " differs from " + pkg.mSharedUserId);
7076                                    origPackage = null;
7077                                    continue;
7078                                }
7079                            } else {
7080                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7081                                        + pkg.packageName + " to old name " + origPackage.name);
7082                            }
7083                            break;
7084                        }
7085                    }
7086                }
7087            }
7088
7089            if (mTransferedPackages.contains(pkg.packageName)) {
7090                Slog.w(TAG, "Package " + pkg.packageName
7091                        + " was transferred to another, but its .apk remains");
7092            }
7093
7094            // Just create the setting, don't add it yet. For already existing packages
7095            // the PkgSetting exists already and doesn't have to be created.
7096            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7097                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7098                    pkg.applicationInfo.primaryCpuAbi,
7099                    pkg.applicationInfo.secondaryCpuAbi,
7100                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7101                    user, false);
7102            if (pkgSetting == null) {
7103                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7104                        "Creating application package " + pkg.packageName + " failed");
7105            }
7106
7107            if (pkgSetting.origPackage != null) {
7108                // If we are first transitioning from an original package,
7109                // fix up the new package's name now.  We need to do this after
7110                // looking up the package under its new name, so getPackageLP
7111                // can take care of fiddling things correctly.
7112                pkg.setPackageName(origPackage.name);
7113
7114                // File a report about this.
7115                String msg = "New package " + pkgSetting.realName
7116                        + " renamed to replace old package " + pkgSetting.name;
7117                reportSettingsProblem(Log.WARN, msg);
7118
7119                // Make a note of it.
7120                mTransferedPackages.add(origPackage.name);
7121
7122                // No longer need to retain this.
7123                pkgSetting.origPackage = null;
7124            }
7125
7126            if (realName != null) {
7127                // Make a note of it.
7128                mTransferedPackages.add(pkg.packageName);
7129            }
7130
7131            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7132                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7133            }
7134
7135            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7136                // Check all shared libraries and map to their actual file path.
7137                // We only do this here for apps not on a system dir, because those
7138                // are the only ones that can fail an install due to this.  We
7139                // will take care of the system apps by updating all of their
7140                // library paths after the scan is done.
7141                updateSharedLibrariesLPw(pkg, null);
7142            }
7143
7144            if (mFoundPolicyFile) {
7145                SELinuxMMAC.assignSeinfoValue(pkg);
7146            }
7147
7148            pkg.applicationInfo.uid = pkgSetting.appId;
7149            pkg.mExtras = pkgSetting;
7150            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7151                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7152                    // We just determined the app is signed correctly, so bring
7153                    // over the latest parsed certs.
7154                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7155                } else {
7156                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7157                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7158                                "Package " + pkg.packageName + " upgrade keys do not match the "
7159                                + "previously installed version");
7160                    } else {
7161                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7162                        String msg = "System package " + pkg.packageName
7163                            + " signature changed; retaining data.";
7164                        reportSettingsProblem(Log.WARN, msg);
7165                    }
7166                }
7167            } else {
7168                try {
7169                    verifySignaturesLP(pkgSetting, pkg);
7170                    // We just determined the app is signed correctly, so bring
7171                    // over the latest parsed certs.
7172                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7173                } catch (PackageManagerException e) {
7174                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7175                        throw e;
7176                    }
7177                    // The signature has changed, but this package is in the system
7178                    // image...  let's recover!
7179                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7180                    // However...  if this package is part of a shared user, but it
7181                    // doesn't match the signature of the shared user, let's fail.
7182                    // What this means is that you can't change the signatures
7183                    // associated with an overall shared user, which doesn't seem all
7184                    // that unreasonable.
7185                    if (pkgSetting.sharedUser != null) {
7186                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7187                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7188                            throw new PackageManagerException(
7189                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7190                                            "Signature mismatch for shared user: "
7191                                            + pkgSetting.sharedUser);
7192                        }
7193                    }
7194                    // File a report about this.
7195                    String msg = "System package " + pkg.packageName
7196                        + " signature changed; retaining data.";
7197                    reportSettingsProblem(Log.WARN, msg);
7198                }
7199            }
7200            // Verify that this new package doesn't have any content providers
7201            // that conflict with existing packages.  Only do this if the
7202            // package isn't already installed, since we don't want to break
7203            // things that are installed.
7204            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7205                final int N = pkg.providers.size();
7206                int i;
7207                for (i=0; i<N; i++) {
7208                    PackageParser.Provider p = pkg.providers.get(i);
7209                    if (p.info.authority != null) {
7210                        String names[] = p.info.authority.split(";");
7211                        for (int j = 0; j < names.length; j++) {
7212                            if (mProvidersByAuthority.containsKey(names[j])) {
7213                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7214                                final String otherPackageName =
7215                                        ((other != null && other.getComponentName() != null) ?
7216                                                other.getComponentName().getPackageName() : "?");
7217                                throw new PackageManagerException(
7218                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7219                                                "Can't install because provider name " + names[j]
7220                                                + " (in package " + pkg.applicationInfo.packageName
7221                                                + ") is already used by " + otherPackageName);
7222                            }
7223                        }
7224                    }
7225                }
7226            }
7227
7228            if (pkg.mAdoptPermissions != null) {
7229                // This package wants to adopt ownership of permissions from
7230                // another package.
7231                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7232                    final String origName = pkg.mAdoptPermissions.get(i);
7233                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7234                    if (orig != null) {
7235                        if (verifyPackageUpdateLPr(orig, pkg)) {
7236                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7237                                    + pkg.packageName);
7238                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7239                        }
7240                    }
7241                }
7242            }
7243        }
7244
7245        final String pkgName = pkg.packageName;
7246
7247        final long scanFileTime = scanFile.lastModified();
7248        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7249        pkg.applicationInfo.processName = fixProcessName(
7250                pkg.applicationInfo.packageName,
7251                pkg.applicationInfo.processName,
7252                pkg.applicationInfo.uid);
7253
7254        if (pkg != mPlatformPackage) {
7255            // This is a normal package, need to make its data directory.
7256            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7257                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7258
7259            boolean uidError = false;
7260            if (dataPath.exists()) {
7261                int currentUid = 0;
7262                try {
7263                    StructStat stat = Os.stat(dataPath.getPath());
7264                    currentUid = stat.st_uid;
7265                } catch (ErrnoException e) {
7266                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7267                }
7268
7269                // If we have mismatched owners for the data path, we have a problem.
7270                if (currentUid != pkg.applicationInfo.uid) {
7271                    boolean recovered = false;
7272                    if (currentUid == 0) {
7273                        // The directory somehow became owned by root.  Wow.
7274                        // This is probably because the system was stopped while
7275                        // installd was in the middle of messing with its libs
7276                        // directory.  Ask installd to fix that.
7277                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7278                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7279                        if (ret >= 0) {
7280                            recovered = true;
7281                            String msg = "Package " + pkg.packageName
7282                                    + " unexpectedly changed to uid 0; recovered to " +
7283                                    + pkg.applicationInfo.uid;
7284                            reportSettingsProblem(Log.WARN, msg);
7285                        }
7286                    }
7287                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7288                            || (scanFlags&SCAN_BOOTING) != 0)) {
7289                        // If this is a system app, we can at least delete its
7290                        // current data so the application will still work.
7291                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7292                        if (ret >= 0) {
7293                            // TODO: Kill the processes first
7294                            // Old data gone!
7295                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7296                                    ? "System package " : "Third party package ";
7297                            String msg = prefix + pkg.packageName
7298                                    + " has changed from uid: "
7299                                    + currentUid + " to "
7300                                    + pkg.applicationInfo.uid + "; old data erased";
7301                            reportSettingsProblem(Log.WARN, msg);
7302                            recovered = true;
7303                        }
7304                        if (!recovered) {
7305                            mHasSystemUidErrors = true;
7306                        }
7307                    } else if (!recovered) {
7308                        // If we allow this install to proceed, we will be broken.
7309                        // Abort, abort!
7310                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7311                                "scanPackageLI");
7312                    }
7313                    if (!recovered) {
7314                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7315                            + pkg.applicationInfo.uid + "/fs_"
7316                            + currentUid;
7317                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7318                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7319                        String msg = "Package " + pkg.packageName
7320                                + " has mismatched uid: "
7321                                + currentUid + " on disk, "
7322                                + pkg.applicationInfo.uid + " in settings";
7323                        // writer
7324                        synchronized (mPackages) {
7325                            mSettings.mReadMessages.append(msg);
7326                            mSettings.mReadMessages.append('\n');
7327                            uidError = true;
7328                            if (!pkgSetting.uidError) {
7329                                reportSettingsProblem(Log.ERROR, msg);
7330                            }
7331                        }
7332                    }
7333                }
7334
7335                // Ensure that directories are prepared
7336                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7337                        pkg.applicationInfo.seinfo);
7338
7339                if (mShouldRestoreconData) {
7340                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7341                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7342                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7343                }
7344            } else {
7345                if (DEBUG_PACKAGE_SCANNING) {
7346                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7347                        Log.v(TAG, "Want this data dir: " + dataPath);
7348                }
7349                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7350                        pkg.applicationInfo.seinfo);
7351            }
7352
7353            // Get all of our default paths setup
7354            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7355
7356            pkgSetting.uidError = uidError;
7357        }
7358
7359        final String path = scanFile.getPath();
7360        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7361
7362        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7363            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7364
7365            // Some system apps still use directory structure for native libraries
7366            // in which case we might end up not detecting abi solely based on apk
7367            // structure. Try to detect abi based on directory structure.
7368            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7369                    pkg.applicationInfo.primaryCpuAbi == null) {
7370                setBundledAppAbisAndRoots(pkg, pkgSetting);
7371                setNativeLibraryPaths(pkg);
7372            }
7373
7374        } else {
7375            if ((scanFlags & SCAN_MOVE) != 0) {
7376                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7377                // but we already have this packages package info in the PackageSetting. We just
7378                // use that and derive the native library path based on the new codepath.
7379                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7380                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7381            }
7382
7383            // Set native library paths again. For moves, the path will be updated based on the
7384            // ABIs we've determined above. For non-moves, the path will be updated based on the
7385            // ABIs we determined during compilation, but the path will depend on the final
7386            // package path (after the rename away from the stage path).
7387            setNativeLibraryPaths(pkg);
7388        }
7389
7390        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7391        final int[] userIds = sUserManager.getUserIds();
7392        synchronized (mInstallLock) {
7393            // Make sure all user data directories are ready to roll; we're okay
7394            // if they already exist
7395            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7396                for (int userId : userIds) {
7397                    if (userId != UserHandle.USER_SYSTEM) {
7398                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7399                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7400                                pkg.applicationInfo.seinfo);
7401                    }
7402                }
7403            }
7404
7405            // Create a native library symlink only if we have native libraries
7406            // and if the native libraries are 32 bit libraries. We do not provide
7407            // this symlink for 64 bit libraries.
7408            if (pkg.applicationInfo.primaryCpuAbi != null &&
7409                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7410                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7411                try {
7412                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7413                    for (int userId : userIds) {
7414                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7415                                nativeLibPath, userId) < 0) {
7416                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7417                                    "Failed linking native library dir (user=" + userId + ")");
7418                        }
7419                    }
7420                } finally {
7421                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7422                }
7423            }
7424        }
7425
7426        // This is a special case for the "system" package, where the ABI is
7427        // dictated by the zygote configuration (and init.rc). We should keep track
7428        // of this ABI so that we can deal with "normal" applications that run under
7429        // the same UID correctly.
7430        if (mPlatformPackage == pkg) {
7431            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7432                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7433        }
7434
7435        // If there's a mismatch between the abi-override in the package setting
7436        // and the abiOverride specified for the install. Warn about this because we
7437        // would've already compiled the app without taking the package setting into
7438        // account.
7439        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7440            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7441                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7442                        " for package " + pkg.packageName);
7443            }
7444        }
7445
7446        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7447        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7448        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7449
7450        // Copy the derived override back to the parsed package, so that we can
7451        // update the package settings accordingly.
7452        pkg.cpuAbiOverride = cpuAbiOverride;
7453
7454        if (DEBUG_ABI_SELECTION) {
7455            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7456                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7457                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7458        }
7459
7460        // Push the derived path down into PackageSettings so we know what to
7461        // clean up at uninstall time.
7462        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7463
7464        if (DEBUG_ABI_SELECTION) {
7465            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7466                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7467                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7468        }
7469
7470        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7471            // We don't do this here during boot because we can do it all
7472            // at once after scanning all existing packages.
7473            //
7474            // We also do this *before* we perform dexopt on this package, so that
7475            // we can avoid redundant dexopts, and also to make sure we've got the
7476            // code and package path correct.
7477            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7478                    pkg, true /* boot complete */);
7479        }
7480
7481        if (mFactoryTest && pkg.requestedPermissions.contains(
7482                android.Manifest.permission.FACTORY_TEST)) {
7483            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7484        }
7485
7486        ArrayList<PackageParser.Package> clientLibPkgs = null;
7487
7488        // writer
7489        synchronized (mPackages) {
7490            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7491                // Only system apps can add new shared libraries.
7492                if (pkg.libraryNames != null) {
7493                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7494                        String name = pkg.libraryNames.get(i);
7495                        boolean allowed = false;
7496                        if (pkg.isUpdatedSystemApp()) {
7497                            // New library entries can only be added through the
7498                            // system image.  This is important to get rid of a lot
7499                            // of nasty edge cases: for example if we allowed a non-
7500                            // system update of the app to add a library, then uninstalling
7501                            // the update would make the library go away, and assumptions
7502                            // we made such as through app install filtering would now
7503                            // have allowed apps on the device which aren't compatible
7504                            // with it.  Better to just have the restriction here, be
7505                            // conservative, and create many fewer cases that can negatively
7506                            // impact the user experience.
7507                            final PackageSetting sysPs = mSettings
7508                                    .getDisabledSystemPkgLPr(pkg.packageName);
7509                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7510                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7511                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7512                                        allowed = true;
7513                                        break;
7514                                    }
7515                                }
7516                            }
7517                        } else {
7518                            allowed = true;
7519                        }
7520                        if (allowed) {
7521                            if (!mSharedLibraries.containsKey(name)) {
7522                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7523                            } else if (!name.equals(pkg.packageName)) {
7524                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7525                                        + name + " already exists; skipping");
7526                            }
7527                        } else {
7528                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7529                                    + name + " that is not declared on system image; skipping");
7530                        }
7531                    }
7532                    if ((scanFlags & SCAN_BOOTING) == 0) {
7533                        // If we are not booting, we need to update any applications
7534                        // that are clients of our shared library.  If we are booting,
7535                        // this will all be done once the scan is complete.
7536                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7537                    }
7538                }
7539            }
7540        }
7541
7542        // Request the ActivityManager to kill the process(only for existing packages)
7543        // so that we do not end up in a confused state while the user is still using the older
7544        // version of the application while the new one gets installed.
7545        if ((scanFlags & SCAN_REPLACING) != 0) {
7546            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7547
7548            killApplication(pkg.applicationInfo.packageName,
7549                        pkg.applicationInfo.uid, "replace pkg");
7550
7551            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7552        }
7553
7554        // Also need to kill any apps that are dependent on the library.
7555        if (clientLibPkgs != null) {
7556            for (int i=0; i<clientLibPkgs.size(); i++) {
7557                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7558                killApplication(clientPkg.applicationInfo.packageName,
7559                        clientPkg.applicationInfo.uid, "update lib");
7560            }
7561        }
7562
7563        // Make sure we're not adding any bogus keyset info
7564        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7565        ksms.assertScannedPackageValid(pkg);
7566
7567        // writer
7568        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7569
7570        boolean createIdmapFailed = false;
7571        synchronized (mPackages) {
7572            // We don't expect installation to fail beyond this point
7573
7574            // Add the new setting to mSettings
7575            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7576            // Add the new setting to mPackages
7577            mPackages.put(pkg.applicationInfo.packageName, pkg);
7578            // Make sure we don't accidentally delete its data.
7579            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7580            while (iter.hasNext()) {
7581                PackageCleanItem item = iter.next();
7582                if (pkgName.equals(item.packageName)) {
7583                    iter.remove();
7584                }
7585            }
7586
7587            // Take care of first install / last update times.
7588            if (currentTime != 0) {
7589                if (pkgSetting.firstInstallTime == 0) {
7590                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7591                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7592                    pkgSetting.lastUpdateTime = currentTime;
7593                }
7594            } else if (pkgSetting.firstInstallTime == 0) {
7595                // We need *something*.  Take time time stamp of the file.
7596                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7597            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7598                if (scanFileTime != pkgSetting.timeStamp) {
7599                    // A package on the system image has changed; consider this
7600                    // to be an update.
7601                    pkgSetting.lastUpdateTime = scanFileTime;
7602                }
7603            }
7604
7605            // Add the package's KeySets to the global KeySetManagerService
7606            ksms.addScannedPackageLPw(pkg);
7607
7608            int N = pkg.providers.size();
7609            StringBuilder r = null;
7610            int i;
7611            for (i=0; i<N; i++) {
7612                PackageParser.Provider p = pkg.providers.get(i);
7613                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7614                        p.info.processName, pkg.applicationInfo.uid);
7615                mProviders.addProvider(p);
7616                p.syncable = p.info.isSyncable;
7617                if (p.info.authority != null) {
7618                    String names[] = p.info.authority.split(";");
7619                    p.info.authority = null;
7620                    for (int j = 0; j < names.length; j++) {
7621                        if (j == 1 && p.syncable) {
7622                            // We only want the first authority for a provider to possibly be
7623                            // syncable, so if we already added this provider using a different
7624                            // authority clear the syncable flag. We copy the provider before
7625                            // changing it because the mProviders object contains a reference
7626                            // to a provider that we don't want to change.
7627                            // Only do this for the second authority since the resulting provider
7628                            // object can be the same for all future authorities for this provider.
7629                            p = new PackageParser.Provider(p);
7630                            p.syncable = false;
7631                        }
7632                        if (!mProvidersByAuthority.containsKey(names[j])) {
7633                            mProvidersByAuthority.put(names[j], p);
7634                            if (p.info.authority == null) {
7635                                p.info.authority = names[j];
7636                            } else {
7637                                p.info.authority = p.info.authority + ";" + names[j];
7638                            }
7639                            if (DEBUG_PACKAGE_SCANNING) {
7640                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7641                                    Log.d(TAG, "Registered content provider: " + names[j]
7642                                            + ", className = " + p.info.name + ", isSyncable = "
7643                                            + p.info.isSyncable);
7644                            }
7645                        } else {
7646                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7647                            Slog.w(TAG, "Skipping provider name " + names[j] +
7648                                    " (in package " + pkg.applicationInfo.packageName +
7649                                    "): name already used by "
7650                                    + ((other != null && other.getComponentName() != null)
7651                                            ? other.getComponentName().getPackageName() : "?"));
7652                        }
7653                    }
7654                }
7655                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7656                    if (r == null) {
7657                        r = new StringBuilder(256);
7658                    } else {
7659                        r.append(' ');
7660                    }
7661                    r.append(p.info.name);
7662                }
7663            }
7664            if (r != null) {
7665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7666            }
7667
7668            N = pkg.services.size();
7669            r = null;
7670            for (i=0; i<N; i++) {
7671                PackageParser.Service s = pkg.services.get(i);
7672                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7673                        s.info.processName, pkg.applicationInfo.uid);
7674                mServices.addService(s);
7675                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7676                    if (r == null) {
7677                        r = new StringBuilder(256);
7678                    } else {
7679                        r.append(' ');
7680                    }
7681                    r.append(s.info.name);
7682                }
7683            }
7684            if (r != null) {
7685                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7686            }
7687
7688            N = pkg.receivers.size();
7689            r = null;
7690            for (i=0; i<N; i++) {
7691                PackageParser.Activity a = pkg.receivers.get(i);
7692                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7693                        a.info.processName, pkg.applicationInfo.uid);
7694                mReceivers.addActivity(a, "receiver");
7695                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7696                    if (r == null) {
7697                        r = new StringBuilder(256);
7698                    } else {
7699                        r.append(' ');
7700                    }
7701                    r.append(a.info.name);
7702                }
7703            }
7704            if (r != null) {
7705                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7706            }
7707
7708            N = pkg.activities.size();
7709            r = null;
7710            for (i=0; i<N; i++) {
7711                PackageParser.Activity a = pkg.activities.get(i);
7712                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7713                        a.info.processName, pkg.applicationInfo.uid);
7714                mActivities.addActivity(a, "activity");
7715                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7716                    if (r == null) {
7717                        r = new StringBuilder(256);
7718                    } else {
7719                        r.append(' ');
7720                    }
7721                    r.append(a.info.name);
7722                }
7723            }
7724            if (r != null) {
7725                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7726            }
7727
7728            N = pkg.permissionGroups.size();
7729            r = null;
7730            for (i=0; i<N; i++) {
7731                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7732                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7733                if (cur == null) {
7734                    mPermissionGroups.put(pg.info.name, pg);
7735                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7736                        if (r == null) {
7737                            r = new StringBuilder(256);
7738                        } else {
7739                            r.append(' ');
7740                        }
7741                        r.append(pg.info.name);
7742                    }
7743                } else {
7744                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7745                            + pg.info.packageName + " ignored: original from "
7746                            + cur.info.packageName);
7747                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7748                        if (r == null) {
7749                            r = new StringBuilder(256);
7750                        } else {
7751                            r.append(' ');
7752                        }
7753                        r.append("DUP:");
7754                        r.append(pg.info.name);
7755                    }
7756                }
7757            }
7758            if (r != null) {
7759                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7760            }
7761
7762            N = pkg.permissions.size();
7763            r = null;
7764            for (i=0; i<N; i++) {
7765                PackageParser.Permission p = pkg.permissions.get(i);
7766
7767                // Assume by default that we did not install this permission into the system.
7768                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7769
7770                // Now that permission groups have a special meaning, we ignore permission
7771                // groups for legacy apps to prevent unexpected behavior. In particular,
7772                // permissions for one app being granted to someone just becuase they happen
7773                // to be in a group defined by another app (before this had no implications).
7774                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7775                    p.group = mPermissionGroups.get(p.info.group);
7776                    // Warn for a permission in an unknown group.
7777                    if (p.info.group != null && p.group == null) {
7778                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7779                                + p.info.packageName + " in an unknown group " + p.info.group);
7780                    }
7781                }
7782
7783                ArrayMap<String, BasePermission> permissionMap =
7784                        p.tree ? mSettings.mPermissionTrees
7785                                : mSettings.mPermissions;
7786                BasePermission bp = permissionMap.get(p.info.name);
7787
7788                // Allow system apps to redefine non-system permissions
7789                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7790                    final boolean currentOwnerIsSystem = (bp.perm != null
7791                            && isSystemApp(bp.perm.owner));
7792                    if (isSystemApp(p.owner)) {
7793                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7794                            // It's a built-in permission and no owner, take ownership now
7795                            bp.packageSetting = pkgSetting;
7796                            bp.perm = p;
7797                            bp.uid = pkg.applicationInfo.uid;
7798                            bp.sourcePackage = p.info.packageName;
7799                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7800                        } else if (!currentOwnerIsSystem) {
7801                            String msg = "New decl " + p.owner + " of permission  "
7802                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7803                            reportSettingsProblem(Log.WARN, msg);
7804                            bp = null;
7805                        }
7806                    }
7807                }
7808
7809                if (bp == null) {
7810                    bp = new BasePermission(p.info.name, p.info.packageName,
7811                            BasePermission.TYPE_NORMAL);
7812                    permissionMap.put(p.info.name, bp);
7813                }
7814
7815                if (bp.perm == null) {
7816                    if (bp.sourcePackage == null
7817                            || bp.sourcePackage.equals(p.info.packageName)) {
7818                        BasePermission tree = findPermissionTreeLP(p.info.name);
7819                        if (tree == null
7820                                || tree.sourcePackage.equals(p.info.packageName)) {
7821                            bp.packageSetting = pkgSetting;
7822                            bp.perm = p;
7823                            bp.uid = pkg.applicationInfo.uid;
7824                            bp.sourcePackage = p.info.packageName;
7825                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7826                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7827                                if (r == null) {
7828                                    r = new StringBuilder(256);
7829                                } else {
7830                                    r.append(' ');
7831                                }
7832                                r.append(p.info.name);
7833                            }
7834                        } else {
7835                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7836                                    + p.info.packageName + " ignored: base tree "
7837                                    + tree.name + " is from package "
7838                                    + tree.sourcePackage);
7839                        }
7840                    } else {
7841                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7842                                + p.info.packageName + " ignored: original from "
7843                                + bp.sourcePackage);
7844                    }
7845                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7846                    if (r == null) {
7847                        r = new StringBuilder(256);
7848                    } else {
7849                        r.append(' ');
7850                    }
7851                    r.append("DUP:");
7852                    r.append(p.info.name);
7853                }
7854                if (bp.perm == p) {
7855                    bp.protectionLevel = p.info.protectionLevel;
7856                }
7857            }
7858
7859            if (r != null) {
7860                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7861            }
7862
7863            N = pkg.instrumentation.size();
7864            r = null;
7865            for (i=0; i<N; i++) {
7866                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7867                a.info.packageName = pkg.applicationInfo.packageName;
7868                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7869                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7870                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7871                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7872                a.info.dataDir = pkg.applicationInfo.dataDir;
7873                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7874                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7875
7876                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7877                // need other information about the application, like the ABI and what not ?
7878                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7879                mInstrumentation.put(a.getComponentName(), a);
7880                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7881                    if (r == null) {
7882                        r = new StringBuilder(256);
7883                    } else {
7884                        r.append(' ');
7885                    }
7886                    r.append(a.info.name);
7887                }
7888            }
7889            if (r != null) {
7890                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7891            }
7892
7893            if (pkg.protectedBroadcasts != null) {
7894                N = pkg.protectedBroadcasts.size();
7895                for (i=0; i<N; i++) {
7896                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7897                }
7898            }
7899
7900            pkgSetting.setTimeStamp(scanFileTime);
7901
7902            // Create idmap files for pairs of (packages, overlay packages).
7903            // Note: "android", ie framework-res.apk, is handled by native layers.
7904            if (pkg.mOverlayTarget != null) {
7905                // This is an overlay package.
7906                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7907                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7908                        mOverlays.put(pkg.mOverlayTarget,
7909                                new ArrayMap<String, PackageParser.Package>());
7910                    }
7911                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7912                    map.put(pkg.packageName, pkg);
7913                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7914                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7915                        createIdmapFailed = true;
7916                    }
7917                }
7918            } else if (mOverlays.containsKey(pkg.packageName) &&
7919                    !pkg.packageName.equals("android")) {
7920                // This is a regular package, with one or more known overlay packages.
7921                createIdmapsForPackageLI(pkg);
7922            }
7923        }
7924
7925        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7926
7927        if (createIdmapFailed) {
7928            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7929                    "scanPackageLI failed to createIdmap");
7930        }
7931        return pkg;
7932    }
7933
7934    /**
7935     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7936     * is derived purely on the basis of the contents of {@code scanFile} and
7937     * {@code cpuAbiOverride}.
7938     *
7939     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7940     */
7941    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7942                                 String cpuAbiOverride, boolean extractLibs)
7943            throws PackageManagerException {
7944        // TODO: We can probably be smarter about this stuff. For installed apps,
7945        // we can calculate this information at install time once and for all. For
7946        // system apps, we can probably assume that this information doesn't change
7947        // after the first boot scan. As things stand, we do lots of unnecessary work.
7948
7949        // Give ourselves some initial paths; we'll come back for another
7950        // pass once we've determined ABI below.
7951        setNativeLibraryPaths(pkg);
7952
7953        // We would never need to extract libs for forward-locked and external packages,
7954        // since the container service will do it for us. We shouldn't attempt to
7955        // extract libs from system app when it was not updated.
7956        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7957                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7958            extractLibs = false;
7959        }
7960
7961        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7962        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7963
7964        NativeLibraryHelper.Handle handle = null;
7965        try {
7966            handle = NativeLibraryHelper.Handle.create(pkg);
7967            // TODO(multiArch): This can be null for apps that didn't go through the
7968            // usual installation process. We can calculate it again, like we
7969            // do during install time.
7970            //
7971            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7972            // unnecessary.
7973            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7974
7975            // Null out the abis so that they can be recalculated.
7976            pkg.applicationInfo.primaryCpuAbi = null;
7977            pkg.applicationInfo.secondaryCpuAbi = null;
7978            if (isMultiArch(pkg.applicationInfo)) {
7979                // Warn if we've set an abiOverride for multi-lib packages..
7980                // By definition, we need to copy both 32 and 64 bit libraries for
7981                // such packages.
7982                if (pkg.cpuAbiOverride != null
7983                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7984                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7985                }
7986
7987                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7988                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7989                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7990                    if (extractLibs) {
7991                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7992                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7993                                useIsaSpecificSubdirs);
7994                    } else {
7995                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7996                    }
7997                }
7998
7999                maybeThrowExceptionForMultiArchCopy(
8000                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8001
8002                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8003                    if (extractLibs) {
8004                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8005                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8006                                useIsaSpecificSubdirs);
8007                    } else {
8008                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8009                    }
8010                }
8011
8012                maybeThrowExceptionForMultiArchCopy(
8013                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8014
8015                if (abi64 >= 0) {
8016                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8017                }
8018
8019                if (abi32 >= 0) {
8020                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8021                    if (abi64 >= 0) {
8022                        pkg.applicationInfo.secondaryCpuAbi = abi;
8023                    } else {
8024                        pkg.applicationInfo.primaryCpuAbi = abi;
8025                    }
8026                }
8027            } else {
8028                String[] abiList = (cpuAbiOverride != null) ?
8029                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8030
8031                // Enable gross and lame hacks for apps that are built with old
8032                // SDK tools. We must scan their APKs for renderscript bitcode and
8033                // not launch them if it's present. Don't bother checking on devices
8034                // that don't have 64 bit support.
8035                boolean needsRenderScriptOverride = false;
8036                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8037                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8038                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8039                    needsRenderScriptOverride = true;
8040                }
8041
8042                final int copyRet;
8043                if (extractLibs) {
8044                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8045                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8046                } else {
8047                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8048                }
8049
8050                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8051                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8052                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8053                }
8054
8055                if (copyRet >= 0) {
8056                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8057                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8058                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8059                } else if (needsRenderScriptOverride) {
8060                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8061                }
8062            }
8063        } catch (IOException ioe) {
8064            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8065        } finally {
8066            IoUtils.closeQuietly(handle);
8067        }
8068
8069        // Now that we've calculated the ABIs and determined if it's an internal app,
8070        // we will go ahead and populate the nativeLibraryPath.
8071        setNativeLibraryPaths(pkg);
8072    }
8073
8074    /**
8075     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8076     * i.e, so that all packages can be run inside a single process if required.
8077     *
8078     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8079     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8080     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8081     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8082     * updating a package that belongs to a shared user.
8083     *
8084     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8085     * adds unnecessary complexity.
8086     */
8087    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8088            PackageParser.Package scannedPackage, boolean bootComplete) {
8089        String requiredInstructionSet = null;
8090        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8091            requiredInstructionSet = VMRuntime.getInstructionSet(
8092                     scannedPackage.applicationInfo.primaryCpuAbi);
8093        }
8094
8095        PackageSetting requirer = null;
8096        for (PackageSetting ps : packagesForUser) {
8097            // If packagesForUser contains scannedPackage, we skip it. This will happen
8098            // when scannedPackage is an update of an existing package. Without this check,
8099            // we will never be able to change the ABI of any package belonging to a shared
8100            // user, even if it's compatible with other packages.
8101            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8102                if (ps.primaryCpuAbiString == null) {
8103                    continue;
8104                }
8105
8106                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8107                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8108                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8109                    // this but there's not much we can do.
8110                    String errorMessage = "Instruction set mismatch, "
8111                            + ((requirer == null) ? "[caller]" : requirer)
8112                            + " requires " + requiredInstructionSet + " whereas " + ps
8113                            + " requires " + instructionSet;
8114                    Slog.w(TAG, errorMessage);
8115                }
8116
8117                if (requiredInstructionSet == null) {
8118                    requiredInstructionSet = instructionSet;
8119                    requirer = ps;
8120                }
8121            }
8122        }
8123
8124        if (requiredInstructionSet != null) {
8125            String adjustedAbi;
8126            if (requirer != null) {
8127                // requirer != null implies that either scannedPackage was null or that scannedPackage
8128                // did not require an ABI, in which case we have to adjust scannedPackage to match
8129                // the ABI of the set (which is the same as requirer's ABI)
8130                adjustedAbi = requirer.primaryCpuAbiString;
8131                if (scannedPackage != null) {
8132                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8133                }
8134            } else {
8135                // requirer == null implies that we're updating all ABIs in the set to
8136                // match scannedPackage.
8137                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8138            }
8139
8140            for (PackageSetting ps : packagesForUser) {
8141                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8142                    if (ps.primaryCpuAbiString != null) {
8143                        continue;
8144                    }
8145
8146                    ps.primaryCpuAbiString = adjustedAbi;
8147                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8148                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8149                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8150                        mInstaller.rmdex(ps.codePathString,
8151                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8152                    }
8153                }
8154            }
8155        }
8156    }
8157
8158    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8159        synchronized (mPackages) {
8160            mResolverReplaced = true;
8161            // Set up information for custom user intent resolution activity.
8162            mResolveActivity.applicationInfo = pkg.applicationInfo;
8163            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8164            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8165            mResolveActivity.processName = pkg.applicationInfo.packageName;
8166            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8167            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8168                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8169            mResolveActivity.theme = 0;
8170            mResolveActivity.exported = true;
8171            mResolveActivity.enabled = true;
8172            mResolveInfo.activityInfo = mResolveActivity;
8173            mResolveInfo.priority = 0;
8174            mResolveInfo.preferredOrder = 0;
8175            mResolveInfo.match = 0;
8176            mResolveComponentName = mCustomResolverComponentName;
8177            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8178                    mResolveComponentName);
8179        }
8180    }
8181
8182    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8183        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8184
8185        // Set up information for ephemeral installer activity
8186        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8187        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8188        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8189        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8190        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8191        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8192                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8193        mEphemeralInstallerActivity.theme = 0;
8194        mEphemeralInstallerActivity.exported = true;
8195        mEphemeralInstallerActivity.enabled = true;
8196        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8197        mEphemeralInstallerInfo.priority = 0;
8198        mEphemeralInstallerInfo.preferredOrder = 0;
8199        mEphemeralInstallerInfo.match = 0;
8200
8201        if (DEBUG_EPHEMERAL) {
8202            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8203        }
8204    }
8205
8206    private static String calculateBundledApkRoot(final String codePathString) {
8207        final File codePath = new File(codePathString);
8208        final File codeRoot;
8209        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8210            codeRoot = Environment.getRootDirectory();
8211        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8212            codeRoot = Environment.getOemDirectory();
8213        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8214            codeRoot = Environment.getVendorDirectory();
8215        } else {
8216            // Unrecognized code path; take its top real segment as the apk root:
8217            // e.g. /something/app/blah.apk => /something
8218            try {
8219                File f = codePath.getCanonicalFile();
8220                File parent = f.getParentFile();    // non-null because codePath is a file
8221                File tmp;
8222                while ((tmp = parent.getParentFile()) != null) {
8223                    f = parent;
8224                    parent = tmp;
8225                }
8226                codeRoot = f;
8227                Slog.w(TAG, "Unrecognized code path "
8228                        + codePath + " - using " + codeRoot);
8229            } catch (IOException e) {
8230                // Can't canonicalize the code path -- shenanigans?
8231                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8232                return Environment.getRootDirectory().getPath();
8233            }
8234        }
8235        return codeRoot.getPath();
8236    }
8237
8238    /**
8239     * Derive and set the location of native libraries for the given package,
8240     * which varies depending on where and how the package was installed.
8241     */
8242    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8243        final ApplicationInfo info = pkg.applicationInfo;
8244        final String codePath = pkg.codePath;
8245        final File codeFile = new File(codePath);
8246        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8247        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8248
8249        info.nativeLibraryRootDir = null;
8250        info.nativeLibraryRootRequiresIsa = false;
8251        info.nativeLibraryDir = null;
8252        info.secondaryNativeLibraryDir = null;
8253
8254        if (isApkFile(codeFile)) {
8255            // Monolithic install
8256            if (bundledApp) {
8257                // If "/system/lib64/apkname" exists, assume that is the per-package
8258                // native library directory to use; otherwise use "/system/lib/apkname".
8259                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8260                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8261                        getPrimaryInstructionSet(info));
8262
8263                // This is a bundled system app so choose the path based on the ABI.
8264                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8265                // is just the default path.
8266                final String apkName = deriveCodePathName(codePath);
8267                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8268                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8269                        apkName).getAbsolutePath();
8270
8271                if (info.secondaryCpuAbi != null) {
8272                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8273                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8274                            secondaryLibDir, apkName).getAbsolutePath();
8275                }
8276            } else if (asecApp) {
8277                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8278                        .getAbsolutePath();
8279            } else {
8280                final String apkName = deriveCodePathName(codePath);
8281                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8282                        .getAbsolutePath();
8283            }
8284
8285            info.nativeLibraryRootRequiresIsa = false;
8286            info.nativeLibraryDir = info.nativeLibraryRootDir;
8287        } else {
8288            // Cluster install
8289            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8290            info.nativeLibraryRootRequiresIsa = true;
8291
8292            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8293                    getPrimaryInstructionSet(info)).getAbsolutePath();
8294
8295            if (info.secondaryCpuAbi != null) {
8296                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8297                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8298            }
8299        }
8300    }
8301
8302    /**
8303     * Calculate the abis and roots for a bundled app. These can uniquely
8304     * be determined from the contents of the system partition, i.e whether
8305     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8306     * of this information, and instead assume that the system was built
8307     * sensibly.
8308     */
8309    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8310                                           PackageSetting pkgSetting) {
8311        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8312
8313        // If "/system/lib64/apkname" exists, assume that is the per-package
8314        // native library directory to use; otherwise use "/system/lib/apkname".
8315        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8316        setBundledAppAbi(pkg, apkRoot, apkName);
8317        // pkgSetting might be null during rescan following uninstall of updates
8318        // to a bundled app, so accommodate that possibility.  The settings in
8319        // that case will be established later from the parsed package.
8320        //
8321        // If the settings aren't null, sync them up with what we've just derived.
8322        // note that apkRoot isn't stored in the package settings.
8323        if (pkgSetting != null) {
8324            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8325            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8326        }
8327    }
8328
8329    /**
8330     * Deduces the ABI of a bundled app and sets the relevant fields on the
8331     * parsed pkg object.
8332     *
8333     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8334     *        under which system libraries are installed.
8335     * @param apkName the name of the installed package.
8336     */
8337    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8338        final File codeFile = new File(pkg.codePath);
8339
8340        final boolean has64BitLibs;
8341        final boolean has32BitLibs;
8342        if (isApkFile(codeFile)) {
8343            // Monolithic install
8344            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8345            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8346        } else {
8347            // Cluster install
8348            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8349            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8350                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8351                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8352                has64BitLibs = (new File(rootDir, isa)).exists();
8353            } else {
8354                has64BitLibs = false;
8355            }
8356            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8357                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8358                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8359                has32BitLibs = (new File(rootDir, isa)).exists();
8360            } else {
8361                has32BitLibs = false;
8362            }
8363        }
8364
8365        if (has64BitLibs && !has32BitLibs) {
8366            // The package has 64 bit libs, but not 32 bit libs. Its primary
8367            // ABI should be 64 bit. We can safely assume here that the bundled
8368            // native libraries correspond to the most preferred ABI in the list.
8369
8370            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8371            pkg.applicationInfo.secondaryCpuAbi = null;
8372        } else if (has32BitLibs && !has64BitLibs) {
8373            // The package has 32 bit libs but not 64 bit libs. Its primary
8374            // ABI should be 32 bit.
8375
8376            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8377            pkg.applicationInfo.secondaryCpuAbi = null;
8378        } else if (has32BitLibs && has64BitLibs) {
8379            // The application has both 64 and 32 bit bundled libraries. We check
8380            // here that the app declares multiArch support, and warn if it doesn't.
8381            //
8382            // We will be lenient here and record both ABIs. The primary will be the
8383            // ABI that's higher on the list, i.e, a device that's configured to prefer
8384            // 64 bit apps will see a 64 bit primary ABI,
8385
8386            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8387                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8388            }
8389
8390            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8391                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8392                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8393            } else {
8394                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8395                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8396            }
8397        } else {
8398            pkg.applicationInfo.primaryCpuAbi = null;
8399            pkg.applicationInfo.secondaryCpuAbi = null;
8400        }
8401    }
8402
8403    private void killApplication(String pkgName, int appId, String reason) {
8404        // Request the ActivityManager to kill the process(only for existing packages)
8405        // so that we do not end up in a confused state while the user is still using the older
8406        // version of the application while the new one gets installed.
8407        IActivityManager am = ActivityManagerNative.getDefault();
8408        if (am != null) {
8409            try {
8410                am.killApplicationWithAppId(pkgName, appId, reason);
8411            } catch (RemoteException e) {
8412            }
8413        }
8414    }
8415
8416    void removePackageLI(PackageSetting ps, boolean chatty) {
8417        if (DEBUG_INSTALL) {
8418            if (chatty)
8419                Log.d(TAG, "Removing package " + ps.name);
8420        }
8421
8422        // writer
8423        synchronized (mPackages) {
8424            mPackages.remove(ps.name);
8425            final PackageParser.Package pkg = ps.pkg;
8426            if (pkg != null) {
8427                cleanPackageDataStructuresLILPw(pkg, chatty);
8428            }
8429        }
8430    }
8431
8432    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8433        if (DEBUG_INSTALL) {
8434            if (chatty)
8435                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8436        }
8437
8438        // writer
8439        synchronized (mPackages) {
8440            mPackages.remove(pkg.applicationInfo.packageName);
8441            cleanPackageDataStructuresLILPw(pkg, chatty);
8442        }
8443    }
8444
8445    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8446        int N = pkg.providers.size();
8447        StringBuilder r = null;
8448        int i;
8449        for (i=0; i<N; i++) {
8450            PackageParser.Provider p = pkg.providers.get(i);
8451            mProviders.removeProvider(p);
8452            if (p.info.authority == null) {
8453
8454                /* There was another ContentProvider with this authority when
8455                 * this app was installed so this authority is null,
8456                 * Ignore it as we don't have to unregister the provider.
8457                 */
8458                continue;
8459            }
8460            String names[] = p.info.authority.split(";");
8461            for (int j = 0; j < names.length; j++) {
8462                if (mProvidersByAuthority.get(names[j]) == p) {
8463                    mProvidersByAuthority.remove(names[j]);
8464                    if (DEBUG_REMOVE) {
8465                        if (chatty)
8466                            Log.d(TAG, "Unregistered content provider: " + names[j]
8467                                    + ", className = " + p.info.name + ", isSyncable = "
8468                                    + p.info.isSyncable);
8469                    }
8470                }
8471            }
8472            if (DEBUG_REMOVE && chatty) {
8473                if (r == null) {
8474                    r = new StringBuilder(256);
8475                } else {
8476                    r.append(' ');
8477                }
8478                r.append(p.info.name);
8479            }
8480        }
8481        if (r != null) {
8482            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8483        }
8484
8485        N = pkg.services.size();
8486        r = null;
8487        for (i=0; i<N; i++) {
8488            PackageParser.Service s = pkg.services.get(i);
8489            mServices.removeService(s);
8490            if (chatty) {
8491                if (r == null) {
8492                    r = new StringBuilder(256);
8493                } else {
8494                    r.append(' ');
8495                }
8496                r.append(s.info.name);
8497            }
8498        }
8499        if (r != null) {
8500            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8501        }
8502
8503        N = pkg.receivers.size();
8504        r = null;
8505        for (i=0; i<N; i++) {
8506            PackageParser.Activity a = pkg.receivers.get(i);
8507            mReceivers.removeActivity(a, "receiver");
8508            if (DEBUG_REMOVE && chatty) {
8509                if (r == null) {
8510                    r = new StringBuilder(256);
8511                } else {
8512                    r.append(' ');
8513                }
8514                r.append(a.info.name);
8515            }
8516        }
8517        if (r != null) {
8518            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8519        }
8520
8521        N = pkg.activities.size();
8522        r = null;
8523        for (i=0; i<N; i++) {
8524            PackageParser.Activity a = pkg.activities.get(i);
8525            mActivities.removeActivity(a, "activity");
8526            if (DEBUG_REMOVE && chatty) {
8527                if (r == null) {
8528                    r = new StringBuilder(256);
8529                } else {
8530                    r.append(' ');
8531                }
8532                r.append(a.info.name);
8533            }
8534        }
8535        if (r != null) {
8536            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8537        }
8538
8539        N = pkg.permissions.size();
8540        r = null;
8541        for (i=0; i<N; i++) {
8542            PackageParser.Permission p = pkg.permissions.get(i);
8543            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8544            if (bp == null) {
8545                bp = mSettings.mPermissionTrees.get(p.info.name);
8546            }
8547            if (bp != null && bp.perm == p) {
8548                bp.perm = null;
8549                if (DEBUG_REMOVE && chatty) {
8550                    if (r == null) {
8551                        r = new StringBuilder(256);
8552                    } else {
8553                        r.append(' ');
8554                    }
8555                    r.append(p.info.name);
8556                }
8557            }
8558            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8559                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8560                if (appOpPkgs != null) {
8561                    appOpPkgs.remove(pkg.packageName);
8562                }
8563            }
8564        }
8565        if (r != null) {
8566            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8567        }
8568
8569        N = pkg.requestedPermissions.size();
8570        r = null;
8571        for (i=0; i<N; i++) {
8572            String perm = pkg.requestedPermissions.get(i);
8573            BasePermission bp = mSettings.mPermissions.get(perm);
8574            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8575                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8576                if (appOpPkgs != null) {
8577                    appOpPkgs.remove(pkg.packageName);
8578                    if (appOpPkgs.isEmpty()) {
8579                        mAppOpPermissionPackages.remove(perm);
8580                    }
8581                }
8582            }
8583        }
8584        if (r != null) {
8585            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8586        }
8587
8588        N = pkg.instrumentation.size();
8589        r = null;
8590        for (i=0; i<N; i++) {
8591            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8592            mInstrumentation.remove(a.getComponentName());
8593            if (DEBUG_REMOVE && chatty) {
8594                if (r == null) {
8595                    r = new StringBuilder(256);
8596                } else {
8597                    r.append(' ');
8598                }
8599                r.append(a.info.name);
8600            }
8601        }
8602        if (r != null) {
8603            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8604        }
8605
8606        r = null;
8607        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8608            // Only system apps can hold shared libraries.
8609            if (pkg.libraryNames != null) {
8610                for (i=0; i<pkg.libraryNames.size(); i++) {
8611                    String name = pkg.libraryNames.get(i);
8612                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8613                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8614                        mSharedLibraries.remove(name);
8615                        if (DEBUG_REMOVE && chatty) {
8616                            if (r == null) {
8617                                r = new StringBuilder(256);
8618                            } else {
8619                                r.append(' ');
8620                            }
8621                            r.append(name);
8622                        }
8623                    }
8624                }
8625            }
8626        }
8627        if (r != null) {
8628            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8629        }
8630    }
8631
8632    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8633        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8634            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8635                return true;
8636            }
8637        }
8638        return false;
8639    }
8640
8641    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8642    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8643    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8644
8645    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8646            int flags) {
8647        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8648        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8649    }
8650
8651    private void updatePermissionsLPw(String changingPkg,
8652            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8653        // Make sure there are no dangling permission trees.
8654        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8655        while (it.hasNext()) {
8656            final BasePermission bp = it.next();
8657            if (bp.packageSetting == null) {
8658                // We may not yet have parsed the package, so just see if
8659                // we still know about its settings.
8660                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8661            }
8662            if (bp.packageSetting == null) {
8663                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8664                        + " from package " + bp.sourcePackage);
8665                it.remove();
8666            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8667                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8668                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8669                            + " from package " + bp.sourcePackage);
8670                    flags |= UPDATE_PERMISSIONS_ALL;
8671                    it.remove();
8672                }
8673            }
8674        }
8675
8676        // Make sure all dynamic permissions have been assigned to a package,
8677        // and make sure there are no dangling permissions.
8678        it = mSettings.mPermissions.values().iterator();
8679        while (it.hasNext()) {
8680            final BasePermission bp = it.next();
8681            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8682                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8683                        + bp.name + " pkg=" + bp.sourcePackage
8684                        + " info=" + bp.pendingInfo);
8685                if (bp.packageSetting == null && bp.pendingInfo != null) {
8686                    final BasePermission tree = findPermissionTreeLP(bp.name);
8687                    if (tree != null && tree.perm != null) {
8688                        bp.packageSetting = tree.packageSetting;
8689                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8690                                new PermissionInfo(bp.pendingInfo));
8691                        bp.perm.info.packageName = tree.perm.info.packageName;
8692                        bp.perm.info.name = bp.name;
8693                        bp.uid = tree.uid;
8694                    }
8695                }
8696            }
8697            if (bp.packageSetting == null) {
8698                // We may not yet have parsed the package, so just see if
8699                // we still know about its settings.
8700                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8701            }
8702            if (bp.packageSetting == null) {
8703                Slog.w(TAG, "Removing dangling permission: " + bp.name
8704                        + " from package " + bp.sourcePackage);
8705                it.remove();
8706            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8707                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8708                    Slog.i(TAG, "Removing old permission: " + bp.name
8709                            + " from package " + bp.sourcePackage);
8710                    flags |= UPDATE_PERMISSIONS_ALL;
8711                    it.remove();
8712                }
8713            }
8714        }
8715
8716        // Now update the permissions for all packages, in particular
8717        // replace the granted permissions of the system packages.
8718        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8719            for (PackageParser.Package pkg : mPackages.values()) {
8720                if (pkg != pkgInfo) {
8721                    // Only replace for packages on requested volume
8722                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8723                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8724                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8725                    grantPermissionsLPw(pkg, replace, changingPkg);
8726                }
8727            }
8728        }
8729
8730        if (pkgInfo != null) {
8731            // Only replace for packages on requested volume
8732            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8733            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8734                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8735            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8736        }
8737    }
8738
8739    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8740            String packageOfInterest) {
8741        // IMPORTANT: There are two types of permissions: install and runtime.
8742        // Install time permissions are granted when the app is installed to
8743        // all device users and users added in the future. Runtime permissions
8744        // are granted at runtime explicitly to specific users. Normal and signature
8745        // protected permissions are install time permissions. Dangerous permissions
8746        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8747        // otherwise they are runtime permissions. This function does not manage
8748        // runtime permissions except for the case an app targeting Lollipop MR1
8749        // being upgraded to target a newer SDK, in which case dangerous permissions
8750        // are transformed from install time to runtime ones.
8751
8752        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8753        if (ps == null) {
8754            return;
8755        }
8756
8757        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8758
8759        PermissionsState permissionsState = ps.getPermissionsState();
8760        PermissionsState origPermissions = permissionsState;
8761
8762        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8763
8764        boolean runtimePermissionsRevoked = false;
8765        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8766
8767        boolean changedInstallPermission = false;
8768
8769        if (replace) {
8770            ps.installPermissionsFixed = false;
8771            if (!ps.isSharedUser()) {
8772                origPermissions = new PermissionsState(permissionsState);
8773                permissionsState.reset();
8774            } else {
8775                // We need to know only about runtime permission changes since the
8776                // calling code always writes the install permissions state but
8777                // the runtime ones are written only if changed. The only cases of
8778                // changed runtime permissions here are promotion of an install to
8779                // runtime and revocation of a runtime from a shared user.
8780                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8781                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8782                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8783                    runtimePermissionsRevoked = true;
8784                }
8785            }
8786        }
8787
8788        permissionsState.setGlobalGids(mGlobalGids);
8789
8790        final int N = pkg.requestedPermissions.size();
8791        for (int i=0; i<N; i++) {
8792            final String name = pkg.requestedPermissions.get(i);
8793            final BasePermission bp = mSettings.mPermissions.get(name);
8794
8795            if (DEBUG_INSTALL) {
8796                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8797            }
8798
8799            if (bp == null || bp.packageSetting == null) {
8800                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8801                    Slog.w(TAG, "Unknown permission " + name
8802                            + " in package " + pkg.packageName);
8803                }
8804                continue;
8805            }
8806
8807            final String perm = bp.name;
8808            boolean allowedSig = false;
8809            int grant = GRANT_DENIED;
8810
8811            // Keep track of app op permissions.
8812            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8813                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8814                if (pkgs == null) {
8815                    pkgs = new ArraySet<>();
8816                    mAppOpPermissionPackages.put(bp.name, pkgs);
8817                }
8818                pkgs.add(pkg.packageName);
8819            }
8820
8821            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8822            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8823                    >= Build.VERSION_CODES.M;
8824            switch (level) {
8825                case PermissionInfo.PROTECTION_NORMAL: {
8826                    // For all apps normal permissions are install time ones.
8827                    grant = GRANT_INSTALL;
8828                } break;
8829
8830                case PermissionInfo.PROTECTION_DANGEROUS: {
8831                    // If a permission review is required for legacy apps we represent
8832                    // their permissions as always granted runtime ones since we need
8833                    // to keep the review required permission flag per user while an
8834                    // install permission's state is shared across all users.
8835                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8836                        // For legacy apps dangerous permissions are install time ones.
8837                        grant = GRANT_INSTALL;
8838                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8839                        // For legacy apps that became modern, install becomes runtime.
8840                        grant = GRANT_UPGRADE;
8841                    } else if (mPromoteSystemApps
8842                            && isSystemApp(ps)
8843                            && mExistingSystemPackages.contains(ps.name)) {
8844                        // For legacy system apps, install becomes runtime.
8845                        // We cannot check hasInstallPermission() for system apps since those
8846                        // permissions were granted implicitly and not persisted pre-M.
8847                        grant = GRANT_UPGRADE;
8848                    } else {
8849                        // For modern apps keep runtime permissions unchanged.
8850                        grant = GRANT_RUNTIME;
8851                    }
8852                } break;
8853
8854                case PermissionInfo.PROTECTION_SIGNATURE: {
8855                    // For all apps signature permissions are install time ones.
8856                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8857                    if (allowedSig) {
8858                        grant = GRANT_INSTALL;
8859                    }
8860                } break;
8861            }
8862
8863            if (DEBUG_INSTALL) {
8864                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8865            }
8866
8867            if (grant != GRANT_DENIED) {
8868                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8869                    // If this is an existing, non-system package, then
8870                    // we can't add any new permissions to it.
8871                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8872                        // Except...  if this is a permission that was added
8873                        // to the platform (note: need to only do this when
8874                        // updating the platform).
8875                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8876                            grant = GRANT_DENIED;
8877                        }
8878                    }
8879                }
8880
8881                switch (grant) {
8882                    case GRANT_INSTALL: {
8883                        // Revoke this as runtime permission to handle the case of
8884                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8885                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8886                            if (origPermissions.getRuntimePermissionState(
8887                                    bp.name, userId) != null) {
8888                                // Revoke the runtime permission and clear the flags.
8889                                origPermissions.revokeRuntimePermission(bp, userId);
8890                                origPermissions.updatePermissionFlags(bp, userId,
8891                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8892                                // If we revoked a permission permission, we have to write.
8893                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8894                                        changedRuntimePermissionUserIds, userId);
8895                            }
8896                        }
8897                        // Grant an install permission.
8898                        if (permissionsState.grantInstallPermission(bp) !=
8899                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8900                            changedInstallPermission = true;
8901                        }
8902                    } break;
8903
8904                    case GRANT_RUNTIME: {
8905                        // Grant previously granted runtime permissions.
8906                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8907                            PermissionState permissionState = origPermissions
8908                                    .getRuntimePermissionState(bp.name, userId);
8909                            int flags = permissionState != null
8910                                    ? permissionState.getFlags() : 0;
8911                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8912                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8913                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8914                                    // If we cannot put the permission as it was, we have to write.
8915                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8916                                            changedRuntimePermissionUserIds, userId);
8917                                }
8918                                // If the app supports runtime permissions no need for a review.
8919                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8920                                        && appSupportsRuntimePermissions
8921                                        && (flags & PackageManager
8922                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8923                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8924                                    // Since we changed the flags, we have to write.
8925                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8926                                            changedRuntimePermissionUserIds, userId);
8927                                }
8928                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8929                                    && !appSupportsRuntimePermissions) {
8930                                // For legacy apps that need a permission review, every new
8931                                // runtime permission is granted but it is pending a review.
8932                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8933                                    permissionsState.grantRuntimePermission(bp, userId);
8934                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8935                                    // We changed the permission and flags, hence have to write.
8936                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8937                                            changedRuntimePermissionUserIds, userId);
8938                                }
8939                            }
8940                            // Propagate the permission flags.
8941                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8942                        }
8943                    } break;
8944
8945                    case GRANT_UPGRADE: {
8946                        // Grant runtime permissions for a previously held install permission.
8947                        PermissionState permissionState = origPermissions
8948                                .getInstallPermissionState(bp.name);
8949                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8950
8951                        if (origPermissions.revokeInstallPermission(bp)
8952                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8953                            // We will be transferring the permission flags, so clear them.
8954                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8955                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8956                            changedInstallPermission = true;
8957                        }
8958
8959                        // If the permission is not to be promoted to runtime we ignore it and
8960                        // also its other flags as they are not applicable to install permissions.
8961                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8962                            for (int userId : currentUserIds) {
8963                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8964                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8965                                    // Transfer the permission flags.
8966                                    permissionsState.updatePermissionFlags(bp, userId,
8967                                            flags, flags);
8968                                    // If we granted the permission, we have to write.
8969                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8970                                            changedRuntimePermissionUserIds, userId);
8971                                }
8972                            }
8973                        }
8974                    } break;
8975
8976                    default: {
8977                        if (packageOfInterest == null
8978                                || packageOfInterest.equals(pkg.packageName)) {
8979                            Slog.w(TAG, "Not granting permission " + perm
8980                                    + " to package " + pkg.packageName
8981                                    + " because it was previously installed without");
8982                        }
8983                    } break;
8984                }
8985            } else {
8986                if (permissionsState.revokeInstallPermission(bp) !=
8987                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8988                    // Also drop the permission flags.
8989                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8990                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8991                    changedInstallPermission = true;
8992                    Slog.i(TAG, "Un-granting permission " + perm
8993                            + " from package " + pkg.packageName
8994                            + " (protectionLevel=" + bp.protectionLevel
8995                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8996                            + ")");
8997                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8998                    // Don't print warning for app op permissions, since it is fine for them
8999                    // not to be granted, there is a UI for the user to decide.
9000                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9001                        Slog.w(TAG, "Not granting permission " + perm
9002                                + " to package " + pkg.packageName
9003                                + " (protectionLevel=" + bp.protectionLevel
9004                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9005                                + ")");
9006                    }
9007                }
9008            }
9009        }
9010
9011        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9012                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9013            // This is the first that we have heard about this package, so the
9014            // permissions we have now selected are fixed until explicitly
9015            // changed.
9016            ps.installPermissionsFixed = true;
9017        }
9018
9019        // Persist the runtime permissions state for users with changes. If permissions
9020        // were revoked because no app in the shared user declares them we have to
9021        // write synchronously to avoid losing runtime permissions state.
9022        for (int userId : changedRuntimePermissionUserIds) {
9023            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9024        }
9025
9026        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9027    }
9028
9029    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9030        boolean allowed = false;
9031        final int NP = PackageParser.NEW_PERMISSIONS.length;
9032        for (int ip=0; ip<NP; ip++) {
9033            final PackageParser.NewPermissionInfo npi
9034                    = PackageParser.NEW_PERMISSIONS[ip];
9035            if (npi.name.equals(perm)
9036                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9037                allowed = true;
9038                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9039                        + pkg.packageName);
9040                break;
9041            }
9042        }
9043        return allowed;
9044    }
9045
9046    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9047            BasePermission bp, PermissionsState origPermissions) {
9048        boolean allowed;
9049        allowed = (compareSignatures(
9050                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9051                        == PackageManager.SIGNATURE_MATCH)
9052                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9053                        == PackageManager.SIGNATURE_MATCH);
9054        if (!allowed && (bp.protectionLevel
9055                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9056            if (isSystemApp(pkg)) {
9057                // For updated system applications, a system permission
9058                // is granted only if it had been defined by the original application.
9059                if (pkg.isUpdatedSystemApp()) {
9060                    final PackageSetting sysPs = mSettings
9061                            .getDisabledSystemPkgLPr(pkg.packageName);
9062                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9063                        // If the original was granted this permission, we take
9064                        // that grant decision as read and propagate it to the
9065                        // update.
9066                        if (sysPs.isPrivileged()) {
9067                            allowed = true;
9068                        }
9069                    } else {
9070                        // The system apk may have been updated with an older
9071                        // version of the one on the data partition, but which
9072                        // granted a new system permission that it didn't have
9073                        // before.  In this case we do want to allow the app to
9074                        // now get the new permission if the ancestral apk is
9075                        // privileged to get it.
9076                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9077                            for (int j=0;
9078                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9079                                if (perm.equals(
9080                                        sysPs.pkg.requestedPermissions.get(j))) {
9081                                    allowed = true;
9082                                    break;
9083                                }
9084                            }
9085                        }
9086                    }
9087                } else {
9088                    allowed = isPrivilegedApp(pkg);
9089                }
9090            }
9091        }
9092        if (!allowed) {
9093            if (!allowed && (bp.protectionLevel
9094                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9095                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9096                // If this was a previously normal/dangerous permission that got moved
9097                // to a system permission as part of the runtime permission redesign, then
9098                // we still want to blindly grant it to old apps.
9099                allowed = true;
9100            }
9101            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9102                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9103                // If this permission is to be granted to the system installer and
9104                // this app is an installer, then it gets the permission.
9105                allowed = true;
9106            }
9107            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9108                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9109                // If this permission is to be granted to the system verifier and
9110                // this app is a verifier, then it gets the permission.
9111                allowed = true;
9112            }
9113            if (!allowed && (bp.protectionLevel
9114                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9115                    && isSystemApp(pkg)) {
9116                // Any pre-installed system app is allowed to get this permission.
9117                allowed = true;
9118            }
9119            if (!allowed && (bp.protectionLevel
9120                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9121                // For development permissions, a development permission
9122                // is granted only if it was already granted.
9123                allowed = origPermissions.hasInstallPermission(perm);
9124            }
9125        }
9126        return allowed;
9127    }
9128
9129    final class ActivityIntentResolver
9130            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9131        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9132                boolean defaultOnly, int userId) {
9133            if (!sUserManager.exists(userId)) return null;
9134            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9135            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9136        }
9137
9138        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9139                int userId) {
9140            if (!sUserManager.exists(userId)) return null;
9141            mFlags = flags;
9142            return super.queryIntent(intent, resolvedType,
9143                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9144        }
9145
9146        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9147                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9148            if (!sUserManager.exists(userId)) return null;
9149            if (packageActivities == null) {
9150                return null;
9151            }
9152            mFlags = flags;
9153            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9154            final int N = packageActivities.size();
9155            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9156                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9157
9158            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9159            for (int i = 0; i < N; ++i) {
9160                intentFilters = packageActivities.get(i).intents;
9161                if (intentFilters != null && intentFilters.size() > 0) {
9162                    PackageParser.ActivityIntentInfo[] array =
9163                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9164                    intentFilters.toArray(array);
9165                    listCut.add(array);
9166                }
9167            }
9168            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9169        }
9170
9171        public final void addActivity(PackageParser.Activity a, String type) {
9172            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9173            mActivities.put(a.getComponentName(), a);
9174            if (DEBUG_SHOW_INFO)
9175                Log.v(
9176                TAG, "  " + type + " " +
9177                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9178            if (DEBUG_SHOW_INFO)
9179                Log.v(TAG, "    Class=" + a.info.name);
9180            final int NI = a.intents.size();
9181            for (int j=0; j<NI; j++) {
9182                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9183                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9184                    intent.setPriority(0);
9185                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9186                            + a.className + " with priority > 0, forcing to 0");
9187                }
9188                if (DEBUG_SHOW_INFO) {
9189                    Log.v(TAG, "    IntentFilter:");
9190                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9191                }
9192                if (!intent.debugCheck()) {
9193                    Log.w(TAG, "==> For Activity " + a.info.name);
9194                }
9195                addFilter(intent);
9196            }
9197        }
9198
9199        public final void removeActivity(PackageParser.Activity a, String type) {
9200            mActivities.remove(a.getComponentName());
9201            if (DEBUG_SHOW_INFO) {
9202                Log.v(TAG, "  " + type + " "
9203                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9204                                : a.info.name) + ":");
9205                Log.v(TAG, "    Class=" + a.info.name);
9206            }
9207            final int NI = a.intents.size();
9208            for (int j=0; j<NI; j++) {
9209                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9210                if (DEBUG_SHOW_INFO) {
9211                    Log.v(TAG, "    IntentFilter:");
9212                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9213                }
9214                removeFilter(intent);
9215            }
9216        }
9217
9218        @Override
9219        protected boolean allowFilterResult(
9220                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9221            ActivityInfo filterAi = filter.activity.info;
9222            for (int i=dest.size()-1; i>=0; i--) {
9223                ActivityInfo destAi = dest.get(i).activityInfo;
9224                if (destAi.name == filterAi.name
9225                        && destAi.packageName == filterAi.packageName) {
9226                    return false;
9227                }
9228            }
9229            return true;
9230        }
9231
9232        @Override
9233        protected ActivityIntentInfo[] newArray(int size) {
9234            return new ActivityIntentInfo[size];
9235        }
9236
9237        @Override
9238        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9239            if (!sUserManager.exists(userId)) return true;
9240            PackageParser.Package p = filter.activity.owner;
9241            if (p != null) {
9242                PackageSetting ps = (PackageSetting)p.mExtras;
9243                if (ps != null) {
9244                    // System apps are never considered stopped for purposes of
9245                    // filtering, because there may be no way for the user to
9246                    // actually re-launch them.
9247                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9248                            && ps.getStopped(userId);
9249                }
9250            }
9251            return false;
9252        }
9253
9254        @Override
9255        protected boolean isPackageForFilter(String packageName,
9256                PackageParser.ActivityIntentInfo info) {
9257            return packageName.equals(info.activity.owner.packageName);
9258        }
9259
9260        @Override
9261        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9262                int match, int userId) {
9263            if (!sUserManager.exists(userId)) return null;
9264            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9265                return null;
9266            }
9267            final PackageParser.Activity activity = info.activity;
9268            if (mSafeMode && (activity.info.applicationInfo.flags
9269                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9270                return null;
9271            }
9272            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9273            if (ps == null) {
9274                return null;
9275            }
9276            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9277                    ps.readUserState(userId), userId);
9278            if (ai == null) {
9279                return null;
9280            }
9281            final ResolveInfo res = new ResolveInfo();
9282            res.activityInfo = ai;
9283            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9284                res.filter = info;
9285            }
9286            if (info != null) {
9287                res.handleAllWebDataURI = info.handleAllWebDataURI();
9288            }
9289            res.priority = info.getPriority();
9290            res.preferredOrder = activity.owner.mPreferredOrder;
9291            //System.out.println("Result: " + res.activityInfo.className +
9292            //                   " = " + res.priority);
9293            res.match = match;
9294            res.isDefault = info.hasDefault;
9295            res.labelRes = info.labelRes;
9296            res.nonLocalizedLabel = info.nonLocalizedLabel;
9297            if (userNeedsBadging(userId)) {
9298                res.noResourceId = true;
9299            } else {
9300                res.icon = info.icon;
9301            }
9302            res.iconResourceId = info.icon;
9303            res.system = res.activityInfo.applicationInfo.isSystemApp();
9304            return res;
9305        }
9306
9307        @Override
9308        protected void sortResults(List<ResolveInfo> results) {
9309            Collections.sort(results, mResolvePrioritySorter);
9310        }
9311
9312        @Override
9313        protected void dumpFilter(PrintWriter out, String prefix,
9314                PackageParser.ActivityIntentInfo filter) {
9315            out.print(prefix); out.print(
9316                    Integer.toHexString(System.identityHashCode(filter.activity)));
9317                    out.print(' ');
9318                    filter.activity.printComponentShortName(out);
9319                    out.print(" filter ");
9320                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9321        }
9322
9323        @Override
9324        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9325            return filter.activity;
9326        }
9327
9328        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9329            PackageParser.Activity activity = (PackageParser.Activity)label;
9330            out.print(prefix); out.print(
9331                    Integer.toHexString(System.identityHashCode(activity)));
9332                    out.print(' ');
9333                    activity.printComponentShortName(out);
9334            if (count > 1) {
9335                out.print(" ("); out.print(count); out.print(" filters)");
9336            }
9337            out.println();
9338        }
9339
9340//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9341//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9342//            final List<ResolveInfo> retList = Lists.newArrayList();
9343//            while (i.hasNext()) {
9344//                final ResolveInfo resolveInfo = i.next();
9345//                if (isEnabledLP(resolveInfo.activityInfo)) {
9346//                    retList.add(resolveInfo);
9347//                }
9348//            }
9349//            return retList;
9350//        }
9351
9352        // Keys are String (activity class name), values are Activity.
9353        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9354                = new ArrayMap<ComponentName, PackageParser.Activity>();
9355        private int mFlags;
9356    }
9357
9358    private final class ServiceIntentResolver
9359            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9360        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9361                boolean defaultOnly, int userId) {
9362            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9363            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9364        }
9365
9366        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9367                int userId) {
9368            if (!sUserManager.exists(userId)) return null;
9369            mFlags = flags;
9370            return super.queryIntent(intent, resolvedType,
9371                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9372        }
9373
9374        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9375                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9376            if (!sUserManager.exists(userId)) return null;
9377            if (packageServices == null) {
9378                return null;
9379            }
9380            mFlags = flags;
9381            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9382            final int N = packageServices.size();
9383            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9384                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9385
9386            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9387            for (int i = 0; i < N; ++i) {
9388                intentFilters = packageServices.get(i).intents;
9389                if (intentFilters != null && intentFilters.size() > 0) {
9390                    PackageParser.ServiceIntentInfo[] array =
9391                            new PackageParser.ServiceIntentInfo[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 addService(PackageParser.Service s) {
9400            mServices.put(s.getComponentName(), s);
9401            if (DEBUG_SHOW_INFO) {
9402                Log.v(TAG, "  "
9403                        + (s.info.nonLocalizedLabel != null
9404                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9405                Log.v(TAG, "    Class=" + s.info.name);
9406            }
9407            final int NI = s.intents.size();
9408            int j;
9409            for (j=0; j<NI; j++) {
9410                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9411                if (DEBUG_SHOW_INFO) {
9412                    Log.v(TAG, "    IntentFilter:");
9413                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9414                }
9415                if (!intent.debugCheck()) {
9416                    Log.w(TAG, "==> For Service " + s.info.name);
9417                }
9418                addFilter(intent);
9419            }
9420        }
9421
9422        public final void removeService(PackageParser.Service s) {
9423            mServices.remove(s.getComponentName());
9424            if (DEBUG_SHOW_INFO) {
9425                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9426                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9427                Log.v(TAG, "    Class=" + s.info.name);
9428            }
9429            final int NI = s.intents.size();
9430            int j;
9431            for (j=0; j<NI; j++) {
9432                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9433                if (DEBUG_SHOW_INFO) {
9434                    Log.v(TAG, "    IntentFilter:");
9435                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9436                }
9437                removeFilter(intent);
9438            }
9439        }
9440
9441        @Override
9442        protected boolean allowFilterResult(
9443                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9444            ServiceInfo filterSi = filter.service.info;
9445            for (int i=dest.size()-1; i>=0; i--) {
9446                ServiceInfo destAi = dest.get(i).serviceInfo;
9447                if (destAi.name == filterSi.name
9448                        && destAi.packageName == filterSi.packageName) {
9449                    return false;
9450                }
9451            }
9452            return true;
9453        }
9454
9455        @Override
9456        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9457            return new PackageParser.ServiceIntentInfo[size];
9458        }
9459
9460        @Override
9461        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9462            if (!sUserManager.exists(userId)) return true;
9463            PackageParser.Package p = filter.service.owner;
9464            if (p != null) {
9465                PackageSetting ps = (PackageSetting)p.mExtras;
9466                if (ps != null) {
9467                    // System apps are never considered stopped for purposes of
9468                    // filtering, because there may be no way for the user to
9469                    // actually re-launch them.
9470                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9471                            && ps.getStopped(userId);
9472                }
9473            }
9474            return false;
9475        }
9476
9477        @Override
9478        protected boolean isPackageForFilter(String packageName,
9479                PackageParser.ServiceIntentInfo info) {
9480            return packageName.equals(info.service.owner.packageName);
9481        }
9482
9483        @Override
9484        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9485                int match, int userId) {
9486            if (!sUserManager.exists(userId)) return null;
9487            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9488            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9489                return null;
9490            }
9491            final PackageParser.Service service = info.service;
9492            if (mSafeMode && (service.info.applicationInfo.flags
9493                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9494                return null;
9495            }
9496            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9497            if (ps == null) {
9498                return null;
9499            }
9500            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9501                    ps.readUserState(userId), userId);
9502            if (si == null) {
9503                return null;
9504            }
9505            final ResolveInfo res = new ResolveInfo();
9506            res.serviceInfo = si;
9507            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9508                res.filter = filter;
9509            }
9510            res.priority = info.getPriority();
9511            res.preferredOrder = service.owner.mPreferredOrder;
9512            res.match = match;
9513            res.isDefault = info.hasDefault;
9514            res.labelRes = info.labelRes;
9515            res.nonLocalizedLabel = info.nonLocalizedLabel;
9516            res.icon = info.icon;
9517            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9518            return res;
9519        }
9520
9521        @Override
9522        protected void sortResults(List<ResolveInfo> results) {
9523            Collections.sort(results, mResolvePrioritySorter);
9524        }
9525
9526        @Override
9527        protected void dumpFilter(PrintWriter out, String prefix,
9528                PackageParser.ServiceIntentInfo filter) {
9529            out.print(prefix); out.print(
9530                    Integer.toHexString(System.identityHashCode(filter.service)));
9531                    out.print(' ');
9532                    filter.service.printComponentShortName(out);
9533                    out.print(" filter ");
9534                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9535        }
9536
9537        @Override
9538        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9539            return filter.service;
9540        }
9541
9542        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9543            PackageParser.Service service = (PackageParser.Service)label;
9544            out.print(prefix); out.print(
9545                    Integer.toHexString(System.identityHashCode(service)));
9546                    out.print(' ');
9547                    service.printComponentShortName(out);
9548            if (count > 1) {
9549                out.print(" ("); out.print(count); out.print(" filters)");
9550            }
9551            out.println();
9552        }
9553
9554//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9555//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9556//            final List<ResolveInfo> retList = Lists.newArrayList();
9557//            while (i.hasNext()) {
9558//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9559//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9560//                    retList.add(resolveInfo);
9561//                }
9562//            }
9563//            return retList;
9564//        }
9565
9566        // Keys are String (activity class name), values are Activity.
9567        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9568                = new ArrayMap<ComponentName, PackageParser.Service>();
9569        private int mFlags;
9570    };
9571
9572    private final class ProviderIntentResolver
9573            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9574        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9575                boolean defaultOnly, int userId) {
9576            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9577            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9578        }
9579
9580        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9581                int userId) {
9582            if (!sUserManager.exists(userId))
9583                return null;
9584            mFlags = flags;
9585            return super.queryIntent(intent, resolvedType,
9586                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9587        }
9588
9589        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9590                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9591            if (!sUserManager.exists(userId))
9592                return null;
9593            if (packageProviders == null) {
9594                return null;
9595            }
9596            mFlags = flags;
9597            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9598            final int N = packageProviders.size();
9599            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9600                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9601
9602            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9603            for (int i = 0; i < N; ++i) {
9604                intentFilters = packageProviders.get(i).intents;
9605                if (intentFilters != null && intentFilters.size() > 0) {
9606                    PackageParser.ProviderIntentInfo[] array =
9607                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9608                    intentFilters.toArray(array);
9609                    listCut.add(array);
9610                }
9611            }
9612            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9613        }
9614
9615        public final void addProvider(PackageParser.Provider p) {
9616            if (mProviders.containsKey(p.getComponentName())) {
9617                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9618                return;
9619            }
9620
9621            mProviders.put(p.getComponentName(), p);
9622            if (DEBUG_SHOW_INFO) {
9623                Log.v(TAG, "  "
9624                        + (p.info.nonLocalizedLabel != null
9625                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9626                Log.v(TAG, "    Class=" + p.info.name);
9627            }
9628            final int NI = p.intents.size();
9629            int j;
9630            for (j = 0; j < NI; j++) {
9631                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9632                if (DEBUG_SHOW_INFO) {
9633                    Log.v(TAG, "    IntentFilter:");
9634                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9635                }
9636                if (!intent.debugCheck()) {
9637                    Log.w(TAG, "==> For Provider " + p.info.name);
9638                }
9639                addFilter(intent);
9640            }
9641        }
9642
9643        public final void removeProvider(PackageParser.Provider p) {
9644            mProviders.remove(p.getComponentName());
9645            if (DEBUG_SHOW_INFO) {
9646                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9647                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9648                Log.v(TAG, "    Class=" + p.info.name);
9649            }
9650            final int NI = p.intents.size();
9651            int j;
9652            for (j = 0; j < NI; j++) {
9653                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9654                if (DEBUG_SHOW_INFO) {
9655                    Log.v(TAG, "    IntentFilter:");
9656                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9657                }
9658                removeFilter(intent);
9659            }
9660        }
9661
9662        @Override
9663        protected boolean allowFilterResult(
9664                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9665            ProviderInfo filterPi = filter.provider.info;
9666            for (int i = dest.size() - 1; i >= 0; i--) {
9667                ProviderInfo destPi = dest.get(i).providerInfo;
9668                if (destPi.name == filterPi.name
9669                        && destPi.packageName == filterPi.packageName) {
9670                    return false;
9671                }
9672            }
9673            return true;
9674        }
9675
9676        @Override
9677        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9678            return new PackageParser.ProviderIntentInfo[size];
9679        }
9680
9681        @Override
9682        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9683            if (!sUserManager.exists(userId))
9684                return true;
9685            PackageParser.Package p = filter.provider.owner;
9686            if (p != null) {
9687                PackageSetting ps = (PackageSetting) p.mExtras;
9688                if (ps != null) {
9689                    // System apps are never considered stopped for purposes of
9690                    // filtering, because there may be no way for the user to
9691                    // actually re-launch them.
9692                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9693                            && ps.getStopped(userId);
9694                }
9695            }
9696            return false;
9697        }
9698
9699        @Override
9700        protected boolean isPackageForFilter(String packageName,
9701                PackageParser.ProviderIntentInfo info) {
9702            return packageName.equals(info.provider.owner.packageName);
9703        }
9704
9705        @Override
9706        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9707                int match, int userId) {
9708            if (!sUserManager.exists(userId))
9709                return null;
9710            final PackageParser.ProviderIntentInfo info = filter;
9711            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9712                return null;
9713            }
9714            final PackageParser.Provider provider = info.provider;
9715            if (mSafeMode && (provider.info.applicationInfo.flags
9716                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9717                return null;
9718            }
9719            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9720            if (ps == null) {
9721                return null;
9722            }
9723            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9724                    ps.readUserState(userId), userId);
9725            if (pi == null) {
9726                return null;
9727            }
9728            final ResolveInfo res = new ResolveInfo();
9729            res.providerInfo = pi;
9730            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9731                res.filter = filter;
9732            }
9733            res.priority = info.getPriority();
9734            res.preferredOrder = provider.owner.mPreferredOrder;
9735            res.match = match;
9736            res.isDefault = info.hasDefault;
9737            res.labelRes = info.labelRes;
9738            res.nonLocalizedLabel = info.nonLocalizedLabel;
9739            res.icon = info.icon;
9740            res.system = res.providerInfo.applicationInfo.isSystemApp();
9741            return res;
9742        }
9743
9744        @Override
9745        protected void sortResults(List<ResolveInfo> results) {
9746            Collections.sort(results, mResolvePrioritySorter);
9747        }
9748
9749        @Override
9750        protected void dumpFilter(PrintWriter out, String prefix,
9751                PackageParser.ProviderIntentInfo filter) {
9752            out.print(prefix);
9753            out.print(
9754                    Integer.toHexString(System.identityHashCode(filter.provider)));
9755            out.print(' ');
9756            filter.provider.printComponentShortName(out);
9757            out.print(" filter ");
9758            out.println(Integer.toHexString(System.identityHashCode(filter)));
9759        }
9760
9761        @Override
9762        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9763            return filter.provider;
9764        }
9765
9766        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9767            PackageParser.Provider provider = (PackageParser.Provider)label;
9768            out.print(prefix); out.print(
9769                    Integer.toHexString(System.identityHashCode(provider)));
9770                    out.print(' ');
9771                    provider.printComponentShortName(out);
9772            if (count > 1) {
9773                out.print(" ("); out.print(count); out.print(" filters)");
9774            }
9775            out.println();
9776        }
9777
9778        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9779                = new ArrayMap<ComponentName, PackageParser.Provider>();
9780        private int mFlags;
9781    }
9782
9783    private static final class EphemeralIntentResolver
9784            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9785        @Override
9786        protected EphemeralResolveIntentInfo[] newArray(int size) {
9787            return new EphemeralResolveIntentInfo[size];
9788        }
9789
9790        @Override
9791        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9792            return true;
9793        }
9794
9795        @Override
9796        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9797                int userId) {
9798            if (!sUserManager.exists(userId)) {
9799                return null;
9800            }
9801            return info.getEphemeralResolveInfo();
9802        }
9803    }
9804
9805    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9806            new Comparator<ResolveInfo>() {
9807        public int compare(ResolveInfo r1, ResolveInfo r2) {
9808            int v1 = r1.priority;
9809            int v2 = r2.priority;
9810            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9811            if (v1 != v2) {
9812                return (v1 > v2) ? -1 : 1;
9813            }
9814            v1 = r1.preferredOrder;
9815            v2 = r2.preferredOrder;
9816            if (v1 != v2) {
9817                return (v1 > v2) ? -1 : 1;
9818            }
9819            if (r1.isDefault != r2.isDefault) {
9820                return r1.isDefault ? -1 : 1;
9821            }
9822            v1 = r1.match;
9823            v2 = r2.match;
9824            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9825            if (v1 != v2) {
9826                return (v1 > v2) ? -1 : 1;
9827            }
9828            if (r1.system != r2.system) {
9829                return r1.system ? -1 : 1;
9830            }
9831            if (r1.activityInfo != null) {
9832                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9833            }
9834            if (r1.serviceInfo != null) {
9835                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9836            }
9837            if (r1.providerInfo != null) {
9838                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9839            }
9840            return 0;
9841        }
9842    };
9843
9844    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9845            new Comparator<ProviderInfo>() {
9846        public int compare(ProviderInfo p1, ProviderInfo p2) {
9847            final int v1 = p1.initOrder;
9848            final int v2 = p2.initOrder;
9849            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9850        }
9851    };
9852
9853    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9854            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9855            final int[] userIds) {
9856        mHandler.post(new Runnable() {
9857            @Override
9858            public void run() {
9859                try {
9860                    final IActivityManager am = ActivityManagerNative.getDefault();
9861                    if (am == null) return;
9862                    final int[] resolvedUserIds;
9863                    if (userIds == null) {
9864                        resolvedUserIds = am.getRunningUserIds();
9865                    } else {
9866                        resolvedUserIds = userIds;
9867                    }
9868                    for (int id : resolvedUserIds) {
9869                        final Intent intent = new Intent(action,
9870                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9871                        if (extras != null) {
9872                            intent.putExtras(extras);
9873                        }
9874                        if (targetPkg != null) {
9875                            intent.setPackage(targetPkg);
9876                        }
9877                        // Modify the UID when posting to other users
9878                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9879                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9880                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9881                            intent.putExtra(Intent.EXTRA_UID, uid);
9882                        }
9883                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9884                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9885                        if (DEBUG_BROADCASTS) {
9886                            RuntimeException here = new RuntimeException("here");
9887                            here.fillInStackTrace();
9888                            Slog.d(TAG, "Sending to user " + id + ": "
9889                                    + intent.toShortString(false, true, false, false)
9890                                    + " " + intent.getExtras(), here);
9891                        }
9892                        am.broadcastIntent(null, intent, null, finishedReceiver,
9893                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9894                                null, finishedReceiver != null, false, id);
9895                    }
9896                } catch (RemoteException ex) {
9897                }
9898            }
9899        });
9900    }
9901
9902    /**
9903     * Check if the external storage media is available. This is true if there
9904     * is a mounted external storage medium or if the external storage is
9905     * emulated.
9906     */
9907    private boolean isExternalMediaAvailable() {
9908        return mMediaMounted || Environment.isExternalStorageEmulated();
9909    }
9910
9911    @Override
9912    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9913        // writer
9914        synchronized (mPackages) {
9915            if (!isExternalMediaAvailable()) {
9916                // If the external storage is no longer mounted at this point,
9917                // the caller may not have been able to delete all of this
9918                // packages files and can not delete any more.  Bail.
9919                return null;
9920            }
9921            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9922            if (lastPackage != null) {
9923                pkgs.remove(lastPackage);
9924            }
9925            if (pkgs.size() > 0) {
9926                return pkgs.get(0);
9927            }
9928        }
9929        return null;
9930    }
9931
9932    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9933        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9934                userId, andCode ? 1 : 0, packageName);
9935        if (mSystemReady) {
9936            msg.sendToTarget();
9937        } else {
9938            if (mPostSystemReadyMessages == null) {
9939                mPostSystemReadyMessages = new ArrayList<>();
9940            }
9941            mPostSystemReadyMessages.add(msg);
9942        }
9943    }
9944
9945    void startCleaningPackages() {
9946        // reader
9947        synchronized (mPackages) {
9948            if (!isExternalMediaAvailable()) {
9949                return;
9950            }
9951            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9952                return;
9953            }
9954        }
9955        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9956        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9957        IActivityManager am = ActivityManagerNative.getDefault();
9958        if (am != null) {
9959            try {
9960                am.startService(null, intent, null, mContext.getOpPackageName(),
9961                        UserHandle.USER_SYSTEM);
9962            } catch (RemoteException e) {
9963            }
9964        }
9965    }
9966
9967    @Override
9968    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9969            int installFlags, String installerPackageName, VerificationParams verificationParams,
9970            String packageAbiOverride) {
9971        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9972                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9973    }
9974
9975    @Override
9976    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9977            int installFlags, String installerPackageName, VerificationParams verificationParams,
9978            String packageAbiOverride, int userId) {
9979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9980
9981        final int callingUid = Binder.getCallingUid();
9982        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9983
9984        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9985            try {
9986                if (observer != null) {
9987                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9988                }
9989            } catch (RemoteException re) {
9990            }
9991            return;
9992        }
9993
9994        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9995            installFlags |= PackageManager.INSTALL_FROM_ADB;
9996
9997        } else {
9998            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9999            // about installerPackageName.
10000
10001            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10002            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10003        }
10004
10005        UserHandle user;
10006        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10007            user = UserHandle.ALL;
10008        } else {
10009            user = new UserHandle(userId);
10010        }
10011
10012        // Only system components can circumvent runtime permissions when installing.
10013        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10014                && mContext.checkCallingOrSelfPermission(Manifest.permission
10015                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10016            throw new SecurityException("You need the "
10017                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10018                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10019        }
10020
10021        verificationParams.setInstallerUid(callingUid);
10022
10023        final File originFile = new File(originPath);
10024        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10025
10026        final Message msg = mHandler.obtainMessage(INIT_COPY);
10027        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10028                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10029        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10030        msg.obj = params;
10031
10032        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10033                System.identityHashCode(msg.obj));
10034        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10035                System.identityHashCode(msg.obj));
10036
10037        mHandler.sendMessage(msg);
10038    }
10039
10040    void installStage(String packageName, File stagedDir, String stagedCid,
10041            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10042            String installerPackageName, int installerUid, UserHandle user) {
10043        if (DEBUG_EPHEMERAL) {
10044            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10045                Slog.d(TAG, "Ephemeral install of " + packageName);
10046            }
10047        }
10048        final VerificationParams verifParams = new VerificationParams(
10049                null, sessionParams.originatingUri, sessionParams.referrerUri,
10050                sessionParams.originatingUid);
10051        verifParams.setInstallerUid(installerUid);
10052
10053        final OriginInfo origin;
10054        if (stagedDir != null) {
10055            origin = OriginInfo.fromStagedFile(stagedDir);
10056        } else {
10057            origin = OriginInfo.fromStagedContainer(stagedCid);
10058        }
10059
10060        final Message msg = mHandler.obtainMessage(INIT_COPY);
10061        final InstallParams params = new InstallParams(origin, null, observer,
10062                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10063                verifParams, user, sessionParams.abiOverride,
10064                sessionParams.grantedRuntimePermissions);
10065        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10066        msg.obj = params;
10067
10068        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10069                System.identityHashCode(msg.obj));
10070        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10071                System.identityHashCode(msg.obj));
10072
10073        mHandler.sendMessage(msg);
10074    }
10075
10076    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10077        Bundle extras = new Bundle(1);
10078        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10079
10080        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10081                packageName, extras, 0, null, null, new int[] {userId});
10082        try {
10083            IActivityManager am = ActivityManagerNative.getDefault();
10084            final boolean isSystem =
10085                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10086            if (isSystem && am.isUserRunning(userId, 0)) {
10087                // The just-installed/enabled app is bundled on the system, so presumed
10088                // to be able to run automatically without needing an explicit launch.
10089                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10090                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10091                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10092                        .setPackage(packageName);
10093                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10094                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10095            }
10096        } catch (RemoteException e) {
10097            // shouldn't happen
10098            Slog.w(TAG, "Unable to bootstrap installed package", e);
10099        }
10100    }
10101
10102    @Override
10103    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10104            int userId) {
10105        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10106        PackageSetting pkgSetting;
10107        final int uid = Binder.getCallingUid();
10108        enforceCrossUserPermission(uid, userId, true, true,
10109                "setApplicationHiddenSetting for user " + userId);
10110
10111        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10112            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10113            return false;
10114        }
10115
10116        long callingId = Binder.clearCallingIdentity();
10117        try {
10118            boolean sendAdded = false;
10119            boolean sendRemoved = false;
10120            // writer
10121            synchronized (mPackages) {
10122                pkgSetting = mSettings.mPackages.get(packageName);
10123                if (pkgSetting == null) {
10124                    return false;
10125                }
10126                if (pkgSetting.getHidden(userId) != hidden) {
10127                    pkgSetting.setHidden(hidden, userId);
10128                    mSettings.writePackageRestrictionsLPr(userId);
10129                    if (hidden) {
10130                        sendRemoved = true;
10131                    } else {
10132                        sendAdded = true;
10133                    }
10134                }
10135            }
10136            if (sendAdded) {
10137                sendPackageAddedForUser(packageName, pkgSetting, userId);
10138                return true;
10139            }
10140            if (sendRemoved) {
10141                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10142                        "hiding pkg");
10143                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10144                return true;
10145            }
10146        } finally {
10147            Binder.restoreCallingIdentity(callingId);
10148        }
10149        return false;
10150    }
10151
10152    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10153            int userId) {
10154        final PackageRemovedInfo info = new PackageRemovedInfo();
10155        info.removedPackage = packageName;
10156        info.removedUsers = new int[] {userId};
10157        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10158        info.sendBroadcast(false, false, false);
10159    }
10160
10161    /**
10162     * Returns true if application is not found or there was an error. Otherwise it returns
10163     * the hidden state of the package for the given user.
10164     */
10165    @Override
10166    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10167        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10168        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10169                false, "getApplicationHidden for user " + userId);
10170        PackageSetting pkgSetting;
10171        long callingId = Binder.clearCallingIdentity();
10172        try {
10173            // writer
10174            synchronized (mPackages) {
10175                pkgSetting = mSettings.mPackages.get(packageName);
10176                if (pkgSetting == null) {
10177                    return true;
10178                }
10179                return pkgSetting.getHidden(userId);
10180            }
10181        } finally {
10182            Binder.restoreCallingIdentity(callingId);
10183        }
10184    }
10185
10186    /**
10187     * @hide
10188     */
10189    @Override
10190    public int installExistingPackageAsUser(String packageName, int userId) {
10191        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10192                null);
10193        PackageSetting pkgSetting;
10194        final int uid = Binder.getCallingUid();
10195        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10196                + userId);
10197        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10198            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10199        }
10200
10201        long callingId = Binder.clearCallingIdentity();
10202        try {
10203            boolean sendAdded = false;
10204
10205            // writer
10206            synchronized (mPackages) {
10207                pkgSetting = mSettings.mPackages.get(packageName);
10208                if (pkgSetting == null) {
10209                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10210                }
10211                if (!pkgSetting.getInstalled(userId)) {
10212                    pkgSetting.setInstalled(true, userId);
10213                    pkgSetting.setHidden(false, userId);
10214                    mSettings.writePackageRestrictionsLPr(userId);
10215                    sendAdded = true;
10216                }
10217            }
10218
10219            if (sendAdded) {
10220                sendPackageAddedForUser(packageName, pkgSetting, userId);
10221            }
10222        } finally {
10223            Binder.restoreCallingIdentity(callingId);
10224        }
10225
10226        return PackageManager.INSTALL_SUCCEEDED;
10227    }
10228
10229    boolean isUserRestricted(int userId, String restrictionKey) {
10230        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10231        if (restrictions.getBoolean(restrictionKey, false)) {
10232            Log.w(TAG, "User is restricted: " + restrictionKey);
10233            return true;
10234        }
10235        return false;
10236    }
10237
10238    @Override
10239    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10240        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10241        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10242                "setPackageSuspended for user " + userId);
10243
10244        long callingId = Binder.clearCallingIdentity();
10245        try {
10246            synchronized (mPackages) {
10247                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10248                if (pkgSetting != null) {
10249                    if (pkgSetting.getSuspended(userId) != suspended) {
10250                        pkgSetting.setSuspended(suspended, userId);
10251                        mSettings.writePackageRestrictionsLPr(userId);
10252                    }
10253
10254                    // TODO:
10255                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10256                    // * remove app from recents (kill app it if it is running)
10257                    // * erase existing notifications for this app
10258                    return true;
10259                }
10260
10261                return false;
10262            }
10263        } finally {
10264            Binder.restoreCallingIdentity(callingId);
10265        }
10266    }
10267
10268    @Override
10269    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10270        mContext.enforceCallingOrSelfPermission(
10271                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10272                "Only package verification agents can verify applications");
10273
10274        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10275        final PackageVerificationResponse response = new PackageVerificationResponse(
10276                verificationCode, Binder.getCallingUid());
10277        msg.arg1 = id;
10278        msg.obj = response;
10279        mHandler.sendMessage(msg);
10280    }
10281
10282    @Override
10283    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10284            long millisecondsToDelay) {
10285        mContext.enforceCallingOrSelfPermission(
10286                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10287                "Only package verification agents can extend verification timeouts");
10288
10289        final PackageVerificationState state = mPendingVerification.get(id);
10290        final PackageVerificationResponse response = new PackageVerificationResponse(
10291                verificationCodeAtTimeout, Binder.getCallingUid());
10292
10293        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10294            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10295        }
10296        if (millisecondsToDelay < 0) {
10297            millisecondsToDelay = 0;
10298        }
10299        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10300                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10301            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10302        }
10303
10304        if ((state != null) && !state.timeoutExtended()) {
10305            state.extendTimeout();
10306
10307            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10308            msg.arg1 = id;
10309            msg.obj = response;
10310            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10311        }
10312    }
10313
10314    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10315            int verificationCode, UserHandle user) {
10316        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10317        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10318        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10319        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10320        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10321
10322        mContext.sendBroadcastAsUser(intent, user,
10323                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10324    }
10325
10326    private ComponentName matchComponentForVerifier(String packageName,
10327            List<ResolveInfo> receivers) {
10328        ActivityInfo targetReceiver = null;
10329
10330        final int NR = receivers.size();
10331        for (int i = 0; i < NR; i++) {
10332            final ResolveInfo info = receivers.get(i);
10333            if (info.activityInfo == null) {
10334                continue;
10335            }
10336
10337            if (packageName.equals(info.activityInfo.packageName)) {
10338                targetReceiver = info.activityInfo;
10339                break;
10340            }
10341        }
10342
10343        if (targetReceiver == null) {
10344            return null;
10345        }
10346
10347        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10348    }
10349
10350    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10351            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10352        if (pkgInfo.verifiers.length == 0) {
10353            return null;
10354        }
10355
10356        final int N = pkgInfo.verifiers.length;
10357        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10358        for (int i = 0; i < N; i++) {
10359            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10360
10361            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10362                    receivers);
10363            if (comp == null) {
10364                continue;
10365            }
10366
10367            final int verifierUid = getUidForVerifier(verifierInfo);
10368            if (verifierUid == -1) {
10369                continue;
10370            }
10371
10372            if (DEBUG_VERIFY) {
10373                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10374                        + " with the correct signature");
10375            }
10376            sufficientVerifiers.add(comp);
10377            verificationState.addSufficientVerifier(verifierUid);
10378        }
10379
10380        return sufficientVerifiers;
10381    }
10382
10383    private int getUidForVerifier(VerifierInfo verifierInfo) {
10384        synchronized (mPackages) {
10385            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10386            if (pkg == null) {
10387                return -1;
10388            } else if (pkg.mSignatures.length != 1) {
10389                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10390                        + " has more than one signature; ignoring");
10391                return -1;
10392            }
10393
10394            /*
10395             * If the public key of the package's signature does not match
10396             * our expected public key, then this is a different package and
10397             * we should skip.
10398             */
10399
10400            final byte[] expectedPublicKey;
10401            try {
10402                final Signature verifierSig = pkg.mSignatures[0];
10403                final PublicKey publicKey = verifierSig.getPublicKey();
10404                expectedPublicKey = publicKey.getEncoded();
10405            } catch (CertificateException e) {
10406                return -1;
10407            }
10408
10409            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10410
10411            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10412                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10413                        + " does not have the expected public key; ignoring");
10414                return -1;
10415            }
10416
10417            return pkg.applicationInfo.uid;
10418        }
10419    }
10420
10421    @Override
10422    public void finishPackageInstall(int token) {
10423        enforceSystemOrRoot("Only the system is allowed to finish installs");
10424
10425        if (DEBUG_INSTALL) {
10426            Slog.v(TAG, "BM finishing package install for " + token);
10427        }
10428        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10429
10430        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10431        mHandler.sendMessage(msg);
10432    }
10433
10434    /**
10435     * Get the verification agent timeout.
10436     *
10437     * @return verification timeout in milliseconds
10438     */
10439    private long getVerificationTimeout() {
10440        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10441                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10442                DEFAULT_VERIFICATION_TIMEOUT);
10443    }
10444
10445    /**
10446     * Get the default verification agent response code.
10447     *
10448     * @return default verification response code
10449     */
10450    private int getDefaultVerificationResponse() {
10451        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10452                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10453                DEFAULT_VERIFICATION_RESPONSE);
10454    }
10455
10456    /**
10457     * Check whether or not package verification has been enabled.
10458     *
10459     * @return true if verification should be performed
10460     */
10461    private boolean isVerificationEnabled(int userId, int installFlags) {
10462        if (!DEFAULT_VERIFY_ENABLE) {
10463            return false;
10464        }
10465        // Ephemeral apps don't get the full verification treatment
10466        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10467            if (DEBUG_EPHEMERAL) {
10468                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10469            }
10470            return false;
10471        }
10472
10473        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10474
10475        // Check if installing from ADB
10476        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10477            // Do not run verification in a test harness environment
10478            if (ActivityManager.isRunningInTestHarness()) {
10479                return false;
10480            }
10481            if (ensureVerifyAppsEnabled) {
10482                return true;
10483            }
10484            // Check if the developer does not want package verification for ADB installs
10485            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10486                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10487                return false;
10488            }
10489        }
10490
10491        if (ensureVerifyAppsEnabled) {
10492            return true;
10493        }
10494
10495        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10496                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10497    }
10498
10499    @Override
10500    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10501            throws RemoteException {
10502        mContext.enforceCallingOrSelfPermission(
10503                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10504                "Only intentfilter verification agents can verify applications");
10505
10506        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10507        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10508                Binder.getCallingUid(), verificationCode, failedDomains);
10509        msg.arg1 = id;
10510        msg.obj = response;
10511        mHandler.sendMessage(msg);
10512    }
10513
10514    @Override
10515    public int getIntentVerificationStatus(String packageName, int userId) {
10516        synchronized (mPackages) {
10517            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10518        }
10519    }
10520
10521    @Override
10522    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10523        mContext.enforceCallingOrSelfPermission(
10524                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10525
10526        boolean result = false;
10527        synchronized (mPackages) {
10528            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10529        }
10530        if (result) {
10531            scheduleWritePackageRestrictionsLocked(userId);
10532        }
10533        return result;
10534    }
10535
10536    @Override
10537    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10538        synchronized (mPackages) {
10539            return mSettings.getIntentFilterVerificationsLPr(packageName);
10540        }
10541    }
10542
10543    @Override
10544    public List<IntentFilter> getAllIntentFilters(String packageName) {
10545        if (TextUtils.isEmpty(packageName)) {
10546            return Collections.<IntentFilter>emptyList();
10547        }
10548        synchronized (mPackages) {
10549            PackageParser.Package pkg = mPackages.get(packageName);
10550            if (pkg == null || pkg.activities == null) {
10551                return Collections.<IntentFilter>emptyList();
10552            }
10553            final int count = pkg.activities.size();
10554            ArrayList<IntentFilter> result = new ArrayList<>();
10555            for (int n=0; n<count; n++) {
10556                PackageParser.Activity activity = pkg.activities.get(n);
10557                if (activity.intents != null && activity.intents.size() > 0) {
10558                    result.addAll(activity.intents);
10559                }
10560            }
10561            return result;
10562        }
10563    }
10564
10565    @Override
10566    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10567        mContext.enforceCallingOrSelfPermission(
10568                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10569
10570        synchronized (mPackages) {
10571            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10572            if (packageName != null) {
10573                result |= updateIntentVerificationStatus(packageName,
10574                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10575                        userId);
10576                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10577                        packageName, userId);
10578            }
10579            return result;
10580        }
10581    }
10582
10583    @Override
10584    public String getDefaultBrowserPackageName(int userId) {
10585        synchronized (mPackages) {
10586            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10587        }
10588    }
10589
10590    /**
10591     * Get the "allow unknown sources" setting.
10592     *
10593     * @return the current "allow unknown sources" setting
10594     */
10595    private int getUnknownSourcesSettings() {
10596        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10597                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10598                -1);
10599    }
10600
10601    @Override
10602    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10603        final int uid = Binder.getCallingUid();
10604        // writer
10605        synchronized (mPackages) {
10606            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10607            if (targetPackageSetting == null) {
10608                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10609            }
10610
10611            PackageSetting installerPackageSetting;
10612            if (installerPackageName != null) {
10613                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10614                if (installerPackageSetting == null) {
10615                    throw new IllegalArgumentException("Unknown installer package: "
10616                            + installerPackageName);
10617                }
10618            } else {
10619                installerPackageSetting = null;
10620            }
10621
10622            Signature[] callerSignature;
10623            Object obj = mSettings.getUserIdLPr(uid);
10624            if (obj != null) {
10625                if (obj instanceof SharedUserSetting) {
10626                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10627                } else if (obj instanceof PackageSetting) {
10628                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10629                } else {
10630                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10631                }
10632            } else {
10633                throw new SecurityException("Unknown calling UID: " + uid);
10634            }
10635
10636            // Verify: can't set installerPackageName to a package that is
10637            // not signed with the same cert as the caller.
10638            if (installerPackageSetting != null) {
10639                if (compareSignatures(callerSignature,
10640                        installerPackageSetting.signatures.mSignatures)
10641                        != PackageManager.SIGNATURE_MATCH) {
10642                    throw new SecurityException(
10643                            "Caller does not have same cert as new installer package "
10644                            + installerPackageName);
10645                }
10646            }
10647
10648            // Verify: if target already has an installer package, it must
10649            // be signed with the same cert as the caller.
10650            if (targetPackageSetting.installerPackageName != null) {
10651                PackageSetting setting = mSettings.mPackages.get(
10652                        targetPackageSetting.installerPackageName);
10653                // If the currently set package isn't valid, then it's always
10654                // okay to change it.
10655                if (setting != null) {
10656                    if (compareSignatures(callerSignature,
10657                            setting.signatures.mSignatures)
10658                            != PackageManager.SIGNATURE_MATCH) {
10659                        throw new SecurityException(
10660                                "Caller does not have same cert as old installer package "
10661                                + targetPackageSetting.installerPackageName);
10662                    }
10663                }
10664            }
10665
10666            // Okay!
10667            targetPackageSetting.installerPackageName = installerPackageName;
10668            scheduleWriteSettingsLocked();
10669        }
10670    }
10671
10672    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10673        // Queue up an async operation since the package installation may take a little while.
10674        mHandler.post(new Runnable() {
10675            public void run() {
10676                mHandler.removeCallbacks(this);
10677                 // Result object to be returned
10678                PackageInstalledInfo res = new PackageInstalledInfo();
10679                res.returnCode = currentStatus;
10680                res.uid = -1;
10681                res.pkg = null;
10682                res.removedInfo = new PackageRemovedInfo();
10683                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10684                    args.doPreInstall(res.returnCode);
10685                    synchronized (mInstallLock) {
10686                        installPackageTracedLI(args, res);
10687                    }
10688                    args.doPostInstall(res.returnCode, res.uid);
10689                }
10690
10691                // A restore should be performed at this point if (a) the install
10692                // succeeded, (b) the operation is not an update, and (c) the new
10693                // package has not opted out of backup participation.
10694                final boolean update = res.removedInfo.removedPackage != null;
10695                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10696                boolean doRestore = !update
10697                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10698
10699                // Set up the post-install work request bookkeeping.  This will be used
10700                // and cleaned up by the post-install event handling regardless of whether
10701                // there's a restore pass performed.  Token values are >= 1.
10702                int token;
10703                if (mNextInstallToken < 0) mNextInstallToken = 1;
10704                token = mNextInstallToken++;
10705
10706                PostInstallData data = new PostInstallData(args, res);
10707                mRunningInstalls.put(token, data);
10708                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10709
10710                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10711                    // Pass responsibility to the Backup Manager.  It will perform a
10712                    // restore if appropriate, then pass responsibility back to the
10713                    // Package Manager to run the post-install observer callbacks
10714                    // and broadcasts.
10715                    IBackupManager bm = IBackupManager.Stub.asInterface(
10716                            ServiceManager.getService(Context.BACKUP_SERVICE));
10717                    if (bm != null) {
10718                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10719                                + " to BM for possible restore");
10720                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10721                        try {
10722                            // TODO: http://b/22388012
10723                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10724                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10725                            } else {
10726                                doRestore = false;
10727                            }
10728                        } catch (RemoteException e) {
10729                            // can't happen; the backup manager is local
10730                        } catch (Exception e) {
10731                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10732                            doRestore = false;
10733                        }
10734                    } else {
10735                        Slog.e(TAG, "Backup Manager not found!");
10736                        doRestore = false;
10737                    }
10738                }
10739
10740                if (!doRestore) {
10741                    // No restore possible, or the Backup Manager was mysteriously not
10742                    // available -- just fire the post-install work request directly.
10743                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10744
10745                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10746
10747                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10748                    mHandler.sendMessage(msg);
10749                }
10750            }
10751        });
10752    }
10753
10754    private abstract class HandlerParams {
10755        private static final int MAX_RETRIES = 4;
10756
10757        /**
10758         * Number of times startCopy() has been attempted and had a non-fatal
10759         * error.
10760         */
10761        private int mRetries = 0;
10762
10763        /** User handle for the user requesting the information or installation. */
10764        private final UserHandle mUser;
10765        String traceMethod;
10766        int traceCookie;
10767
10768        HandlerParams(UserHandle user) {
10769            mUser = user;
10770        }
10771
10772        UserHandle getUser() {
10773            return mUser;
10774        }
10775
10776        HandlerParams setTraceMethod(String traceMethod) {
10777            this.traceMethod = traceMethod;
10778            return this;
10779        }
10780
10781        HandlerParams setTraceCookie(int traceCookie) {
10782            this.traceCookie = traceCookie;
10783            return this;
10784        }
10785
10786        final boolean startCopy() {
10787            boolean res;
10788            try {
10789                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10790
10791                if (++mRetries > MAX_RETRIES) {
10792                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10793                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10794                    handleServiceError();
10795                    return false;
10796                } else {
10797                    handleStartCopy();
10798                    res = true;
10799                }
10800            } catch (RemoteException e) {
10801                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10802                mHandler.sendEmptyMessage(MCS_RECONNECT);
10803                res = false;
10804            }
10805            handleReturnCode();
10806            return res;
10807        }
10808
10809        final void serviceError() {
10810            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10811            handleServiceError();
10812            handleReturnCode();
10813        }
10814
10815        abstract void handleStartCopy() throws RemoteException;
10816        abstract void handleServiceError();
10817        abstract void handleReturnCode();
10818    }
10819
10820    class MeasureParams extends HandlerParams {
10821        private final PackageStats mStats;
10822        private boolean mSuccess;
10823
10824        private final IPackageStatsObserver mObserver;
10825
10826        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10827            super(new UserHandle(stats.userHandle));
10828            mObserver = observer;
10829            mStats = stats;
10830        }
10831
10832        @Override
10833        public String toString() {
10834            return "MeasureParams{"
10835                + Integer.toHexString(System.identityHashCode(this))
10836                + " " + mStats.packageName + "}";
10837        }
10838
10839        @Override
10840        void handleStartCopy() throws RemoteException {
10841            synchronized (mInstallLock) {
10842                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10843            }
10844
10845            if (mSuccess) {
10846                final boolean mounted;
10847                if (Environment.isExternalStorageEmulated()) {
10848                    mounted = true;
10849                } else {
10850                    final String status = Environment.getExternalStorageState();
10851                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10852                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10853                }
10854
10855                if (mounted) {
10856                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10857
10858                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10859                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10860
10861                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10862                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10863
10864                    // Always subtract cache size, since it's a subdirectory
10865                    mStats.externalDataSize -= mStats.externalCacheSize;
10866
10867                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10868                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10869
10870                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10871                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10872                }
10873            }
10874        }
10875
10876        @Override
10877        void handleReturnCode() {
10878            if (mObserver != null) {
10879                try {
10880                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10881                } catch (RemoteException e) {
10882                    Slog.i(TAG, "Observer no longer exists.");
10883                }
10884            }
10885        }
10886
10887        @Override
10888        void handleServiceError() {
10889            Slog.e(TAG, "Could not measure application " + mStats.packageName
10890                            + " external storage");
10891        }
10892    }
10893
10894    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10895            throws RemoteException {
10896        long result = 0;
10897        for (File path : paths) {
10898            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10899        }
10900        return result;
10901    }
10902
10903    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10904        for (File path : paths) {
10905            try {
10906                mcs.clearDirectory(path.getAbsolutePath());
10907            } catch (RemoteException e) {
10908            }
10909        }
10910    }
10911
10912    static class OriginInfo {
10913        /**
10914         * Location where install is coming from, before it has been
10915         * copied/renamed into place. This could be a single monolithic APK
10916         * file, or a cluster directory. This location may be untrusted.
10917         */
10918        final File file;
10919        final String cid;
10920
10921        /**
10922         * Flag indicating that {@link #file} or {@link #cid} has already been
10923         * staged, meaning downstream users don't need to defensively copy the
10924         * contents.
10925         */
10926        final boolean staged;
10927
10928        /**
10929         * Flag indicating that {@link #file} or {@link #cid} is an already
10930         * installed app that is being moved.
10931         */
10932        final boolean existing;
10933
10934        final String resolvedPath;
10935        final File resolvedFile;
10936
10937        static OriginInfo fromNothing() {
10938            return new OriginInfo(null, null, false, false);
10939        }
10940
10941        static OriginInfo fromUntrustedFile(File file) {
10942            return new OriginInfo(file, null, false, false);
10943        }
10944
10945        static OriginInfo fromExistingFile(File file) {
10946            return new OriginInfo(file, null, false, true);
10947        }
10948
10949        static OriginInfo fromStagedFile(File file) {
10950            return new OriginInfo(file, null, true, false);
10951        }
10952
10953        static OriginInfo fromStagedContainer(String cid) {
10954            return new OriginInfo(null, cid, true, false);
10955        }
10956
10957        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10958            this.file = file;
10959            this.cid = cid;
10960            this.staged = staged;
10961            this.existing = existing;
10962
10963            if (cid != null) {
10964                resolvedPath = PackageHelper.getSdDir(cid);
10965                resolvedFile = new File(resolvedPath);
10966            } else if (file != null) {
10967                resolvedPath = file.getAbsolutePath();
10968                resolvedFile = file;
10969            } else {
10970                resolvedPath = null;
10971                resolvedFile = null;
10972            }
10973        }
10974    }
10975
10976    static class MoveInfo {
10977        final int moveId;
10978        final String fromUuid;
10979        final String toUuid;
10980        final String packageName;
10981        final String dataAppName;
10982        final int appId;
10983        final String seinfo;
10984
10985        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10986                String dataAppName, int appId, String seinfo) {
10987            this.moveId = moveId;
10988            this.fromUuid = fromUuid;
10989            this.toUuid = toUuid;
10990            this.packageName = packageName;
10991            this.dataAppName = dataAppName;
10992            this.appId = appId;
10993            this.seinfo = seinfo;
10994        }
10995    }
10996
10997    class InstallParams extends HandlerParams {
10998        final OriginInfo origin;
10999        final MoveInfo move;
11000        final IPackageInstallObserver2 observer;
11001        int installFlags;
11002        final String installerPackageName;
11003        final String volumeUuid;
11004        final VerificationParams verificationParams;
11005        private InstallArgs mArgs;
11006        private int mRet;
11007        final String packageAbiOverride;
11008        final String[] grantedRuntimePermissions;
11009
11010        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11011                int installFlags, String installerPackageName, String volumeUuid,
11012                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11013                String[] grantedPermissions) {
11014            super(user);
11015            this.origin = origin;
11016            this.move = move;
11017            this.observer = observer;
11018            this.installFlags = installFlags;
11019            this.installerPackageName = installerPackageName;
11020            this.volumeUuid = volumeUuid;
11021            this.verificationParams = verificationParams;
11022            this.packageAbiOverride = packageAbiOverride;
11023            this.grantedRuntimePermissions = grantedPermissions;
11024        }
11025
11026        @Override
11027        public String toString() {
11028            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11029                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11030        }
11031
11032        private int installLocationPolicy(PackageInfoLite pkgLite) {
11033            String packageName = pkgLite.packageName;
11034            int installLocation = pkgLite.installLocation;
11035            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11036            // reader
11037            synchronized (mPackages) {
11038                PackageParser.Package pkg = mPackages.get(packageName);
11039                if (pkg != null) {
11040                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11041                        // Check for downgrading.
11042                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11043                            try {
11044                                checkDowngrade(pkg, pkgLite);
11045                            } catch (PackageManagerException e) {
11046                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11047                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11048                            }
11049                        }
11050                        // Check for updated system application.
11051                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11052                            if (onSd) {
11053                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11054                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11055                            }
11056                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11057                        } else {
11058                            if (onSd) {
11059                                // Install flag overrides everything.
11060                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11061                            }
11062                            // If current upgrade specifies particular preference
11063                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11064                                // Application explicitly specified internal.
11065                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11066                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11067                                // App explictly prefers external. Let policy decide
11068                            } else {
11069                                // Prefer previous location
11070                                if (isExternal(pkg)) {
11071                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11072                                }
11073                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11074                            }
11075                        }
11076                    } else {
11077                        // Invalid install. Return error code
11078                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11079                    }
11080                }
11081            }
11082            // All the special cases have been taken care of.
11083            // Return result based on recommended install location.
11084            if (onSd) {
11085                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11086            }
11087            return pkgLite.recommendedInstallLocation;
11088        }
11089
11090        /*
11091         * Invoke remote method to get package information and install
11092         * location values. Override install location based on default
11093         * policy if needed and then create install arguments based
11094         * on the install location.
11095         */
11096        public void handleStartCopy() throws RemoteException {
11097            int ret = PackageManager.INSTALL_SUCCEEDED;
11098
11099            // If we're already staged, we've firmly committed to an install location
11100            if (origin.staged) {
11101                if (origin.file != null) {
11102                    installFlags |= PackageManager.INSTALL_INTERNAL;
11103                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11104                } else if (origin.cid != null) {
11105                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11106                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11107                } else {
11108                    throw new IllegalStateException("Invalid stage location");
11109                }
11110            }
11111
11112            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11113            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11114            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11115            PackageInfoLite pkgLite = null;
11116
11117            if (onInt && onSd) {
11118                // Check if both bits are set.
11119                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11120                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11121            } else if (onSd && ephemeral) {
11122                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11123                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11124            } else {
11125                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11126                        packageAbiOverride);
11127
11128                if (DEBUG_EPHEMERAL && ephemeral) {
11129                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11130                }
11131
11132                /*
11133                 * If we have too little free space, try to free cache
11134                 * before giving up.
11135                 */
11136                if (!origin.staged && pkgLite.recommendedInstallLocation
11137                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11138                    // TODO: focus freeing disk space on the target device
11139                    final StorageManager storage = StorageManager.from(mContext);
11140                    final long lowThreshold = storage.getStorageLowBytes(
11141                            Environment.getDataDirectory());
11142
11143                    final long sizeBytes = mContainerService.calculateInstalledSize(
11144                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11145
11146                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11147                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11148                                installFlags, packageAbiOverride);
11149                    }
11150
11151                    /*
11152                     * The cache free must have deleted the file we
11153                     * downloaded to install.
11154                     *
11155                     * TODO: fix the "freeCache" call to not delete
11156                     *       the file we care about.
11157                     */
11158                    if (pkgLite.recommendedInstallLocation
11159                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11160                        pkgLite.recommendedInstallLocation
11161                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11162                    }
11163                }
11164            }
11165
11166            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11167                int loc = pkgLite.recommendedInstallLocation;
11168                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11169                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11170                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11171                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11172                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11173                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11174                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11175                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11176                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11177                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11178                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11179                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11180                } else {
11181                    // Override with defaults if needed.
11182                    loc = installLocationPolicy(pkgLite);
11183                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11184                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11185                    } else if (!onSd && !onInt) {
11186                        // Override install location with flags
11187                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11188                            // Set the flag to install on external media.
11189                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11190                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11191                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11192                            if (DEBUG_EPHEMERAL) {
11193                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11194                            }
11195                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11196                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11197                                    |PackageManager.INSTALL_INTERNAL);
11198                        } else {
11199                            // Make sure the flag for installing on external
11200                            // media is unset
11201                            installFlags |= PackageManager.INSTALL_INTERNAL;
11202                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11203                        }
11204                    }
11205                }
11206            }
11207
11208            final InstallArgs args = createInstallArgs(this);
11209            mArgs = args;
11210
11211            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11212                // TODO: http://b/22976637
11213                // Apps installed for "all" users use the device owner to verify the app
11214                UserHandle verifierUser = getUser();
11215                if (verifierUser == UserHandle.ALL) {
11216                    verifierUser = UserHandle.SYSTEM;
11217                }
11218
11219                /*
11220                 * Determine if we have any installed package verifiers. If we
11221                 * do, then we'll defer to them to verify the packages.
11222                 */
11223                final int requiredUid = mRequiredVerifierPackage == null ? -1
11224                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11225                                verifierUser.getIdentifier());
11226                if (!origin.existing && requiredUid != -1
11227                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11228                    final Intent verification = new Intent(
11229                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11230                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11231                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11232                            PACKAGE_MIME_TYPE);
11233                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11234
11235                    // Query all live verifiers based on current user state
11236                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11237                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11238
11239                    if (DEBUG_VERIFY) {
11240                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11241                                + verification.toString() + " with " + pkgLite.verifiers.length
11242                                + " optional verifiers");
11243                    }
11244
11245                    final int verificationId = mPendingVerificationToken++;
11246
11247                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11248
11249                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11250                            installerPackageName);
11251
11252                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11253                            installFlags);
11254
11255                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11256                            pkgLite.packageName);
11257
11258                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11259                            pkgLite.versionCode);
11260
11261                    if (verificationParams != null) {
11262                        if (verificationParams.getVerificationURI() != null) {
11263                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11264                                 verificationParams.getVerificationURI());
11265                        }
11266                        if (verificationParams.getOriginatingURI() != null) {
11267                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11268                                  verificationParams.getOriginatingURI());
11269                        }
11270                        if (verificationParams.getReferrer() != null) {
11271                            verification.putExtra(Intent.EXTRA_REFERRER,
11272                                  verificationParams.getReferrer());
11273                        }
11274                        if (verificationParams.getOriginatingUid() >= 0) {
11275                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11276                                  verificationParams.getOriginatingUid());
11277                        }
11278                        if (verificationParams.getInstallerUid() >= 0) {
11279                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11280                                  verificationParams.getInstallerUid());
11281                        }
11282                    }
11283
11284                    final PackageVerificationState verificationState = new PackageVerificationState(
11285                            requiredUid, args);
11286
11287                    mPendingVerification.append(verificationId, verificationState);
11288
11289                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11290                            receivers, verificationState);
11291
11292                    /*
11293                     * If any sufficient verifiers were listed in the package
11294                     * manifest, attempt to ask them.
11295                     */
11296                    if (sufficientVerifiers != null) {
11297                        final int N = sufficientVerifiers.size();
11298                        if (N == 0) {
11299                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11300                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11301                        } else {
11302                            for (int i = 0; i < N; i++) {
11303                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11304
11305                                final Intent sufficientIntent = new Intent(verification);
11306                                sufficientIntent.setComponent(verifierComponent);
11307                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11308                            }
11309                        }
11310                    }
11311
11312                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11313                            mRequiredVerifierPackage, receivers);
11314                    if (ret == PackageManager.INSTALL_SUCCEEDED
11315                            && mRequiredVerifierPackage != null) {
11316                        Trace.asyncTraceBegin(
11317                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11318                        /*
11319                         * Send the intent to the required verification agent,
11320                         * but only start the verification timeout after the
11321                         * target BroadcastReceivers have run.
11322                         */
11323                        verification.setComponent(requiredVerifierComponent);
11324                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11325                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11326                                new BroadcastReceiver() {
11327                                    @Override
11328                                    public void onReceive(Context context, Intent intent) {
11329                                        final Message msg = mHandler
11330                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11331                                        msg.arg1 = verificationId;
11332                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11333                                    }
11334                                }, null, 0, null, null);
11335
11336                        /*
11337                         * We don't want the copy to proceed until verification
11338                         * succeeds, so null out this field.
11339                         */
11340                        mArgs = null;
11341                    }
11342                } else {
11343                    /*
11344                     * No package verification is enabled, so immediately start
11345                     * the remote call to initiate copy using temporary file.
11346                     */
11347                    ret = args.copyApk(mContainerService, true);
11348                }
11349            }
11350
11351            mRet = ret;
11352        }
11353
11354        @Override
11355        void handleReturnCode() {
11356            // If mArgs is null, then MCS couldn't be reached. When it
11357            // reconnects, it will try again to install. At that point, this
11358            // will succeed.
11359            if (mArgs != null) {
11360                processPendingInstall(mArgs, mRet);
11361            }
11362        }
11363
11364        @Override
11365        void handleServiceError() {
11366            mArgs = createInstallArgs(this);
11367            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11368        }
11369
11370        public boolean isForwardLocked() {
11371            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11372        }
11373    }
11374
11375    /**
11376     * Used during creation of InstallArgs
11377     *
11378     * @param installFlags package installation flags
11379     * @return true if should be installed on external storage
11380     */
11381    private static boolean installOnExternalAsec(int installFlags) {
11382        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11383            return false;
11384        }
11385        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11386            return true;
11387        }
11388        return false;
11389    }
11390
11391    /**
11392     * Used during creation of InstallArgs
11393     *
11394     * @param installFlags package installation flags
11395     * @return true if should be installed as forward locked
11396     */
11397    private static boolean installForwardLocked(int installFlags) {
11398        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11399    }
11400
11401    private InstallArgs createInstallArgs(InstallParams params) {
11402        if (params.move != null) {
11403            return new MoveInstallArgs(params);
11404        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11405            return new AsecInstallArgs(params);
11406        } else {
11407            return new FileInstallArgs(params);
11408        }
11409    }
11410
11411    /**
11412     * Create args that describe an existing installed package. Typically used
11413     * when cleaning up old installs, or used as a move source.
11414     */
11415    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11416            String resourcePath, String[] instructionSets) {
11417        final boolean isInAsec;
11418        if (installOnExternalAsec(installFlags)) {
11419            /* Apps on SD card are always in ASEC containers. */
11420            isInAsec = true;
11421        } else if (installForwardLocked(installFlags)
11422                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11423            /*
11424             * Forward-locked apps are only in ASEC containers if they're the
11425             * new style
11426             */
11427            isInAsec = true;
11428        } else {
11429            isInAsec = false;
11430        }
11431
11432        if (isInAsec) {
11433            return new AsecInstallArgs(codePath, instructionSets,
11434                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11435        } else {
11436            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11437        }
11438    }
11439
11440    static abstract class InstallArgs {
11441        /** @see InstallParams#origin */
11442        final OriginInfo origin;
11443        /** @see InstallParams#move */
11444        final MoveInfo move;
11445
11446        final IPackageInstallObserver2 observer;
11447        // Always refers to PackageManager flags only
11448        final int installFlags;
11449        final String installerPackageName;
11450        final String volumeUuid;
11451        final UserHandle user;
11452        final String abiOverride;
11453        final String[] installGrantPermissions;
11454        /** If non-null, drop an async trace when the install completes */
11455        final String traceMethod;
11456        final int traceCookie;
11457
11458        // The list of instruction sets supported by this app. This is currently
11459        // only used during the rmdex() phase to clean up resources. We can get rid of this
11460        // if we move dex files under the common app path.
11461        /* nullable */ String[] instructionSets;
11462
11463        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11464                int installFlags, String installerPackageName, String volumeUuid,
11465                UserHandle user, String[] instructionSets,
11466                String abiOverride, String[] installGrantPermissions,
11467                String traceMethod, int traceCookie) {
11468            this.origin = origin;
11469            this.move = move;
11470            this.installFlags = installFlags;
11471            this.observer = observer;
11472            this.installerPackageName = installerPackageName;
11473            this.volumeUuid = volumeUuid;
11474            this.user = user;
11475            this.instructionSets = instructionSets;
11476            this.abiOverride = abiOverride;
11477            this.installGrantPermissions = installGrantPermissions;
11478            this.traceMethod = traceMethod;
11479            this.traceCookie = traceCookie;
11480        }
11481
11482        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11483        abstract int doPreInstall(int status);
11484
11485        /**
11486         * Rename package into final resting place. All paths on the given
11487         * scanned package should be updated to reflect the rename.
11488         */
11489        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11490        abstract int doPostInstall(int status, int uid);
11491
11492        /** @see PackageSettingBase#codePathString */
11493        abstract String getCodePath();
11494        /** @see PackageSettingBase#resourcePathString */
11495        abstract String getResourcePath();
11496
11497        // Need installer lock especially for dex file removal.
11498        abstract void cleanUpResourcesLI();
11499        abstract boolean doPostDeleteLI(boolean delete);
11500
11501        /**
11502         * Called before the source arguments are copied. This is used mostly
11503         * for MoveParams when it needs to read the source file to put it in the
11504         * destination.
11505         */
11506        int doPreCopy() {
11507            return PackageManager.INSTALL_SUCCEEDED;
11508        }
11509
11510        /**
11511         * Called after the source arguments are copied. This is used mostly for
11512         * MoveParams when it needs to read the source file to put it in the
11513         * destination.
11514         *
11515         * @return
11516         */
11517        int doPostCopy(int uid) {
11518            return PackageManager.INSTALL_SUCCEEDED;
11519        }
11520
11521        protected boolean isFwdLocked() {
11522            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11523        }
11524
11525        protected boolean isExternalAsec() {
11526            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11527        }
11528
11529        protected boolean isEphemeral() {
11530            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11531        }
11532
11533        UserHandle getUser() {
11534            return user;
11535        }
11536    }
11537
11538    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11539        if (!allCodePaths.isEmpty()) {
11540            if (instructionSets == null) {
11541                throw new IllegalStateException("instructionSet == null");
11542            }
11543            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11544            for (String codePath : allCodePaths) {
11545                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11546                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11547                    if (retCode < 0) {
11548                        Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath
11549                                + ", retcode=" + retCode);
11550                        // we don't consider this to be a failure of the core package deletion
11551                    }
11552                }
11553            }
11554        }
11555    }
11556
11557    /**
11558     * Logic to handle installation of non-ASEC applications, including copying
11559     * and renaming logic.
11560     */
11561    class FileInstallArgs extends InstallArgs {
11562        private File codeFile;
11563        private File resourceFile;
11564
11565        // Example topology:
11566        // /data/app/com.example/base.apk
11567        // /data/app/com.example/split_foo.apk
11568        // /data/app/com.example/lib/arm/libfoo.so
11569        // /data/app/com.example/lib/arm64/libfoo.so
11570        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11571
11572        /** New install */
11573        FileInstallArgs(InstallParams params) {
11574            super(params.origin, params.move, params.observer, params.installFlags,
11575                    params.installerPackageName, params.volumeUuid,
11576                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11577                    params.grantedRuntimePermissions,
11578                    params.traceMethod, params.traceCookie);
11579            if (isFwdLocked()) {
11580                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11581            }
11582        }
11583
11584        /** Existing install */
11585        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11586            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11587                    null, null, null, 0);
11588            this.codeFile = (codePath != null) ? new File(codePath) : null;
11589            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11590        }
11591
11592        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11593            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11594            try {
11595                return doCopyApk(imcs, temp);
11596            } finally {
11597                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11598            }
11599        }
11600
11601        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11602            if (origin.staged) {
11603                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11604                codeFile = origin.file;
11605                resourceFile = origin.file;
11606                return PackageManager.INSTALL_SUCCEEDED;
11607            }
11608
11609            try {
11610                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11611                final File tempDir =
11612                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11613                codeFile = tempDir;
11614                resourceFile = tempDir;
11615            } catch (IOException e) {
11616                Slog.w(TAG, "Failed to create copy file: " + e);
11617                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11618            }
11619
11620            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11621                @Override
11622                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11623                    if (!FileUtils.isValidExtFilename(name)) {
11624                        throw new IllegalArgumentException("Invalid filename: " + name);
11625                    }
11626                    try {
11627                        final File file = new File(codeFile, name);
11628                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11629                                O_RDWR | O_CREAT, 0644);
11630                        Os.chmod(file.getAbsolutePath(), 0644);
11631                        return new ParcelFileDescriptor(fd);
11632                    } catch (ErrnoException e) {
11633                        throw new RemoteException("Failed to open: " + e.getMessage());
11634                    }
11635                }
11636            };
11637
11638            int ret = PackageManager.INSTALL_SUCCEEDED;
11639            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11640            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11641                Slog.e(TAG, "Failed to copy package");
11642                return ret;
11643            }
11644
11645            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11646            NativeLibraryHelper.Handle handle = null;
11647            try {
11648                handle = NativeLibraryHelper.Handle.create(codeFile);
11649                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11650                        abiOverride);
11651            } catch (IOException e) {
11652                Slog.e(TAG, "Copying native libraries failed", e);
11653                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11654            } finally {
11655                IoUtils.closeQuietly(handle);
11656            }
11657
11658            return ret;
11659        }
11660
11661        int doPreInstall(int status) {
11662            if (status != PackageManager.INSTALL_SUCCEEDED) {
11663                cleanUp();
11664            }
11665            return status;
11666        }
11667
11668        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11669            if (status != PackageManager.INSTALL_SUCCEEDED) {
11670                cleanUp();
11671                return false;
11672            }
11673
11674            final File targetDir = codeFile.getParentFile();
11675            final File beforeCodeFile = codeFile;
11676            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11677
11678            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11679            try {
11680                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11681            } catch (ErrnoException e) {
11682                Slog.w(TAG, "Failed to rename", e);
11683                return false;
11684            }
11685
11686            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11687                Slog.w(TAG, "Failed to restorecon");
11688                return false;
11689            }
11690
11691            // Reflect the rename internally
11692            codeFile = afterCodeFile;
11693            resourceFile = afterCodeFile;
11694
11695            // Reflect the rename in scanned details
11696            pkg.codePath = afterCodeFile.getAbsolutePath();
11697            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11698                    pkg.baseCodePath);
11699            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11700                    pkg.splitCodePaths);
11701
11702            // Reflect the rename in app info
11703            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11704            pkg.applicationInfo.setCodePath(pkg.codePath);
11705            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11706            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11707            pkg.applicationInfo.setResourcePath(pkg.codePath);
11708            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11709            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11710
11711            return true;
11712        }
11713
11714        int doPostInstall(int status, int uid) {
11715            if (status != PackageManager.INSTALL_SUCCEEDED) {
11716                cleanUp();
11717            }
11718            return status;
11719        }
11720
11721        @Override
11722        String getCodePath() {
11723            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11724        }
11725
11726        @Override
11727        String getResourcePath() {
11728            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11729        }
11730
11731        private boolean cleanUp() {
11732            if (codeFile == null || !codeFile.exists()) {
11733                return false;
11734            }
11735
11736            if (codeFile.isDirectory()) {
11737                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11738            } else {
11739                codeFile.delete();
11740            }
11741
11742            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11743                resourceFile.delete();
11744            }
11745
11746            return true;
11747        }
11748
11749        void cleanUpResourcesLI() {
11750            // Try enumerating all code paths before deleting
11751            List<String> allCodePaths = Collections.EMPTY_LIST;
11752            if (codeFile != null && codeFile.exists()) {
11753                try {
11754                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11755                    allCodePaths = pkg.getAllCodePaths();
11756                } catch (PackageParserException e) {
11757                    // Ignored; we tried our best
11758                }
11759            }
11760
11761            cleanUp();
11762            removeDexFiles(allCodePaths, instructionSets);
11763        }
11764
11765        boolean doPostDeleteLI(boolean delete) {
11766            // XXX err, shouldn't we respect the delete flag?
11767            cleanUpResourcesLI();
11768            return true;
11769        }
11770    }
11771
11772    private boolean isAsecExternal(String cid) {
11773        final String asecPath = PackageHelper.getSdFilesystem(cid);
11774        return !asecPath.startsWith(mAsecInternalPath);
11775    }
11776
11777    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11778            PackageManagerException {
11779        if (copyRet < 0) {
11780            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11781                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11782                throw new PackageManagerException(copyRet, message);
11783            }
11784        }
11785    }
11786
11787    /**
11788     * Extract the MountService "container ID" from the full code path of an
11789     * .apk.
11790     */
11791    static String cidFromCodePath(String fullCodePath) {
11792        int eidx = fullCodePath.lastIndexOf("/");
11793        String subStr1 = fullCodePath.substring(0, eidx);
11794        int sidx = subStr1.lastIndexOf("/");
11795        return subStr1.substring(sidx+1, eidx);
11796    }
11797
11798    /**
11799     * Logic to handle installation of ASEC applications, including copying and
11800     * renaming logic.
11801     */
11802    class AsecInstallArgs extends InstallArgs {
11803        static final String RES_FILE_NAME = "pkg.apk";
11804        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11805
11806        String cid;
11807        String packagePath;
11808        String resourcePath;
11809
11810        /** New install */
11811        AsecInstallArgs(InstallParams params) {
11812            super(params.origin, params.move, params.observer, params.installFlags,
11813                    params.installerPackageName, params.volumeUuid,
11814                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11815                    params.grantedRuntimePermissions,
11816                    params.traceMethod, params.traceCookie);
11817        }
11818
11819        /** Existing install */
11820        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11821                        boolean isExternal, boolean isForwardLocked) {
11822            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11823                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11824                    instructionSets, null, null, null, 0);
11825            // Hackily pretend we're still looking at a full code path
11826            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11827                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11828            }
11829
11830            // Extract cid from fullCodePath
11831            int eidx = fullCodePath.lastIndexOf("/");
11832            String subStr1 = fullCodePath.substring(0, eidx);
11833            int sidx = subStr1.lastIndexOf("/");
11834            cid = subStr1.substring(sidx+1, eidx);
11835            setMountPath(subStr1);
11836        }
11837
11838        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11839            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11840                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11841                    instructionSets, null, null, null, 0);
11842            this.cid = cid;
11843            setMountPath(PackageHelper.getSdDir(cid));
11844        }
11845
11846        void createCopyFile() {
11847            cid = mInstallerService.allocateExternalStageCidLegacy();
11848        }
11849
11850        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11851            if (origin.staged && origin.cid != null) {
11852                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11853                cid = origin.cid;
11854                setMountPath(PackageHelper.getSdDir(cid));
11855                return PackageManager.INSTALL_SUCCEEDED;
11856            }
11857
11858            if (temp) {
11859                createCopyFile();
11860            } else {
11861                /*
11862                 * Pre-emptively destroy the container since it's destroyed if
11863                 * copying fails due to it existing anyway.
11864                 */
11865                PackageHelper.destroySdDir(cid);
11866            }
11867
11868            final String newMountPath = imcs.copyPackageToContainer(
11869                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11870                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11871
11872            if (newMountPath != null) {
11873                setMountPath(newMountPath);
11874                return PackageManager.INSTALL_SUCCEEDED;
11875            } else {
11876                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11877            }
11878        }
11879
11880        @Override
11881        String getCodePath() {
11882            return packagePath;
11883        }
11884
11885        @Override
11886        String getResourcePath() {
11887            return resourcePath;
11888        }
11889
11890        int doPreInstall(int status) {
11891            if (status != PackageManager.INSTALL_SUCCEEDED) {
11892                // Destroy container
11893                PackageHelper.destroySdDir(cid);
11894            } else {
11895                boolean mounted = PackageHelper.isContainerMounted(cid);
11896                if (!mounted) {
11897                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11898                            Process.SYSTEM_UID);
11899                    if (newMountPath != null) {
11900                        setMountPath(newMountPath);
11901                    } else {
11902                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11903                    }
11904                }
11905            }
11906            return status;
11907        }
11908
11909        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11910            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11911            String newMountPath = null;
11912            if (PackageHelper.isContainerMounted(cid)) {
11913                // Unmount the container
11914                if (!PackageHelper.unMountSdDir(cid)) {
11915                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11916                    return false;
11917                }
11918            }
11919            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11920                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11921                        " which might be stale. Will try to clean up.");
11922                // Clean up the stale container and proceed to recreate.
11923                if (!PackageHelper.destroySdDir(newCacheId)) {
11924                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11925                    return false;
11926                }
11927                // Successfully cleaned up stale container. Try to rename again.
11928                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11929                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11930                            + " inspite of cleaning it up.");
11931                    return false;
11932                }
11933            }
11934            if (!PackageHelper.isContainerMounted(newCacheId)) {
11935                Slog.w(TAG, "Mounting container " + newCacheId);
11936                newMountPath = PackageHelper.mountSdDir(newCacheId,
11937                        getEncryptKey(), Process.SYSTEM_UID);
11938            } else {
11939                newMountPath = PackageHelper.getSdDir(newCacheId);
11940            }
11941            if (newMountPath == null) {
11942                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11943                return false;
11944            }
11945            Log.i(TAG, "Succesfully renamed " + cid +
11946                    " to " + newCacheId +
11947                    " at new path: " + newMountPath);
11948            cid = newCacheId;
11949
11950            final File beforeCodeFile = new File(packagePath);
11951            setMountPath(newMountPath);
11952            final File afterCodeFile = new File(packagePath);
11953
11954            // Reflect the rename in scanned details
11955            pkg.codePath = afterCodeFile.getAbsolutePath();
11956            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11957                    pkg.baseCodePath);
11958            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11959                    pkg.splitCodePaths);
11960
11961            // Reflect the rename in app info
11962            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11963            pkg.applicationInfo.setCodePath(pkg.codePath);
11964            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11965            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11966            pkg.applicationInfo.setResourcePath(pkg.codePath);
11967            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11968            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11969
11970            return true;
11971        }
11972
11973        private void setMountPath(String mountPath) {
11974            final File mountFile = new File(mountPath);
11975
11976            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11977            if (monolithicFile.exists()) {
11978                packagePath = monolithicFile.getAbsolutePath();
11979                if (isFwdLocked()) {
11980                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11981                } else {
11982                    resourcePath = packagePath;
11983                }
11984            } else {
11985                packagePath = mountFile.getAbsolutePath();
11986                resourcePath = packagePath;
11987            }
11988        }
11989
11990        int doPostInstall(int status, int uid) {
11991            if (status != PackageManager.INSTALL_SUCCEEDED) {
11992                cleanUp();
11993            } else {
11994                final int groupOwner;
11995                final String protectedFile;
11996                if (isFwdLocked()) {
11997                    groupOwner = UserHandle.getSharedAppGid(uid);
11998                    protectedFile = RES_FILE_NAME;
11999                } else {
12000                    groupOwner = -1;
12001                    protectedFile = null;
12002                }
12003
12004                if (uid < Process.FIRST_APPLICATION_UID
12005                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12006                    Slog.e(TAG, "Failed to finalize " + cid);
12007                    PackageHelper.destroySdDir(cid);
12008                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12009                }
12010
12011                boolean mounted = PackageHelper.isContainerMounted(cid);
12012                if (!mounted) {
12013                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12014                }
12015            }
12016            return status;
12017        }
12018
12019        private void cleanUp() {
12020            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12021
12022            // Destroy secure container
12023            PackageHelper.destroySdDir(cid);
12024        }
12025
12026        private List<String> getAllCodePaths() {
12027            final File codeFile = new File(getCodePath());
12028            if (codeFile != null && codeFile.exists()) {
12029                try {
12030                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12031                    return pkg.getAllCodePaths();
12032                } catch (PackageParserException e) {
12033                    // Ignored; we tried our best
12034                }
12035            }
12036            return Collections.EMPTY_LIST;
12037        }
12038
12039        void cleanUpResourcesLI() {
12040            // Enumerate all code paths before deleting
12041            cleanUpResourcesLI(getAllCodePaths());
12042        }
12043
12044        private void cleanUpResourcesLI(List<String> allCodePaths) {
12045            cleanUp();
12046            removeDexFiles(allCodePaths, instructionSets);
12047        }
12048
12049        String getPackageName() {
12050            return getAsecPackageName(cid);
12051        }
12052
12053        boolean doPostDeleteLI(boolean delete) {
12054            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12055            final List<String> allCodePaths = getAllCodePaths();
12056            boolean mounted = PackageHelper.isContainerMounted(cid);
12057            if (mounted) {
12058                // Unmount first
12059                if (PackageHelper.unMountSdDir(cid)) {
12060                    mounted = false;
12061                }
12062            }
12063            if (!mounted && delete) {
12064                cleanUpResourcesLI(allCodePaths);
12065            }
12066            return !mounted;
12067        }
12068
12069        @Override
12070        int doPreCopy() {
12071            if (isFwdLocked()) {
12072                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12073                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12074                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12075                }
12076            }
12077
12078            return PackageManager.INSTALL_SUCCEEDED;
12079        }
12080
12081        @Override
12082        int doPostCopy(int uid) {
12083            if (isFwdLocked()) {
12084                if (uid < Process.FIRST_APPLICATION_UID
12085                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12086                                RES_FILE_NAME)) {
12087                    Slog.e(TAG, "Failed to finalize " + cid);
12088                    PackageHelper.destroySdDir(cid);
12089                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12090                }
12091            }
12092
12093            return PackageManager.INSTALL_SUCCEEDED;
12094        }
12095    }
12096
12097    /**
12098     * Logic to handle movement of existing installed applications.
12099     */
12100    class MoveInstallArgs extends InstallArgs {
12101        private File codeFile;
12102        private File resourceFile;
12103
12104        /** New install */
12105        MoveInstallArgs(InstallParams params) {
12106            super(params.origin, params.move, params.observer, params.installFlags,
12107                    params.installerPackageName, params.volumeUuid,
12108                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12109                    params.grantedRuntimePermissions,
12110                    params.traceMethod, params.traceCookie);
12111        }
12112
12113        int copyApk(IMediaContainerService imcs, boolean temp) {
12114            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12115                    + move.fromUuid + " to " + move.toUuid);
12116            synchronized (mInstaller) {
12117                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12118                        move.dataAppName, move.appId, move.seinfo) != 0) {
12119                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12120                }
12121            }
12122
12123            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12124            resourceFile = codeFile;
12125            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12126
12127            return PackageManager.INSTALL_SUCCEEDED;
12128        }
12129
12130        int doPreInstall(int status) {
12131            if (status != PackageManager.INSTALL_SUCCEEDED) {
12132                cleanUp(move.toUuid);
12133            }
12134            return status;
12135        }
12136
12137        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12138            if (status != PackageManager.INSTALL_SUCCEEDED) {
12139                cleanUp(move.toUuid);
12140                return false;
12141            }
12142
12143            // Reflect the move in app info
12144            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12145            pkg.applicationInfo.setCodePath(pkg.codePath);
12146            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12147            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12148            pkg.applicationInfo.setResourcePath(pkg.codePath);
12149            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12150            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12151
12152            return true;
12153        }
12154
12155        int doPostInstall(int status, int uid) {
12156            if (status == PackageManager.INSTALL_SUCCEEDED) {
12157                cleanUp(move.fromUuid);
12158            } else {
12159                cleanUp(move.toUuid);
12160            }
12161            return status;
12162        }
12163
12164        @Override
12165        String getCodePath() {
12166            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12167        }
12168
12169        @Override
12170        String getResourcePath() {
12171            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12172        }
12173
12174        private boolean cleanUp(String volumeUuid) {
12175            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12176                    move.dataAppName);
12177            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12178            synchronized (mInstallLock) {
12179                // Clean up both app data and code
12180                removeDataDirsLI(volumeUuid, move.packageName);
12181                if (codeFile.isDirectory()) {
12182                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12183                } else {
12184                    codeFile.delete();
12185                }
12186            }
12187            return true;
12188        }
12189
12190        void cleanUpResourcesLI() {
12191            throw new UnsupportedOperationException();
12192        }
12193
12194        boolean doPostDeleteLI(boolean delete) {
12195            throw new UnsupportedOperationException();
12196        }
12197    }
12198
12199    static String getAsecPackageName(String packageCid) {
12200        int idx = packageCid.lastIndexOf("-");
12201        if (idx == -1) {
12202            return packageCid;
12203        }
12204        return packageCid.substring(0, idx);
12205    }
12206
12207    // Utility method used to create code paths based on package name and available index.
12208    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12209        String idxStr = "";
12210        int idx = 1;
12211        // Fall back to default value of idx=1 if prefix is not
12212        // part of oldCodePath
12213        if (oldCodePath != null) {
12214            String subStr = oldCodePath;
12215            // Drop the suffix right away
12216            if (suffix != null && subStr.endsWith(suffix)) {
12217                subStr = subStr.substring(0, subStr.length() - suffix.length());
12218            }
12219            // If oldCodePath already contains prefix find out the
12220            // ending index to either increment or decrement.
12221            int sidx = subStr.lastIndexOf(prefix);
12222            if (sidx != -1) {
12223                subStr = subStr.substring(sidx + prefix.length());
12224                if (subStr != null) {
12225                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12226                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12227                    }
12228                    try {
12229                        idx = Integer.parseInt(subStr);
12230                        if (idx <= 1) {
12231                            idx++;
12232                        } else {
12233                            idx--;
12234                        }
12235                    } catch(NumberFormatException e) {
12236                    }
12237                }
12238            }
12239        }
12240        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12241        return prefix + idxStr;
12242    }
12243
12244    private File getNextCodePath(File targetDir, String packageName) {
12245        int suffix = 1;
12246        File result;
12247        do {
12248            result = new File(targetDir, packageName + "-" + suffix);
12249            suffix++;
12250        } while (result.exists());
12251        return result;
12252    }
12253
12254    // Utility method that returns the relative package path with respect
12255    // to the installation directory. Like say for /data/data/com.test-1.apk
12256    // string com.test-1 is returned.
12257    static String deriveCodePathName(String codePath) {
12258        if (codePath == null) {
12259            return null;
12260        }
12261        final File codeFile = new File(codePath);
12262        final String name = codeFile.getName();
12263        if (codeFile.isDirectory()) {
12264            return name;
12265        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12266            final int lastDot = name.lastIndexOf('.');
12267            return name.substring(0, lastDot);
12268        } else {
12269            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12270            return null;
12271        }
12272    }
12273
12274    static class PackageInstalledInfo {
12275        String name;
12276        int uid;
12277        // The set of users that originally had this package installed.
12278        int[] origUsers;
12279        // The set of users that now have this package installed.
12280        int[] newUsers;
12281        PackageParser.Package pkg;
12282        int returnCode;
12283        String returnMsg;
12284        PackageRemovedInfo removedInfo;
12285
12286        public void setError(int code, String msg) {
12287            returnCode = code;
12288            returnMsg = msg;
12289            Slog.w(TAG, msg);
12290        }
12291
12292        public void setError(String msg, PackageParserException e) {
12293            returnCode = e.error;
12294            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12295            Slog.w(TAG, msg, e);
12296        }
12297
12298        public void setError(String msg, PackageManagerException e) {
12299            returnCode = e.error;
12300            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12301            Slog.w(TAG, msg, e);
12302        }
12303
12304        // In some error cases we want to convey more info back to the observer
12305        String origPackage;
12306        String origPermission;
12307    }
12308
12309    /*
12310     * Install a non-existing package.
12311     */
12312    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12313            UserHandle user, String installerPackageName, String volumeUuid,
12314            PackageInstalledInfo res) {
12315        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12316
12317        // Remember this for later, in case we need to rollback this install
12318        String pkgName = pkg.packageName;
12319
12320        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12321        // TODO: b/23350563
12322        final boolean dataDirExists = Environment
12323                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12324
12325        synchronized(mPackages) {
12326            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12327                // A package with the same name is already installed, though
12328                // it has been renamed to an older name.  The package we
12329                // are trying to install should be installed as an update to
12330                // the existing one, but that has not been requested, so bail.
12331                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12332                        + " without first uninstalling package running as "
12333                        + mSettings.mRenamedPackages.get(pkgName));
12334                return;
12335            }
12336            if (mPackages.containsKey(pkgName)) {
12337                // Don't allow installation over an existing package with the same name.
12338                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12339                        + " without first uninstalling.");
12340                return;
12341            }
12342        }
12343
12344        try {
12345            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12346                    System.currentTimeMillis(), user);
12347
12348            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12349            // delete the partially installed application. the data directory will have to be
12350            // restored if it was already existing
12351            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12352                // remove package from internal structures.  Note that we want deletePackageX to
12353                // delete the package data and cache directories that it created in
12354                // scanPackageLocked, unless those directories existed before we even tried to
12355                // install.
12356                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12357                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12358                                res.removedInfo, true);
12359            }
12360
12361        } catch (PackageManagerException e) {
12362            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12363        }
12364
12365        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12366    }
12367
12368    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12369        // Can't rotate keys during boot or if sharedUser.
12370        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12371                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12372            return false;
12373        }
12374        // app is using upgradeKeySets; make sure all are valid
12375        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12376        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12377        for (int i = 0; i < upgradeKeySets.length; i++) {
12378            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12379                Slog.wtf(TAG, "Package "
12380                         + (oldPs.name != null ? oldPs.name : "<null>")
12381                         + " contains upgrade-key-set reference to unknown key-set: "
12382                         + upgradeKeySets[i]
12383                         + " reverting to signatures check.");
12384                return false;
12385            }
12386        }
12387        return true;
12388    }
12389
12390    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12391        // Upgrade keysets are being used.  Determine if new package has a superset of the
12392        // required keys.
12393        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12394        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12395        for (int i = 0; i < upgradeKeySets.length; i++) {
12396            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12397            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12398                return true;
12399            }
12400        }
12401        return false;
12402    }
12403
12404    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12405            UserHandle user, String installerPackageName, String volumeUuid,
12406            PackageInstalledInfo res) {
12407        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12408
12409        final PackageParser.Package oldPackage;
12410        final String pkgName = pkg.packageName;
12411        final int[] allUsers;
12412        final boolean[] perUserInstalled;
12413
12414        // First find the old package info and check signatures
12415        synchronized(mPackages) {
12416            oldPackage = mPackages.get(pkgName);
12417            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12418            if (isEphemeral && !oldIsEphemeral) {
12419                // can't downgrade from full to ephemeral
12420                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12421                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12422                return;
12423            }
12424            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12425            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12426            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12427                if(!checkUpgradeKeySetLP(ps, pkg)) {
12428                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12429                            "New package not signed by keys specified by upgrade-keysets: "
12430                            + pkgName);
12431                    return;
12432                }
12433            } else {
12434                // default to original signature matching
12435                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12436                    != PackageManager.SIGNATURE_MATCH) {
12437                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12438                            "New package has a different signature: " + pkgName);
12439                    return;
12440                }
12441            }
12442
12443            // In case of rollback, remember per-user/profile install state
12444            allUsers = sUserManager.getUserIds();
12445            perUserInstalled = new boolean[allUsers.length];
12446            for (int i = 0; i < allUsers.length; i++) {
12447                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12448            }
12449        }
12450
12451        boolean sysPkg = (isSystemApp(oldPackage));
12452        if (sysPkg) {
12453            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12454                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12455        } else {
12456            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12457                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12458        }
12459    }
12460
12461    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12462            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12463            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12464            String volumeUuid, PackageInstalledInfo res) {
12465        String pkgName = deletedPackage.packageName;
12466        boolean deletedPkg = true;
12467        boolean updatedSettings = false;
12468
12469        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12470                + deletedPackage);
12471        long origUpdateTime;
12472        if (pkg.mExtras != null) {
12473            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12474        } else {
12475            origUpdateTime = 0;
12476        }
12477
12478        // First delete the existing package while retaining the data directory
12479        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12480                res.removedInfo, true)) {
12481            // If the existing package wasn't successfully deleted
12482            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12483            deletedPkg = false;
12484        } else {
12485            // Successfully deleted the old package; proceed with replace.
12486
12487            // If deleted package lived in a container, give users a chance to
12488            // relinquish resources before killing.
12489            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12490                if (DEBUG_INSTALL) {
12491                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12492                }
12493                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12494                final ArrayList<String> pkgList = new ArrayList<String>(1);
12495                pkgList.add(deletedPackage.applicationInfo.packageName);
12496                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12497            }
12498
12499            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12500            try {
12501                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12502                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12503                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12504                        perUserInstalled, res, user);
12505                updatedSettings = true;
12506            } catch (PackageManagerException e) {
12507                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12508            }
12509        }
12510
12511        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12512            // remove package from internal structures.  Note that we want deletePackageX to
12513            // delete the package data and cache directories that it created in
12514            // scanPackageLocked, unless those directories existed before we even tried to
12515            // install.
12516            if(updatedSettings) {
12517                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12518                deletePackageLI(
12519                        pkgName, null, true, allUsers, perUserInstalled,
12520                        PackageManager.DELETE_KEEP_DATA,
12521                                res.removedInfo, true);
12522            }
12523            // Since we failed to install the new package we need to restore the old
12524            // package that we deleted.
12525            if (deletedPkg) {
12526                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12527                File restoreFile = new File(deletedPackage.codePath);
12528                // Parse old package
12529                boolean oldExternal = isExternal(deletedPackage);
12530                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12531                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12532                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12533                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12534                try {
12535                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12536                            null);
12537                } catch (PackageManagerException e) {
12538                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12539                            + e.getMessage());
12540                    return;
12541                }
12542                // Restore of old package succeeded. Update permissions.
12543                // writer
12544                synchronized (mPackages) {
12545                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12546                            UPDATE_PERMISSIONS_ALL);
12547                    // can downgrade to reader
12548                    mSettings.writeLPr();
12549                }
12550                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12551            }
12552        }
12553    }
12554
12555    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12556            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12557            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12558            String volumeUuid, PackageInstalledInfo res) {
12559        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12560                + ", old=" + deletedPackage);
12561        boolean disabledSystem = false;
12562        boolean updatedSettings = false;
12563        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12564        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12565                != 0) {
12566            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12567        }
12568        String packageName = deletedPackage.packageName;
12569        if (packageName == null) {
12570            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12571                    "Attempt to delete null packageName.");
12572            return;
12573        }
12574        PackageParser.Package oldPkg;
12575        PackageSetting oldPkgSetting;
12576        // reader
12577        synchronized (mPackages) {
12578            oldPkg = mPackages.get(packageName);
12579            oldPkgSetting = mSettings.mPackages.get(packageName);
12580            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12581                    (oldPkgSetting == null)) {
12582                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12583                        "Couldn't find package " + packageName + " information");
12584                return;
12585            }
12586        }
12587
12588        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12589
12590        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12591        res.removedInfo.removedPackage = packageName;
12592        // Remove existing system package
12593        removePackageLI(oldPkgSetting, true);
12594        // writer
12595        synchronized (mPackages) {
12596            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12597            if (!disabledSystem && deletedPackage != null) {
12598                // We didn't need to disable the .apk as a current system package,
12599                // which means we are replacing another update that is already
12600                // installed.  We need to make sure to delete the older one's .apk.
12601                res.removedInfo.args = createInstallArgsForExisting(0,
12602                        deletedPackage.applicationInfo.getCodePath(),
12603                        deletedPackage.applicationInfo.getResourcePath(),
12604                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12605            } else {
12606                res.removedInfo.args = null;
12607            }
12608        }
12609
12610        // Successfully disabled the old package. Now proceed with re-installation
12611        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12612
12613        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12614        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12615
12616        PackageParser.Package newPackage = null;
12617        try {
12618            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12619            if (newPackage.mExtras != null) {
12620                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12621                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12622                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12623
12624                // is the update attempting to change shared user? that isn't going to work...
12625                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12626                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12627                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12628                            + " to " + newPkgSetting.sharedUser);
12629                    updatedSettings = true;
12630                }
12631            }
12632
12633            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12634                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12635                        perUserInstalled, res, user);
12636                updatedSettings = true;
12637            }
12638
12639        } catch (PackageManagerException e) {
12640            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12641        }
12642
12643        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12644            // Re installation failed. Restore old information
12645            // Remove new pkg information
12646            if (newPackage != null) {
12647                removeInstalledPackageLI(newPackage, true);
12648            }
12649            // Add back the old system package
12650            try {
12651                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12652            } catch (PackageManagerException e) {
12653                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12654            }
12655            // Restore the old system information in Settings
12656            synchronized (mPackages) {
12657                if (disabledSystem) {
12658                    mSettings.enableSystemPackageLPw(packageName);
12659                }
12660                if (updatedSettings) {
12661                    mSettings.setInstallerPackageName(packageName,
12662                            oldPkgSetting.installerPackageName);
12663                }
12664                mSettings.writeLPr();
12665            }
12666        }
12667    }
12668
12669    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12670        // Collect all used permissions in the UID
12671        ArraySet<String> usedPermissions = new ArraySet<>();
12672        final int packageCount = su.packages.size();
12673        for (int i = 0; i < packageCount; i++) {
12674            PackageSetting ps = su.packages.valueAt(i);
12675            if (ps.pkg == null) {
12676                continue;
12677            }
12678            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12679            for (int j = 0; j < requestedPermCount; j++) {
12680                String permission = ps.pkg.requestedPermissions.get(j);
12681                BasePermission bp = mSettings.mPermissions.get(permission);
12682                if (bp != null) {
12683                    usedPermissions.add(permission);
12684                }
12685            }
12686        }
12687
12688        PermissionsState permissionsState = su.getPermissionsState();
12689        // Prune install permissions
12690        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12691        final int installPermCount = installPermStates.size();
12692        for (int i = installPermCount - 1; i >= 0;  i--) {
12693            PermissionState permissionState = installPermStates.get(i);
12694            if (!usedPermissions.contains(permissionState.getName())) {
12695                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12696                if (bp != null) {
12697                    permissionsState.revokeInstallPermission(bp);
12698                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12699                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12700                }
12701            }
12702        }
12703
12704        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12705
12706        // Prune runtime permissions
12707        for (int userId : allUserIds) {
12708            List<PermissionState> runtimePermStates = permissionsState
12709                    .getRuntimePermissionStates(userId);
12710            final int runtimePermCount = runtimePermStates.size();
12711            for (int i = runtimePermCount - 1; i >= 0; i--) {
12712                PermissionState permissionState = runtimePermStates.get(i);
12713                if (!usedPermissions.contains(permissionState.getName())) {
12714                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12715                    if (bp != null) {
12716                        permissionsState.revokeRuntimePermission(bp, userId);
12717                        permissionsState.updatePermissionFlags(bp, userId,
12718                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12719                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12720                                runtimePermissionChangedUserIds, userId);
12721                    }
12722                }
12723            }
12724        }
12725
12726        return runtimePermissionChangedUserIds;
12727    }
12728
12729    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12730            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12731            UserHandle user) {
12732        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12733
12734        String pkgName = newPackage.packageName;
12735        synchronized (mPackages) {
12736            //write settings. the installStatus will be incomplete at this stage.
12737            //note that the new package setting would have already been
12738            //added to mPackages. It hasn't been persisted yet.
12739            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12740            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12741            mSettings.writeLPr();
12742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12743        }
12744
12745        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12746        synchronized (mPackages) {
12747            updatePermissionsLPw(newPackage.packageName, newPackage,
12748                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12749                            ? UPDATE_PERMISSIONS_ALL : 0));
12750            // For system-bundled packages, we assume that installing an upgraded version
12751            // of the package implies that the user actually wants to run that new code,
12752            // so we enable the package.
12753            PackageSetting ps = mSettings.mPackages.get(pkgName);
12754            if (ps != null) {
12755                if (isSystemApp(newPackage)) {
12756                    // NB: implicit assumption that system package upgrades apply to all users
12757                    if (DEBUG_INSTALL) {
12758                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12759                    }
12760                    if (res.origUsers != null) {
12761                        for (int userHandle : res.origUsers) {
12762                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12763                                    userHandle, installerPackageName);
12764                        }
12765                    }
12766                    // Also convey the prior install/uninstall state
12767                    if (allUsers != null && perUserInstalled != null) {
12768                        for (int i = 0; i < allUsers.length; i++) {
12769                            if (DEBUG_INSTALL) {
12770                                Slog.d(TAG, "    user " + allUsers[i]
12771                                        + " => " + perUserInstalled[i]);
12772                            }
12773                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12774                        }
12775                        // these install state changes will be persisted in the
12776                        // upcoming call to mSettings.writeLPr().
12777                    }
12778                }
12779                // It's implied that when a user requests installation, they want the app to be
12780                // installed and enabled.
12781                int userId = user.getIdentifier();
12782                if (userId != UserHandle.USER_ALL) {
12783                    ps.setInstalled(true, userId);
12784                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12785                }
12786            }
12787            res.name = pkgName;
12788            res.uid = newPackage.applicationInfo.uid;
12789            res.pkg = newPackage;
12790            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12791            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12792            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12793            //to update install status
12794            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12795            mSettings.writeLPr();
12796            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12797        }
12798
12799        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12800    }
12801
12802    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12803        try {
12804            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12805            installPackageLI(args, res);
12806        } finally {
12807            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12808        }
12809    }
12810
12811    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12812        final int installFlags = args.installFlags;
12813        final String installerPackageName = args.installerPackageName;
12814        final String volumeUuid = args.volumeUuid;
12815        final File tmpPackageFile = new File(args.getCodePath());
12816        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12817        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12818                || (args.volumeUuid != null));
12819        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12820        boolean replace = false;
12821        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12822        if (args.move != null) {
12823            // moving a complete application; perfom an initial scan on the new install location
12824            scanFlags |= SCAN_INITIAL;
12825        }
12826        // Result object to be returned
12827        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12828
12829        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12830
12831        // Sanity check
12832        if (ephemeral && (forwardLocked || onExternal)) {
12833            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12834                    + " external=" + onExternal);
12835            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12836            return;
12837        }
12838
12839        // Retrieve PackageSettings and parse package
12840        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12841                | PackageParser.PARSE_ENFORCE_CODE
12842                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12843                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12844                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12845        PackageParser pp = new PackageParser();
12846        pp.setSeparateProcesses(mSeparateProcesses);
12847        pp.setDisplayMetrics(mMetrics);
12848
12849        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12850        final PackageParser.Package pkg;
12851        try {
12852            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12853        } catch (PackageParserException e) {
12854            res.setError("Failed parse during installPackageLI", e);
12855            return;
12856        } finally {
12857            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12858        }
12859
12860        // Mark that we have an install time CPU ABI override.
12861        pkg.cpuAbiOverride = args.abiOverride;
12862
12863        String pkgName = res.name = pkg.packageName;
12864        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12865            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12866                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12867                return;
12868            }
12869        }
12870
12871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12872        try {
12873            pp.collectCertificates(pkg, parseFlags);
12874        } catch (PackageParserException e) {
12875            res.setError("Failed collect during installPackageLI", e);
12876            return;
12877        } finally {
12878            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12879        }
12880
12881        // Get rid of all references to package scan path via parser.
12882        pp = null;
12883        String oldCodePath = null;
12884        boolean systemApp = false;
12885        synchronized (mPackages) {
12886            // Check if installing already existing package
12887            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12888                String oldName = mSettings.mRenamedPackages.get(pkgName);
12889                if (pkg.mOriginalPackages != null
12890                        && pkg.mOriginalPackages.contains(oldName)
12891                        && mPackages.containsKey(oldName)) {
12892                    // This package is derived from an original package,
12893                    // and this device has been updating from that original
12894                    // name.  We must continue using the original name, so
12895                    // rename the new package here.
12896                    pkg.setPackageName(oldName);
12897                    pkgName = pkg.packageName;
12898                    replace = true;
12899                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12900                            + oldName + " pkgName=" + pkgName);
12901                } else if (mPackages.containsKey(pkgName)) {
12902                    // This package, under its official name, already exists
12903                    // on the device; we should replace it.
12904                    replace = true;
12905                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12906                }
12907
12908                // Prevent apps opting out from runtime permissions
12909                if (replace) {
12910                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12911                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12912                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12913                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12914                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12915                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12916                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12917                                        + " doesn't support runtime permissions but the old"
12918                                        + " target SDK " + oldTargetSdk + " does.");
12919                        return;
12920                    }
12921                }
12922            }
12923
12924            PackageSetting ps = mSettings.mPackages.get(pkgName);
12925            if (ps != null) {
12926                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12927
12928                // Quick sanity check that we're signed correctly if updating;
12929                // we'll check this again later when scanning, but we want to
12930                // bail early here before tripping over redefined permissions.
12931                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12932                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12933                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12934                                + pkg.packageName + " upgrade keys do not match the "
12935                                + "previously installed version");
12936                        return;
12937                    }
12938                } else {
12939                    try {
12940                        verifySignaturesLP(ps, pkg);
12941                    } catch (PackageManagerException e) {
12942                        res.setError(e.error, e.getMessage());
12943                        return;
12944                    }
12945                }
12946
12947                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12948                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12949                    systemApp = (ps.pkg.applicationInfo.flags &
12950                            ApplicationInfo.FLAG_SYSTEM) != 0;
12951                }
12952                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12953            }
12954
12955            // Check whether the newly-scanned package wants to define an already-defined perm
12956            int N = pkg.permissions.size();
12957            for (int i = N-1; i >= 0; i--) {
12958                PackageParser.Permission perm = pkg.permissions.get(i);
12959                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12960                if (bp != null) {
12961                    // If the defining package is signed with our cert, it's okay.  This
12962                    // also includes the "updating the same package" case, of course.
12963                    // "updating same package" could also involve key-rotation.
12964                    final boolean sigsOk;
12965                    if (bp.sourcePackage.equals(pkg.packageName)
12966                            && (bp.packageSetting instanceof PackageSetting)
12967                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12968                                    scanFlags))) {
12969                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12970                    } else {
12971                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12972                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12973                    }
12974                    if (!sigsOk) {
12975                        // If the owning package is the system itself, we log but allow
12976                        // install to proceed; we fail the install on all other permission
12977                        // redefinitions.
12978                        if (!bp.sourcePackage.equals("android")) {
12979                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12980                                    + pkg.packageName + " attempting to redeclare permission "
12981                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12982                            res.origPermission = perm.info.name;
12983                            res.origPackage = bp.sourcePackage;
12984                            return;
12985                        } else {
12986                            Slog.w(TAG, "Package " + pkg.packageName
12987                                    + " attempting to redeclare system permission "
12988                                    + perm.info.name + "; ignoring new declaration");
12989                            pkg.permissions.remove(i);
12990                        }
12991                    }
12992                }
12993            }
12994
12995        }
12996
12997        if (systemApp) {
12998            if (onExternal) {
12999                // Abort update; system app can't be replaced with app on sdcard
13000                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13001                        "Cannot install updates to system apps on sdcard");
13002                return;
13003            } else if (ephemeral) {
13004                // Abort update; system app can't be replaced with an ephemeral app
13005                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13006                        "Cannot update a system app with an ephemeral app");
13007                return;
13008            }
13009        }
13010
13011        if (args.move != null) {
13012            // We did an in-place move, so dex is ready to roll
13013            scanFlags |= SCAN_NO_DEX;
13014            scanFlags |= SCAN_MOVE;
13015
13016            synchronized (mPackages) {
13017                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13018                if (ps == null) {
13019                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13020                            "Missing settings for moved package " + pkgName);
13021                }
13022
13023                // We moved the entire application as-is, so bring over the
13024                // previously derived ABI information.
13025                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13026                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13027            }
13028
13029        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13030            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13031            scanFlags |= SCAN_NO_DEX;
13032
13033            try {
13034                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13035                        true /* extract libs */);
13036            } catch (PackageManagerException pme) {
13037                Slog.e(TAG, "Error deriving application ABI", pme);
13038                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13039                return;
13040            }
13041        }
13042
13043        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13044            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13045            return;
13046        }
13047
13048        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13049
13050        if (replace) {
13051            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13052                    installerPackageName, volumeUuid, res);
13053        } else {
13054            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13055                    args.user, installerPackageName, volumeUuid, res);
13056        }
13057        synchronized (mPackages) {
13058            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13059            if (ps != null) {
13060                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13061            }
13062        }
13063    }
13064
13065    private void startIntentFilterVerifications(int userId, boolean replacing,
13066            PackageParser.Package pkg) {
13067        if (mIntentFilterVerifierComponent == null) {
13068            Slog.w(TAG, "No IntentFilter verification will not be done as "
13069                    + "there is no IntentFilterVerifier available!");
13070            return;
13071        }
13072
13073        final int verifierUid = getPackageUid(
13074                mIntentFilterVerifierComponent.getPackageName(),
13075                MATCH_DEBUG_TRIAGED_MISSING,
13076                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13077
13078        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13079        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13080        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13081        mHandler.sendMessage(msg);
13082    }
13083
13084    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13085            PackageParser.Package pkg) {
13086        int size = pkg.activities.size();
13087        if (size == 0) {
13088            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13089                    "No activity, so no need to verify any IntentFilter!");
13090            return;
13091        }
13092
13093        final boolean hasDomainURLs = hasDomainURLs(pkg);
13094        if (!hasDomainURLs) {
13095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13096                    "No domain URLs, so no need to verify any IntentFilter!");
13097            return;
13098        }
13099
13100        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13101                + " if any IntentFilter from the " + size
13102                + " Activities needs verification ...");
13103
13104        int count = 0;
13105        final String packageName = pkg.packageName;
13106
13107        synchronized (mPackages) {
13108            // If this is a new install and we see that we've already run verification for this
13109            // package, we have nothing to do: it means the state was restored from backup.
13110            if (!replacing) {
13111                IntentFilterVerificationInfo ivi =
13112                        mSettings.getIntentFilterVerificationLPr(packageName);
13113                if (ivi != null) {
13114                    if (DEBUG_DOMAIN_VERIFICATION) {
13115                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13116                                + ivi.getStatusString());
13117                    }
13118                    return;
13119                }
13120            }
13121
13122            // If any filters need to be verified, then all need to be.
13123            boolean needToVerify = false;
13124            for (PackageParser.Activity a : pkg.activities) {
13125                for (ActivityIntentInfo filter : a.intents) {
13126                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13127                        if (DEBUG_DOMAIN_VERIFICATION) {
13128                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13129                        }
13130                        needToVerify = true;
13131                        break;
13132                    }
13133                }
13134            }
13135
13136            if (needToVerify) {
13137                final int verificationId = mIntentFilterVerificationToken++;
13138                for (PackageParser.Activity a : pkg.activities) {
13139                    for (ActivityIntentInfo filter : a.intents) {
13140                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13141                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13142                                    "Verification needed for IntentFilter:" + filter.toString());
13143                            mIntentFilterVerifier.addOneIntentFilterVerification(
13144                                    verifierUid, userId, verificationId, filter, packageName);
13145                            count++;
13146                        }
13147                    }
13148                }
13149            }
13150        }
13151
13152        if (count > 0) {
13153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13154                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13155                    +  " for userId:" + userId);
13156            mIntentFilterVerifier.startVerifications(userId);
13157        } else {
13158            if (DEBUG_DOMAIN_VERIFICATION) {
13159                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13160            }
13161        }
13162    }
13163
13164    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13165        final ComponentName cn  = filter.activity.getComponentName();
13166        final String packageName = cn.getPackageName();
13167
13168        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13169                packageName);
13170        if (ivi == null) {
13171            return true;
13172        }
13173        int status = ivi.getStatus();
13174        switch (status) {
13175            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13176            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13177                return true;
13178
13179            default:
13180                // Nothing to do
13181                return false;
13182        }
13183    }
13184
13185    private static boolean isMultiArch(ApplicationInfo info) {
13186        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13187    }
13188
13189    private static boolean isExternal(PackageParser.Package pkg) {
13190        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13191    }
13192
13193    private static boolean isExternal(PackageSetting ps) {
13194        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13195    }
13196
13197    private static boolean isEphemeral(PackageParser.Package pkg) {
13198        return pkg.applicationInfo.isEphemeralApp();
13199    }
13200
13201    private static boolean isEphemeral(PackageSetting ps) {
13202        return ps.pkg != null && isEphemeral(ps.pkg);
13203    }
13204
13205    private static boolean isSystemApp(PackageParser.Package pkg) {
13206        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13207    }
13208
13209    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13210        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13211    }
13212
13213    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13214        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13215    }
13216
13217    private static boolean isSystemApp(PackageSetting ps) {
13218        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13219    }
13220
13221    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13222        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13223    }
13224
13225    private int packageFlagsToInstallFlags(PackageSetting ps) {
13226        int installFlags = 0;
13227        if (isEphemeral(ps)) {
13228            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13229        }
13230        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13231            // This existing package was an external ASEC install when we have
13232            // the external flag without a UUID
13233            installFlags |= PackageManager.INSTALL_EXTERNAL;
13234        }
13235        if (ps.isForwardLocked()) {
13236            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13237        }
13238        return installFlags;
13239    }
13240
13241    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13242        if (isExternal(pkg)) {
13243            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13244                return StorageManager.UUID_PRIMARY_PHYSICAL;
13245            } else {
13246                return pkg.volumeUuid;
13247            }
13248        } else {
13249            return StorageManager.UUID_PRIVATE_INTERNAL;
13250        }
13251    }
13252
13253    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13254        if (isExternal(pkg)) {
13255            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13256                return mSettings.getExternalVersion();
13257            } else {
13258                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13259            }
13260        } else {
13261            return mSettings.getInternalVersion();
13262        }
13263    }
13264
13265    private void deleteTempPackageFiles() {
13266        final FilenameFilter filter = new FilenameFilter() {
13267            public boolean accept(File dir, String name) {
13268                return name.startsWith("vmdl") && name.endsWith(".tmp");
13269            }
13270        };
13271        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13272            file.delete();
13273        }
13274    }
13275
13276    @Override
13277    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13278            int flags) {
13279        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13280                flags);
13281    }
13282
13283    @Override
13284    public void deletePackage(final String packageName,
13285            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13286        mContext.enforceCallingOrSelfPermission(
13287                android.Manifest.permission.DELETE_PACKAGES, null);
13288        Preconditions.checkNotNull(packageName);
13289        Preconditions.checkNotNull(observer);
13290        final int uid = Binder.getCallingUid();
13291        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13292        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13293        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13294            mContext.enforceCallingOrSelfPermission(
13295                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13296                    "deletePackage for user " + userId);
13297        }
13298
13299        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13300            try {
13301                observer.onPackageDeleted(packageName,
13302                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13303            } catch (RemoteException re) {
13304            }
13305            return;
13306        }
13307
13308        for (int currentUserId : users) {
13309            if (getBlockUninstallForUser(packageName, currentUserId)) {
13310                try {
13311                    observer.onPackageDeleted(packageName,
13312                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13313                } catch (RemoteException re) {
13314                }
13315                return;
13316            }
13317        }
13318
13319        if (DEBUG_REMOVE) {
13320            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13321        }
13322        // Queue up an async operation since the package deletion may take a little while.
13323        mHandler.post(new Runnable() {
13324            public void run() {
13325                mHandler.removeCallbacks(this);
13326                final int returnCode = deletePackageX(packageName, userId, flags);
13327                try {
13328                    observer.onPackageDeleted(packageName, returnCode, null);
13329                } catch (RemoteException e) {
13330                    Log.i(TAG, "Observer no longer exists.");
13331                } //end catch
13332            } //end run
13333        });
13334    }
13335
13336    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13337        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13338                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13339        try {
13340            if (dpm != null) {
13341                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13342                        /* callingUserOnly =*/ false);
13343                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13344                        : deviceOwnerComponentName.getPackageName();
13345                // Does the package contains the device owner?
13346                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13347                // this check is probably not needed, since DO should be registered as a device
13348                // admin on some user too. (Original bug for this: b/17657954)
13349                if (packageName.equals(deviceOwnerPackageName)) {
13350                    return true;
13351                }
13352                // Does it contain a device admin for any user?
13353                int[] users;
13354                if (userId == UserHandle.USER_ALL) {
13355                    users = sUserManager.getUserIds();
13356                } else {
13357                    users = new int[]{userId};
13358                }
13359                for (int i = 0; i < users.length; ++i) {
13360                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13361                        return true;
13362                    }
13363                }
13364            }
13365        } catch (RemoteException e) {
13366        }
13367        return false;
13368    }
13369
13370    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13371        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13372    }
13373
13374    /**
13375     *  This method is an internal method that could be get invoked either
13376     *  to delete an installed package or to clean up a failed installation.
13377     *  After deleting an installed package, a broadcast is sent to notify any
13378     *  listeners that the package has been installed. For cleaning up a failed
13379     *  installation, the broadcast is not necessary since the package's
13380     *  installation wouldn't have sent the initial broadcast either
13381     *  The key steps in deleting a package are
13382     *  deleting the package information in internal structures like mPackages,
13383     *  deleting the packages base directories through installd
13384     *  updating mSettings to reflect current status
13385     *  persisting settings for later use
13386     *  sending a broadcast if necessary
13387     */
13388    private int deletePackageX(String packageName, int userId, int flags) {
13389        final PackageRemovedInfo info = new PackageRemovedInfo();
13390        final boolean res;
13391
13392        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13393                ? UserHandle.ALL : new UserHandle(userId);
13394
13395        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13396            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13397            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13398        }
13399
13400        boolean removedForAllUsers = false;
13401        boolean systemUpdate = false;
13402
13403        PackageParser.Package uninstalledPkg;
13404
13405        // for the uninstall-updates case and restricted profiles, remember the per-
13406        // userhandle installed state
13407        int[] allUsers;
13408        boolean[] perUserInstalled;
13409        synchronized (mPackages) {
13410            uninstalledPkg = mPackages.get(packageName);
13411            PackageSetting ps = mSettings.mPackages.get(packageName);
13412            allUsers = sUserManager.getUserIds();
13413            perUserInstalled = new boolean[allUsers.length];
13414            for (int i = 0; i < allUsers.length; i++) {
13415                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13416            }
13417        }
13418
13419        synchronized (mInstallLock) {
13420            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13421            res = deletePackageLI(packageName, removeForUser,
13422                    true, allUsers, perUserInstalled,
13423                    flags | REMOVE_CHATTY, info, true);
13424            systemUpdate = info.isRemovedPackageSystemUpdate;
13425            synchronized (mPackages) {
13426                if (res) {
13427                    if (!systemUpdate && mPackages.get(packageName) == null) {
13428                        removedForAllUsers = true;
13429                    }
13430                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13431                }
13432            }
13433            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13434                    + " removedForAllUsers=" + removedForAllUsers);
13435        }
13436
13437        if (res) {
13438            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13439
13440            // If the removed package was a system update, the old system package
13441            // was re-enabled; we need to broadcast this information
13442            if (systemUpdate) {
13443                Bundle extras = new Bundle(1);
13444                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13445                        ? info.removedAppId : info.uid);
13446                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13447
13448                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13449                        extras, 0, null, null, null);
13450                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13451                        extras, 0, null, null, null);
13452                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13453                        null, 0, packageName, null, null);
13454            }
13455        }
13456        // Force a gc here.
13457        Runtime.getRuntime().gc();
13458        // Delete the resources here after sending the broadcast to let
13459        // other processes clean up before deleting resources.
13460        if (info.args != null) {
13461            synchronized (mInstallLock) {
13462                info.args.doPostDeleteLI(true);
13463            }
13464        }
13465
13466        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13467    }
13468
13469    class PackageRemovedInfo {
13470        String removedPackage;
13471        int uid = -1;
13472        int removedAppId = -1;
13473        int[] removedUsers = null;
13474        boolean isRemovedPackageSystemUpdate = false;
13475        // Clean up resources deleted packages.
13476        InstallArgs args = null;
13477
13478        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13479            Bundle extras = new Bundle(1);
13480            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13481            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13482            if (replacing) {
13483                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13484            }
13485            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13486            if (removedPackage != null) {
13487                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13488                        extras, 0, null, null, removedUsers);
13489                if (fullRemove && !replacing) {
13490                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13491                            extras, 0, null, null, removedUsers);
13492                }
13493            }
13494            if (removedAppId >= 0) {
13495                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13496                        removedUsers);
13497            }
13498        }
13499    }
13500
13501    /*
13502     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13503     * flag is not set, the data directory is removed as well.
13504     * make sure this flag is set for partially installed apps. If not its meaningless to
13505     * delete a partially installed application.
13506     */
13507    private void removePackageDataLI(PackageSetting ps,
13508            int[] allUserHandles, boolean[] perUserInstalled,
13509            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13510        String packageName = ps.name;
13511        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13512        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13513        // Retrieve object to delete permissions for shared user later on
13514        final PackageSetting deletedPs;
13515        // reader
13516        synchronized (mPackages) {
13517            deletedPs = mSettings.mPackages.get(packageName);
13518            if (outInfo != null) {
13519                outInfo.removedPackage = packageName;
13520                outInfo.removedUsers = deletedPs != null
13521                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13522                        : null;
13523            }
13524        }
13525        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13526            removeDataDirsLI(ps.volumeUuid, packageName);
13527            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13528        }
13529        // writer
13530        synchronized (mPackages) {
13531            if (deletedPs != null) {
13532                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13533                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13534                    clearDefaultBrowserIfNeeded(packageName);
13535                    if (outInfo != null) {
13536                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13537                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13538                    }
13539                    updatePermissionsLPw(deletedPs.name, null, 0);
13540                    if (deletedPs.sharedUser != null) {
13541                        // Remove permissions associated with package. Since runtime
13542                        // permissions are per user we have to kill the removed package
13543                        // or packages running under the shared user of the removed
13544                        // package if revoking the permissions requested only by the removed
13545                        // package is successful and this causes a change in gids.
13546                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13547                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13548                                    userId);
13549                            if (userIdToKill == UserHandle.USER_ALL
13550                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13551                                // If gids changed for this user, kill all affected packages.
13552                                mHandler.post(new Runnable() {
13553                                    @Override
13554                                    public void run() {
13555                                        // This has to happen with no lock held.
13556                                        killApplication(deletedPs.name, deletedPs.appId,
13557                                                KILL_APP_REASON_GIDS_CHANGED);
13558                                    }
13559                                });
13560                                break;
13561                            }
13562                        }
13563                    }
13564                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13565                }
13566                // make sure to preserve per-user disabled state if this removal was just
13567                // a downgrade of a system app to the factory package
13568                if (allUserHandles != null && perUserInstalled != null) {
13569                    if (DEBUG_REMOVE) {
13570                        Slog.d(TAG, "Propagating install state across downgrade");
13571                    }
13572                    for (int i = 0; i < allUserHandles.length; i++) {
13573                        if (DEBUG_REMOVE) {
13574                            Slog.d(TAG, "    user " + allUserHandles[i]
13575                                    + " => " + perUserInstalled[i]);
13576                        }
13577                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13578                    }
13579                }
13580            }
13581            // can downgrade to reader
13582            if (writeSettings) {
13583                // Save settings now
13584                mSettings.writeLPr();
13585            }
13586        }
13587        if (outInfo != null) {
13588            // A user ID was deleted here. Go through all users and remove it
13589            // from KeyStore.
13590            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13591        }
13592    }
13593
13594    static boolean locationIsPrivileged(File path) {
13595        try {
13596            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13597                    .getCanonicalPath();
13598            return path.getCanonicalPath().startsWith(privilegedAppDir);
13599        } catch (IOException e) {
13600            Slog.e(TAG, "Unable to access code path " + path);
13601        }
13602        return false;
13603    }
13604
13605    /*
13606     * Tries to delete system package.
13607     */
13608    private boolean deleteSystemPackageLI(PackageSetting newPs,
13609            int[] allUserHandles, boolean[] perUserInstalled,
13610            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13611        final boolean applyUserRestrictions
13612                = (allUserHandles != null) && (perUserInstalled != null);
13613        PackageSetting disabledPs = null;
13614        // Confirm if the system package has been updated
13615        // An updated system app can be deleted. This will also have to restore
13616        // the system pkg from system partition
13617        // reader
13618        synchronized (mPackages) {
13619            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13620        }
13621        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13622                + " disabledPs=" + disabledPs);
13623        if (disabledPs == null) {
13624            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13625            return false;
13626        } else if (DEBUG_REMOVE) {
13627            Slog.d(TAG, "Deleting system pkg from data partition");
13628        }
13629        if (DEBUG_REMOVE) {
13630            if (applyUserRestrictions) {
13631                Slog.d(TAG, "Remembering install states:");
13632                for (int i = 0; i < allUserHandles.length; i++) {
13633                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13634                }
13635            }
13636        }
13637        // Delete the updated package
13638        outInfo.isRemovedPackageSystemUpdate = true;
13639        if (disabledPs.versionCode < newPs.versionCode) {
13640            // Delete data for downgrades
13641            flags &= ~PackageManager.DELETE_KEEP_DATA;
13642        } else {
13643            // Preserve data by setting flag
13644            flags |= PackageManager.DELETE_KEEP_DATA;
13645        }
13646        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13647                allUserHandles, perUserInstalled, outInfo, writeSettings);
13648        if (!ret) {
13649            return false;
13650        }
13651        // writer
13652        synchronized (mPackages) {
13653            // Reinstate the old system package
13654            mSettings.enableSystemPackageLPw(newPs.name);
13655            // Remove any native libraries from the upgraded package.
13656            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13657        }
13658        // Install the system package
13659        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13660        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13661        if (locationIsPrivileged(disabledPs.codePath)) {
13662            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13663        }
13664
13665        final PackageParser.Package newPkg;
13666        try {
13667            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13668        } catch (PackageManagerException e) {
13669            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13670            return false;
13671        }
13672
13673        // writer
13674        synchronized (mPackages) {
13675            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13676
13677            // Propagate the permissions state as we do not want to drop on the floor
13678            // runtime permissions. The update permissions method below will take
13679            // care of removing obsolete permissions and grant install permissions.
13680            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13681            updatePermissionsLPw(newPkg.packageName, newPkg,
13682                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13683
13684            if (applyUserRestrictions) {
13685                if (DEBUG_REMOVE) {
13686                    Slog.d(TAG, "Propagating install state across reinstall");
13687                }
13688                for (int i = 0; i < allUserHandles.length; i++) {
13689                    if (DEBUG_REMOVE) {
13690                        Slog.d(TAG, "    user " + allUserHandles[i]
13691                                + " => " + perUserInstalled[i]);
13692                    }
13693                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13694
13695                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13696                }
13697                // Regardless of writeSettings we need to ensure that this restriction
13698                // state propagation is persisted
13699                mSettings.writeAllUsersPackageRestrictionsLPr();
13700            }
13701            // can downgrade to reader here
13702            if (writeSettings) {
13703                mSettings.writeLPr();
13704            }
13705        }
13706        return true;
13707    }
13708
13709    private boolean deleteInstalledPackageLI(PackageSetting ps,
13710            boolean deleteCodeAndResources, int flags,
13711            int[] allUserHandles, boolean[] perUserInstalled,
13712            PackageRemovedInfo outInfo, boolean writeSettings) {
13713        if (outInfo != null) {
13714            outInfo.uid = ps.appId;
13715        }
13716
13717        // Delete package data from internal structures and also remove data if flag is set
13718        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13719
13720        // Delete application code and resources
13721        if (deleteCodeAndResources && (outInfo != null)) {
13722            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13723                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13724            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13725        }
13726        return true;
13727    }
13728
13729    @Override
13730    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13731            int userId) {
13732        mContext.enforceCallingOrSelfPermission(
13733                android.Manifest.permission.DELETE_PACKAGES, null);
13734        synchronized (mPackages) {
13735            PackageSetting ps = mSettings.mPackages.get(packageName);
13736            if (ps == null) {
13737                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13738                return false;
13739            }
13740            if (!ps.getInstalled(userId)) {
13741                // Can't block uninstall for an app that is not installed or enabled.
13742                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13743                return false;
13744            }
13745            ps.setBlockUninstall(blockUninstall, userId);
13746            mSettings.writePackageRestrictionsLPr(userId);
13747        }
13748        return true;
13749    }
13750
13751    @Override
13752    public boolean getBlockUninstallForUser(String packageName, int userId) {
13753        synchronized (mPackages) {
13754            PackageSetting ps = mSettings.mPackages.get(packageName);
13755            if (ps == null) {
13756                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13757                return false;
13758            }
13759            return ps.getBlockUninstall(userId);
13760        }
13761    }
13762
13763    @Override
13764    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13765        int callingUid = Binder.getCallingUid();
13766        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13767            throw new SecurityException(
13768                    "setRequiredForSystemUser can only be run by the system or root");
13769        }
13770        synchronized (mPackages) {
13771            PackageSetting ps = mSettings.mPackages.get(packageName);
13772            if (ps == null) {
13773                Log.w(TAG, "Package doesn't exist: " + packageName);
13774                return false;
13775            }
13776            if (systemUserApp) {
13777                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13778            } else {
13779                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13780            }
13781            mSettings.writeLPr();
13782        }
13783        return true;
13784    }
13785
13786    /*
13787     * This method handles package deletion in general
13788     */
13789    private boolean deletePackageLI(String packageName, UserHandle user,
13790            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13791            int flags, PackageRemovedInfo outInfo,
13792            boolean writeSettings) {
13793        if (packageName == null) {
13794            Slog.w(TAG, "Attempt to delete null packageName.");
13795            return false;
13796        }
13797        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13798        PackageSetting ps;
13799        boolean dataOnly = false;
13800        int removeUser = -1;
13801        int appId = -1;
13802        synchronized (mPackages) {
13803            ps = mSettings.mPackages.get(packageName);
13804            if (ps == null) {
13805                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13806                return false;
13807            }
13808            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13809                    && user.getIdentifier() != UserHandle.USER_ALL) {
13810                // The caller is asking that the package only be deleted for a single
13811                // user.  To do this, we just mark its uninstalled state and delete
13812                // its data.  If this is a system app, we only allow this to happen if
13813                // they have set the special DELETE_SYSTEM_APP which requests different
13814                // semantics than normal for uninstalling system apps.
13815                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13816                final int userId = user.getIdentifier();
13817                ps.setUserState(userId,
13818                        COMPONENT_ENABLED_STATE_DEFAULT,
13819                        false, //installed
13820                        true,  //stopped
13821                        true,  //notLaunched
13822                        false, //hidden
13823                        false, //suspended
13824                        null, null, null,
13825                        false, // blockUninstall
13826                        ps.readUserState(userId).domainVerificationStatus, 0);
13827                if (!isSystemApp(ps)) {
13828                    // Do not uninstall the APK if an app should be cached
13829                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13830                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13831                        // Other user still have this package installed, so all
13832                        // we need to do is clear this user's data and save that
13833                        // it is uninstalled.
13834                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13835                        removeUser = user.getIdentifier();
13836                        appId = ps.appId;
13837                        scheduleWritePackageRestrictionsLocked(removeUser);
13838                    } else {
13839                        // We need to set it back to 'installed' so the uninstall
13840                        // broadcasts will be sent correctly.
13841                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13842                        ps.setInstalled(true, user.getIdentifier());
13843                    }
13844                } else {
13845                    // This is a system app, so we assume that the
13846                    // other users still have this package installed, so all
13847                    // we need to do is clear this user's data and save that
13848                    // it is uninstalled.
13849                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13850                    removeUser = user.getIdentifier();
13851                    appId = ps.appId;
13852                    scheduleWritePackageRestrictionsLocked(removeUser);
13853                }
13854            }
13855        }
13856
13857        if (removeUser >= 0) {
13858            // From above, we determined that we are deleting this only
13859            // for a single user.  Continue the work here.
13860            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13861            if (outInfo != null) {
13862                outInfo.removedPackage = packageName;
13863                outInfo.removedAppId = appId;
13864                outInfo.removedUsers = new int[] {removeUser};
13865            }
13866            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13867            removeKeystoreDataIfNeeded(removeUser, appId);
13868            schedulePackageCleaning(packageName, removeUser, false);
13869            synchronized (mPackages) {
13870                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13871                    scheduleWritePackageRestrictionsLocked(removeUser);
13872                }
13873                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13874            }
13875            return true;
13876        }
13877
13878        if (dataOnly) {
13879            // Delete application data first
13880            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13881            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13882            return true;
13883        }
13884
13885        boolean ret = false;
13886        if (isSystemApp(ps)) {
13887            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13888            // When an updated system application is deleted we delete the existing resources as well and
13889            // fall back to existing code in system partition
13890            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13891                    flags, outInfo, writeSettings);
13892        } else {
13893            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13894            // Kill application pre-emptively especially for apps on sd.
13895            killApplication(packageName, ps.appId, "uninstall pkg");
13896            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13897                    allUserHandles, perUserInstalled,
13898                    outInfo, writeSettings);
13899        }
13900
13901        return ret;
13902    }
13903
13904    private final static class ClearStorageConnection implements ServiceConnection {
13905        IMediaContainerService mContainerService;
13906
13907        @Override
13908        public void onServiceConnected(ComponentName name, IBinder service) {
13909            synchronized (this) {
13910                mContainerService = IMediaContainerService.Stub.asInterface(service);
13911                notifyAll();
13912            }
13913        }
13914
13915        @Override
13916        public void onServiceDisconnected(ComponentName name) {
13917        }
13918    }
13919
13920    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13921        final boolean mounted;
13922        if (Environment.isExternalStorageEmulated()) {
13923            mounted = true;
13924        } else {
13925            final String status = Environment.getExternalStorageState();
13926
13927            mounted = status.equals(Environment.MEDIA_MOUNTED)
13928                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13929        }
13930
13931        if (!mounted) {
13932            return;
13933        }
13934
13935        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13936        int[] users;
13937        if (userId == UserHandle.USER_ALL) {
13938            users = sUserManager.getUserIds();
13939        } else {
13940            users = new int[] { userId };
13941        }
13942        final ClearStorageConnection conn = new ClearStorageConnection();
13943        if (mContext.bindServiceAsUser(
13944                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13945            try {
13946                for (int curUser : users) {
13947                    long timeout = SystemClock.uptimeMillis() + 5000;
13948                    synchronized (conn) {
13949                        long now = SystemClock.uptimeMillis();
13950                        while (conn.mContainerService == null && now < timeout) {
13951                            try {
13952                                conn.wait(timeout - now);
13953                            } catch (InterruptedException e) {
13954                            }
13955                        }
13956                    }
13957                    if (conn.mContainerService == null) {
13958                        return;
13959                    }
13960
13961                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13962                    clearDirectory(conn.mContainerService,
13963                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13964                    if (allData) {
13965                        clearDirectory(conn.mContainerService,
13966                                userEnv.buildExternalStorageAppDataDirs(packageName));
13967                        clearDirectory(conn.mContainerService,
13968                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13969                    }
13970                }
13971            } finally {
13972                mContext.unbindService(conn);
13973            }
13974        }
13975    }
13976
13977    @Override
13978    public void clearApplicationUserData(final String packageName,
13979            final IPackageDataObserver observer, final int userId) {
13980        mContext.enforceCallingOrSelfPermission(
13981                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13982        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13983        // Queue up an async operation since the package deletion may take a little while.
13984        mHandler.post(new Runnable() {
13985            public void run() {
13986                mHandler.removeCallbacks(this);
13987                final boolean succeeded;
13988                synchronized (mInstallLock) {
13989                    succeeded = clearApplicationUserDataLI(packageName, userId);
13990                }
13991                clearExternalStorageDataSync(packageName, userId, true);
13992                if (succeeded) {
13993                    // invoke DeviceStorageMonitor's update method to clear any notifications
13994                    DeviceStorageMonitorInternal
13995                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13996                    if (dsm != null) {
13997                        dsm.checkMemory();
13998                    }
13999                }
14000                if(observer != null) {
14001                    try {
14002                        observer.onRemoveCompleted(packageName, succeeded);
14003                    } catch (RemoteException e) {
14004                        Log.i(TAG, "Observer no longer exists.");
14005                    }
14006                } //end if observer
14007            } //end run
14008        });
14009    }
14010
14011    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14012        if (packageName == null) {
14013            Slog.w(TAG, "Attempt to delete null packageName.");
14014            return false;
14015        }
14016
14017        // Try finding details about the requested package
14018        PackageParser.Package pkg;
14019        synchronized (mPackages) {
14020            pkg = mPackages.get(packageName);
14021            if (pkg == null) {
14022                final PackageSetting ps = mSettings.mPackages.get(packageName);
14023                if (ps != null) {
14024                    pkg = ps.pkg;
14025                }
14026            }
14027
14028            if (pkg == null) {
14029                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14030                return false;
14031            }
14032
14033            PackageSetting ps = (PackageSetting) pkg.mExtras;
14034            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14035        }
14036
14037        // Always delete data directories for package, even if we found no other
14038        // record of app. This helps users recover from UID mismatches without
14039        // resorting to a full data wipe.
14040        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14041        if (retCode < 0) {
14042            Slog.w(TAG, "Couldn't remove cache files for package " + packageName);
14043            return false;
14044        }
14045
14046        final int appId = pkg.applicationInfo.uid;
14047        removeKeystoreDataIfNeeded(userId, appId);
14048
14049        // Create a native library symlink only if we have native libraries
14050        // and if the native libraries are 32 bit libraries. We do not provide
14051        // this symlink for 64 bit libraries.
14052        if (pkg.applicationInfo.primaryCpuAbi != null &&
14053                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14054            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14055            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14056                    nativeLibPath, userId) < 0) {
14057                Slog.w(TAG, "Failed linking native library dir");
14058                return false;
14059            }
14060        }
14061
14062        return true;
14063    }
14064
14065    /**
14066     * Reverts user permission state changes (permissions and flags) in
14067     * all packages for a given user.
14068     *
14069     * @param userId The device user for which to do a reset.
14070     */
14071    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14072        final int packageCount = mPackages.size();
14073        for (int i = 0; i < packageCount; i++) {
14074            PackageParser.Package pkg = mPackages.valueAt(i);
14075            PackageSetting ps = (PackageSetting) pkg.mExtras;
14076            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14077        }
14078    }
14079
14080    /**
14081     * Reverts user permission state changes (permissions and flags).
14082     *
14083     * @param ps The package for which to reset.
14084     * @param userId The device user for which to do a reset.
14085     */
14086    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14087            final PackageSetting ps, final int userId) {
14088        if (ps.pkg == null) {
14089            return;
14090        }
14091
14092        // These are flags that can change base on user actions.
14093        final int userSettableMask = FLAG_PERMISSION_USER_SET
14094                | FLAG_PERMISSION_USER_FIXED
14095                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14096                | FLAG_PERMISSION_REVIEW_REQUIRED;
14097
14098        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14099                | FLAG_PERMISSION_POLICY_FIXED;
14100
14101        boolean writeInstallPermissions = false;
14102        boolean writeRuntimePermissions = false;
14103
14104        final int permissionCount = ps.pkg.requestedPermissions.size();
14105        for (int i = 0; i < permissionCount; i++) {
14106            String permission = ps.pkg.requestedPermissions.get(i);
14107
14108            BasePermission bp = mSettings.mPermissions.get(permission);
14109            if (bp == null) {
14110                continue;
14111            }
14112
14113            // If shared user we just reset the state to which only this app contributed.
14114            if (ps.sharedUser != null) {
14115                boolean used = false;
14116                final int packageCount = ps.sharedUser.packages.size();
14117                for (int j = 0; j < packageCount; j++) {
14118                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14119                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14120                            && pkg.pkg.requestedPermissions.contains(permission)) {
14121                        used = true;
14122                        break;
14123                    }
14124                }
14125                if (used) {
14126                    continue;
14127                }
14128            }
14129
14130            PermissionsState permissionsState = ps.getPermissionsState();
14131
14132            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14133
14134            // Always clear the user settable flags.
14135            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14136                    bp.name) != null;
14137            // If permission review is enabled and this is a legacy app, mark the
14138            // permission as requiring a review as this is the initial state.
14139            int flags = 0;
14140            if (Build.PERMISSIONS_REVIEW_REQUIRED
14141                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14142                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14143            }
14144            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14145                if (hasInstallState) {
14146                    writeInstallPermissions = true;
14147                } else {
14148                    writeRuntimePermissions = true;
14149                }
14150            }
14151
14152            // Below is only runtime permission handling.
14153            if (!bp.isRuntime()) {
14154                continue;
14155            }
14156
14157            // Never clobber system or policy.
14158            if ((oldFlags & policyOrSystemFlags) != 0) {
14159                continue;
14160            }
14161
14162            // If this permission was granted by default, make sure it is.
14163            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14164                if (permissionsState.grantRuntimePermission(bp, userId)
14165                        != PERMISSION_OPERATION_FAILURE) {
14166                    writeRuntimePermissions = true;
14167                }
14168            // If permission review is enabled the permissions for a legacy apps
14169            // are represented as constantly granted runtime ones, so don't revoke.
14170            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14171                // Otherwise, reset the permission.
14172                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14173                switch (revokeResult) {
14174                    case PERMISSION_OPERATION_SUCCESS: {
14175                        writeRuntimePermissions = true;
14176                    } break;
14177
14178                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14179                        writeRuntimePermissions = true;
14180                        final int appId = ps.appId;
14181                        mHandler.post(new Runnable() {
14182                            @Override
14183                            public void run() {
14184                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14185                            }
14186                        });
14187                    } break;
14188                }
14189            }
14190        }
14191
14192        // Synchronously write as we are taking permissions away.
14193        if (writeRuntimePermissions) {
14194            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14195        }
14196
14197        // Synchronously write as we are taking permissions away.
14198        if (writeInstallPermissions) {
14199            mSettings.writeLPr();
14200        }
14201    }
14202
14203    /**
14204     * Remove entries from the keystore daemon. Will only remove it if the
14205     * {@code appId} is valid.
14206     */
14207    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14208        if (appId < 0) {
14209            return;
14210        }
14211
14212        final KeyStore keyStore = KeyStore.getInstance();
14213        if (keyStore != null) {
14214            if (userId == UserHandle.USER_ALL) {
14215                for (final int individual : sUserManager.getUserIds()) {
14216                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14217                }
14218            } else {
14219                keyStore.clearUid(UserHandle.getUid(userId, appId));
14220            }
14221        } else {
14222            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14223        }
14224    }
14225
14226    @Override
14227    public void deleteApplicationCacheFiles(final String packageName,
14228            final IPackageDataObserver observer) {
14229        mContext.enforceCallingOrSelfPermission(
14230                android.Manifest.permission.DELETE_CACHE_FILES, null);
14231        // Queue up an async operation since the package deletion may take a little while.
14232        final int userId = UserHandle.getCallingUserId();
14233        mHandler.post(new Runnable() {
14234            public void run() {
14235                mHandler.removeCallbacks(this);
14236                final boolean succeded;
14237                synchronized (mInstallLock) {
14238                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14239                }
14240                clearExternalStorageDataSync(packageName, userId, false);
14241                if (observer != null) {
14242                    try {
14243                        observer.onRemoveCompleted(packageName, succeded);
14244                    } catch (RemoteException e) {
14245                        Log.i(TAG, "Observer no longer exists.");
14246                    }
14247                } //end if observer
14248            } //end run
14249        });
14250    }
14251
14252    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14253        if (packageName == null) {
14254            Slog.w(TAG, "Attempt to delete null packageName.");
14255            return false;
14256        }
14257        PackageParser.Package p;
14258        synchronized (mPackages) {
14259            p = mPackages.get(packageName);
14260        }
14261        if (p == null) {
14262            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14263            return false;
14264        }
14265        final ApplicationInfo applicationInfo = p.applicationInfo;
14266        if (applicationInfo == null) {
14267            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14268            return false;
14269        }
14270        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14271        if (retCode < 0) {
14272            Slog.w(TAG, "Couldn't remove cache files for package "
14273                       + packageName + " u" + userId);
14274            return false;
14275        }
14276        return true;
14277    }
14278
14279    @Override
14280    public void getPackageSizeInfo(final String packageName, int userHandle,
14281            final IPackageStatsObserver observer) {
14282        mContext.enforceCallingOrSelfPermission(
14283                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14284        if (packageName == null) {
14285            throw new IllegalArgumentException("Attempt to get size of null packageName");
14286        }
14287
14288        PackageStats stats = new PackageStats(packageName, userHandle);
14289
14290        /*
14291         * Queue up an async operation since the package measurement may take a
14292         * little while.
14293         */
14294        Message msg = mHandler.obtainMessage(INIT_COPY);
14295        msg.obj = new MeasureParams(stats, observer);
14296        mHandler.sendMessage(msg);
14297    }
14298
14299    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14300            PackageStats pStats) {
14301        if (packageName == null) {
14302            Slog.w(TAG, "Attempt to get size of null packageName.");
14303            return false;
14304        }
14305        PackageParser.Package p;
14306        boolean dataOnly = false;
14307        String libDirRoot = null;
14308        String asecPath = null;
14309        PackageSetting ps = null;
14310        synchronized (mPackages) {
14311            p = mPackages.get(packageName);
14312            ps = mSettings.mPackages.get(packageName);
14313            if(p == null) {
14314                dataOnly = true;
14315                if((ps == null) || (ps.pkg == null)) {
14316                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14317                    return false;
14318                }
14319                p = ps.pkg;
14320            }
14321            if (ps != null) {
14322                libDirRoot = ps.legacyNativeLibraryPathString;
14323            }
14324            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14325                final long token = Binder.clearCallingIdentity();
14326                try {
14327                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14328                    if (secureContainerId != null) {
14329                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14330                    }
14331                } finally {
14332                    Binder.restoreCallingIdentity(token);
14333                }
14334            }
14335        }
14336        String publicSrcDir = null;
14337        if(!dataOnly) {
14338            final ApplicationInfo applicationInfo = p.applicationInfo;
14339            if (applicationInfo == null) {
14340                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14341                return false;
14342            }
14343            if (p.isForwardLocked()) {
14344                publicSrcDir = applicationInfo.getBaseResourcePath();
14345            }
14346        }
14347        // TODO: extend to measure size of split APKs
14348        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14349        // not just the first level.
14350        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14351        // just the primary.
14352        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14353
14354        String apkPath;
14355        File packageDir = new File(p.codePath);
14356
14357        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14358            apkPath = packageDir.getAbsolutePath();
14359            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14360            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14361                libDirRoot = null;
14362            }
14363        } else {
14364            apkPath = p.baseCodePath;
14365        }
14366
14367        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14368                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14369        if (res < 0) {
14370            return false;
14371        }
14372
14373        // Fix-up for forward-locked applications in ASEC containers.
14374        if (!isExternal(p)) {
14375            pStats.codeSize += pStats.externalCodeSize;
14376            pStats.externalCodeSize = 0L;
14377        }
14378
14379        return true;
14380    }
14381
14382
14383    @Override
14384    public void addPackageToPreferred(String packageName) {
14385        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14386    }
14387
14388    @Override
14389    public void removePackageFromPreferred(String packageName) {
14390        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14391    }
14392
14393    @Override
14394    public List<PackageInfo> getPreferredPackages(int flags) {
14395        return new ArrayList<PackageInfo>();
14396    }
14397
14398    private int getUidTargetSdkVersionLockedLPr(int uid) {
14399        Object obj = mSettings.getUserIdLPr(uid);
14400        if (obj instanceof SharedUserSetting) {
14401            final SharedUserSetting sus = (SharedUserSetting) obj;
14402            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14403            final Iterator<PackageSetting> it = sus.packages.iterator();
14404            while (it.hasNext()) {
14405                final PackageSetting ps = it.next();
14406                if (ps.pkg != null) {
14407                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14408                    if (v < vers) vers = v;
14409                }
14410            }
14411            return vers;
14412        } else if (obj instanceof PackageSetting) {
14413            final PackageSetting ps = (PackageSetting) obj;
14414            if (ps.pkg != null) {
14415                return ps.pkg.applicationInfo.targetSdkVersion;
14416            }
14417        }
14418        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14419    }
14420
14421    @Override
14422    public void addPreferredActivity(IntentFilter filter, int match,
14423            ComponentName[] set, ComponentName activity, int userId) {
14424        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14425                "Adding preferred");
14426    }
14427
14428    private void addPreferredActivityInternal(IntentFilter filter, int match,
14429            ComponentName[] set, ComponentName activity, boolean always, int userId,
14430            String opname) {
14431        // writer
14432        int callingUid = Binder.getCallingUid();
14433        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14434        if (filter.countActions() == 0) {
14435            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14436            return;
14437        }
14438        synchronized (mPackages) {
14439            if (mContext.checkCallingOrSelfPermission(
14440                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14441                    != PackageManager.PERMISSION_GRANTED) {
14442                if (getUidTargetSdkVersionLockedLPr(callingUid)
14443                        < Build.VERSION_CODES.FROYO) {
14444                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14445                            + callingUid);
14446                    return;
14447                }
14448                mContext.enforceCallingOrSelfPermission(
14449                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14450            }
14451
14452            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14453            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14454                    + userId + ":");
14455            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14456            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14457            scheduleWritePackageRestrictionsLocked(userId);
14458        }
14459    }
14460
14461    @Override
14462    public void replacePreferredActivity(IntentFilter filter, int match,
14463            ComponentName[] set, ComponentName activity, int userId) {
14464        if (filter.countActions() != 1) {
14465            throw new IllegalArgumentException(
14466                    "replacePreferredActivity expects filter to have only 1 action.");
14467        }
14468        if (filter.countDataAuthorities() != 0
14469                || filter.countDataPaths() != 0
14470                || filter.countDataSchemes() > 1
14471                || filter.countDataTypes() != 0) {
14472            throw new IllegalArgumentException(
14473                    "replacePreferredActivity expects filter to have no data authorities, " +
14474                    "paths, or types; and at most one scheme.");
14475        }
14476
14477        final int callingUid = Binder.getCallingUid();
14478        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14479        synchronized (mPackages) {
14480            if (mContext.checkCallingOrSelfPermission(
14481                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14482                    != PackageManager.PERMISSION_GRANTED) {
14483                if (getUidTargetSdkVersionLockedLPr(callingUid)
14484                        < Build.VERSION_CODES.FROYO) {
14485                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14486                            + Binder.getCallingUid());
14487                    return;
14488                }
14489                mContext.enforceCallingOrSelfPermission(
14490                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14491            }
14492
14493            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14494            if (pir != null) {
14495                // Get all of the existing entries that exactly match this filter.
14496                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14497                if (existing != null && existing.size() == 1) {
14498                    PreferredActivity cur = existing.get(0);
14499                    if (DEBUG_PREFERRED) {
14500                        Slog.i(TAG, "Checking replace of preferred:");
14501                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14502                        if (!cur.mPref.mAlways) {
14503                            Slog.i(TAG, "  -- CUR; not mAlways!");
14504                        } else {
14505                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14506                            Slog.i(TAG, "  -- CUR: mSet="
14507                                    + Arrays.toString(cur.mPref.mSetComponents));
14508                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14509                            Slog.i(TAG, "  -- NEW: mMatch="
14510                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14511                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14512                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14513                        }
14514                    }
14515                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14516                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14517                            && cur.mPref.sameSet(set)) {
14518                        // Setting the preferred activity to what it happens to be already
14519                        if (DEBUG_PREFERRED) {
14520                            Slog.i(TAG, "Replacing with same preferred activity "
14521                                    + cur.mPref.mShortComponent + " for user "
14522                                    + userId + ":");
14523                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14524                        }
14525                        return;
14526                    }
14527                }
14528
14529                if (existing != null) {
14530                    if (DEBUG_PREFERRED) {
14531                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14532                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14533                    }
14534                    for (int i = 0; i < existing.size(); i++) {
14535                        PreferredActivity pa = existing.get(i);
14536                        if (DEBUG_PREFERRED) {
14537                            Slog.i(TAG, "Removing existing preferred activity "
14538                                    + pa.mPref.mComponent + ":");
14539                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14540                        }
14541                        pir.removeFilter(pa);
14542                    }
14543                }
14544            }
14545            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14546                    "Replacing preferred");
14547        }
14548    }
14549
14550    @Override
14551    public void clearPackagePreferredActivities(String packageName) {
14552        final int uid = Binder.getCallingUid();
14553        // writer
14554        synchronized (mPackages) {
14555            PackageParser.Package pkg = mPackages.get(packageName);
14556            if (pkg == null || pkg.applicationInfo.uid != uid) {
14557                if (mContext.checkCallingOrSelfPermission(
14558                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14559                        != PackageManager.PERMISSION_GRANTED) {
14560                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14561                            < Build.VERSION_CODES.FROYO) {
14562                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14563                                + Binder.getCallingUid());
14564                        return;
14565                    }
14566                    mContext.enforceCallingOrSelfPermission(
14567                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14568                }
14569            }
14570
14571            int user = UserHandle.getCallingUserId();
14572            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14573                scheduleWritePackageRestrictionsLocked(user);
14574            }
14575        }
14576    }
14577
14578    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14579    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14580        ArrayList<PreferredActivity> removed = null;
14581        boolean changed = false;
14582        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14583            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14584            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14585            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14586                continue;
14587            }
14588            Iterator<PreferredActivity> it = pir.filterIterator();
14589            while (it.hasNext()) {
14590                PreferredActivity pa = it.next();
14591                // Mark entry for removal only if it matches the package name
14592                // and the entry is of type "always".
14593                if (packageName == null ||
14594                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14595                                && pa.mPref.mAlways)) {
14596                    if (removed == null) {
14597                        removed = new ArrayList<PreferredActivity>();
14598                    }
14599                    removed.add(pa);
14600                }
14601            }
14602            if (removed != null) {
14603                for (int j=0; j<removed.size(); j++) {
14604                    PreferredActivity pa = removed.get(j);
14605                    pir.removeFilter(pa);
14606                }
14607                changed = true;
14608            }
14609        }
14610        return changed;
14611    }
14612
14613    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14614    private void clearIntentFilterVerificationsLPw(int userId) {
14615        final int packageCount = mPackages.size();
14616        for (int i = 0; i < packageCount; i++) {
14617            PackageParser.Package pkg = mPackages.valueAt(i);
14618            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14619        }
14620    }
14621
14622    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14623    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14624        if (userId == UserHandle.USER_ALL) {
14625            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14626                    sUserManager.getUserIds())) {
14627                for (int oneUserId : sUserManager.getUserIds()) {
14628                    scheduleWritePackageRestrictionsLocked(oneUserId);
14629                }
14630            }
14631        } else {
14632            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14633                scheduleWritePackageRestrictionsLocked(userId);
14634            }
14635        }
14636    }
14637
14638    void clearDefaultBrowserIfNeeded(String packageName) {
14639        for (int oneUserId : sUserManager.getUserIds()) {
14640            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14641            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14642            if (packageName.equals(defaultBrowserPackageName)) {
14643                setDefaultBrowserPackageName(null, oneUserId);
14644            }
14645        }
14646    }
14647
14648    @Override
14649    public void resetApplicationPreferences(int userId) {
14650        mContext.enforceCallingOrSelfPermission(
14651                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14652        // writer
14653        synchronized (mPackages) {
14654            final long identity = Binder.clearCallingIdentity();
14655            try {
14656                clearPackagePreferredActivitiesLPw(null, userId);
14657                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14658                // TODO: We have to reset the default SMS and Phone. This requires
14659                // significant refactoring to keep all default apps in the package
14660                // manager (cleaner but more work) or have the services provide
14661                // callbacks to the package manager to request a default app reset.
14662                applyFactoryDefaultBrowserLPw(userId);
14663                clearIntentFilterVerificationsLPw(userId);
14664                primeDomainVerificationsLPw(userId);
14665                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14666                scheduleWritePackageRestrictionsLocked(userId);
14667            } finally {
14668                Binder.restoreCallingIdentity(identity);
14669            }
14670        }
14671    }
14672
14673    @Override
14674    public int getPreferredActivities(List<IntentFilter> outFilters,
14675            List<ComponentName> outActivities, String packageName) {
14676
14677        int num = 0;
14678        final int userId = UserHandle.getCallingUserId();
14679        // reader
14680        synchronized (mPackages) {
14681            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14682            if (pir != null) {
14683                final Iterator<PreferredActivity> it = pir.filterIterator();
14684                while (it.hasNext()) {
14685                    final PreferredActivity pa = it.next();
14686                    if (packageName == null
14687                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14688                                    && pa.mPref.mAlways)) {
14689                        if (outFilters != null) {
14690                            outFilters.add(new IntentFilter(pa));
14691                        }
14692                        if (outActivities != null) {
14693                            outActivities.add(pa.mPref.mComponent);
14694                        }
14695                    }
14696                }
14697            }
14698        }
14699
14700        return num;
14701    }
14702
14703    @Override
14704    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14705            int userId) {
14706        int callingUid = Binder.getCallingUid();
14707        if (callingUid != Process.SYSTEM_UID) {
14708            throw new SecurityException(
14709                    "addPersistentPreferredActivity can only be run by the system");
14710        }
14711        if (filter.countActions() == 0) {
14712            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14713            return;
14714        }
14715        synchronized (mPackages) {
14716            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14717                    ":");
14718            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14719            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14720                    new PersistentPreferredActivity(filter, activity));
14721            scheduleWritePackageRestrictionsLocked(userId);
14722        }
14723    }
14724
14725    @Override
14726    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14727        int callingUid = Binder.getCallingUid();
14728        if (callingUid != Process.SYSTEM_UID) {
14729            throw new SecurityException(
14730                    "clearPackagePersistentPreferredActivities can only be run by the system");
14731        }
14732        ArrayList<PersistentPreferredActivity> removed = null;
14733        boolean changed = false;
14734        synchronized (mPackages) {
14735            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14736                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14737                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14738                        .valueAt(i);
14739                if (userId != thisUserId) {
14740                    continue;
14741                }
14742                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14743                while (it.hasNext()) {
14744                    PersistentPreferredActivity ppa = it.next();
14745                    // Mark entry for removal only if it matches the package name.
14746                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14747                        if (removed == null) {
14748                            removed = new ArrayList<PersistentPreferredActivity>();
14749                        }
14750                        removed.add(ppa);
14751                    }
14752                }
14753                if (removed != null) {
14754                    for (int j=0; j<removed.size(); j++) {
14755                        PersistentPreferredActivity ppa = removed.get(j);
14756                        ppir.removeFilter(ppa);
14757                    }
14758                    changed = true;
14759                }
14760            }
14761
14762            if (changed) {
14763                scheduleWritePackageRestrictionsLocked(userId);
14764            }
14765        }
14766    }
14767
14768    /**
14769     * Common machinery for picking apart a restored XML blob and passing
14770     * it to a caller-supplied functor to be applied to the running system.
14771     */
14772    private void restoreFromXml(XmlPullParser parser, int userId,
14773            String expectedStartTag, BlobXmlRestorer functor)
14774            throws IOException, XmlPullParserException {
14775        int type;
14776        while ((type = parser.next()) != XmlPullParser.START_TAG
14777                && type != XmlPullParser.END_DOCUMENT) {
14778        }
14779        if (type != XmlPullParser.START_TAG) {
14780            // oops didn't find a start tag?!
14781            if (DEBUG_BACKUP) {
14782                Slog.e(TAG, "Didn't find start tag during restore");
14783            }
14784            return;
14785        }
14786
14787        // this is supposed to be TAG_PREFERRED_BACKUP
14788        if (!expectedStartTag.equals(parser.getName())) {
14789            if (DEBUG_BACKUP) {
14790                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14791            }
14792            return;
14793        }
14794
14795        // skip interfering stuff, then we're aligned with the backing implementation
14796        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14797        functor.apply(parser, userId);
14798    }
14799
14800    private interface BlobXmlRestorer {
14801        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14802    }
14803
14804    /**
14805     * Non-Binder method, support for the backup/restore mechanism: write the
14806     * full set of preferred activities in its canonical XML format.  Returns the
14807     * XML output as a byte array, or null if there is none.
14808     */
14809    @Override
14810    public byte[] getPreferredActivityBackup(int userId) {
14811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14812            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14813        }
14814
14815        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14816        try {
14817            final XmlSerializer serializer = new FastXmlSerializer();
14818            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14819            serializer.startDocument(null, true);
14820            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14821
14822            synchronized (mPackages) {
14823                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14824            }
14825
14826            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14827            serializer.endDocument();
14828            serializer.flush();
14829        } catch (Exception e) {
14830            if (DEBUG_BACKUP) {
14831                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14832            }
14833            return null;
14834        }
14835
14836        return dataStream.toByteArray();
14837    }
14838
14839    @Override
14840    public void restorePreferredActivities(byte[] backup, int userId) {
14841        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14842            throw new SecurityException("Only the system may call restorePreferredActivities()");
14843        }
14844
14845        try {
14846            final XmlPullParser parser = Xml.newPullParser();
14847            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14848            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14849                    new BlobXmlRestorer() {
14850                        @Override
14851                        public void apply(XmlPullParser parser, int userId)
14852                                throws XmlPullParserException, IOException {
14853                            synchronized (mPackages) {
14854                                mSettings.readPreferredActivitiesLPw(parser, userId);
14855                            }
14856                        }
14857                    } );
14858        } catch (Exception e) {
14859            if (DEBUG_BACKUP) {
14860                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14861            }
14862        }
14863    }
14864
14865    /**
14866     * Non-Binder method, support for the backup/restore mechanism: write the
14867     * default browser (etc) settings in its canonical XML format.  Returns the default
14868     * browser XML representation as a byte array, or null if there is none.
14869     */
14870    @Override
14871    public byte[] getDefaultAppsBackup(int userId) {
14872        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14873            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14874        }
14875
14876        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14877        try {
14878            final XmlSerializer serializer = new FastXmlSerializer();
14879            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14880            serializer.startDocument(null, true);
14881            serializer.startTag(null, TAG_DEFAULT_APPS);
14882
14883            synchronized (mPackages) {
14884                mSettings.writeDefaultAppsLPr(serializer, userId);
14885            }
14886
14887            serializer.endTag(null, TAG_DEFAULT_APPS);
14888            serializer.endDocument();
14889            serializer.flush();
14890        } catch (Exception e) {
14891            if (DEBUG_BACKUP) {
14892                Slog.e(TAG, "Unable to write default apps for backup", e);
14893            }
14894            return null;
14895        }
14896
14897        return dataStream.toByteArray();
14898    }
14899
14900    @Override
14901    public void restoreDefaultApps(byte[] backup, int userId) {
14902        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14903            throw new SecurityException("Only the system may call restoreDefaultApps()");
14904        }
14905
14906        try {
14907            final XmlPullParser parser = Xml.newPullParser();
14908            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14909            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14910                    new BlobXmlRestorer() {
14911                        @Override
14912                        public void apply(XmlPullParser parser, int userId)
14913                                throws XmlPullParserException, IOException {
14914                            synchronized (mPackages) {
14915                                mSettings.readDefaultAppsLPw(parser, userId);
14916                            }
14917                        }
14918                    } );
14919        } catch (Exception e) {
14920            if (DEBUG_BACKUP) {
14921                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14922            }
14923        }
14924    }
14925
14926    @Override
14927    public byte[] getIntentFilterVerificationBackup(int userId) {
14928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14929            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14930        }
14931
14932        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14933        try {
14934            final XmlSerializer serializer = new FastXmlSerializer();
14935            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14936            serializer.startDocument(null, true);
14937            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14938
14939            synchronized (mPackages) {
14940                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14941            }
14942
14943            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14944            serializer.endDocument();
14945            serializer.flush();
14946        } catch (Exception e) {
14947            if (DEBUG_BACKUP) {
14948                Slog.e(TAG, "Unable to write default apps for backup", e);
14949            }
14950            return null;
14951        }
14952
14953        return dataStream.toByteArray();
14954    }
14955
14956    @Override
14957    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14958        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14959            throw new SecurityException("Only the system may call restorePreferredActivities()");
14960        }
14961
14962        try {
14963            final XmlPullParser parser = Xml.newPullParser();
14964            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14965            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14966                    new BlobXmlRestorer() {
14967                        @Override
14968                        public void apply(XmlPullParser parser, int userId)
14969                                throws XmlPullParserException, IOException {
14970                            synchronized (mPackages) {
14971                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14972                                mSettings.writeLPr();
14973                            }
14974                        }
14975                    } );
14976        } catch (Exception e) {
14977            if (DEBUG_BACKUP) {
14978                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14979            }
14980        }
14981    }
14982
14983    @Override
14984    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14985            int sourceUserId, int targetUserId, int flags) {
14986        mContext.enforceCallingOrSelfPermission(
14987                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14988        int callingUid = Binder.getCallingUid();
14989        enforceOwnerRights(ownerPackage, callingUid);
14990        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14991        if (intentFilter.countActions() == 0) {
14992            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14993            return;
14994        }
14995        synchronized (mPackages) {
14996            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14997                    ownerPackage, targetUserId, flags);
14998            CrossProfileIntentResolver resolver =
14999                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15000            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15001            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15002            if (existing != null) {
15003                int size = existing.size();
15004                for (int i = 0; i < size; i++) {
15005                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15006                        return;
15007                    }
15008                }
15009            }
15010            resolver.addFilter(newFilter);
15011            scheduleWritePackageRestrictionsLocked(sourceUserId);
15012        }
15013    }
15014
15015    @Override
15016    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15017        mContext.enforceCallingOrSelfPermission(
15018                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15019        int callingUid = Binder.getCallingUid();
15020        enforceOwnerRights(ownerPackage, callingUid);
15021        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15022        synchronized (mPackages) {
15023            CrossProfileIntentResolver resolver =
15024                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15025            ArraySet<CrossProfileIntentFilter> set =
15026                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15027            for (CrossProfileIntentFilter filter : set) {
15028                if (filter.getOwnerPackage().equals(ownerPackage)) {
15029                    resolver.removeFilter(filter);
15030                }
15031            }
15032            scheduleWritePackageRestrictionsLocked(sourceUserId);
15033        }
15034    }
15035
15036    // Enforcing that callingUid is owning pkg on userId
15037    private void enforceOwnerRights(String pkg, int callingUid) {
15038        // The system owns everything.
15039        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15040            return;
15041        }
15042        int callingUserId = UserHandle.getUserId(callingUid);
15043        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15044        if (pi == null) {
15045            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15046                    + callingUserId);
15047        }
15048        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15049            throw new SecurityException("Calling uid " + callingUid
15050                    + " does not own package " + pkg);
15051        }
15052    }
15053
15054    @Override
15055    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15056        Intent intent = new Intent(Intent.ACTION_MAIN);
15057        intent.addCategory(Intent.CATEGORY_HOME);
15058
15059        final int callingUserId = UserHandle.getCallingUserId();
15060        List<ResolveInfo> list = queryIntentActivities(intent, null,
15061                PackageManager.GET_META_DATA, callingUserId);
15062        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15063                true, false, false, callingUserId);
15064
15065        allHomeCandidates.clear();
15066        if (list != null) {
15067            for (ResolveInfo ri : list) {
15068                allHomeCandidates.add(ri);
15069            }
15070        }
15071        return (preferred == null || preferred.activityInfo == null)
15072                ? null
15073                : new ComponentName(preferred.activityInfo.packageName,
15074                        preferred.activityInfo.name);
15075    }
15076
15077    @Override
15078    public void setApplicationEnabledSetting(String appPackageName,
15079            int newState, int flags, int userId, String callingPackage) {
15080        if (!sUserManager.exists(userId)) return;
15081        if (callingPackage == null) {
15082            callingPackage = Integer.toString(Binder.getCallingUid());
15083        }
15084        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15085    }
15086
15087    @Override
15088    public void setComponentEnabledSetting(ComponentName componentName,
15089            int newState, int flags, int userId) {
15090        if (!sUserManager.exists(userId)) return;
15091        setEnabledSetting(componentName.getPackageName(),
15092                componentName.getClassName(), newState, flags, userId, null);
15093    }
15094
15095    private void setEnabledSetting(final String packageName, String className, int newState,
15096            final int flags, int userId, String callingPackage) {
15097        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15098              || newState == COMPONENT_ENABLED_STATE_ENABLED
15099              || newState == COMPONENT_ENABLED_STATE_DISABLED
15100              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15101              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15102            throw new IllegalArgumentException("Invalid new component state: "
15103                    + newState);
15104        }
15105        PackageSetting pkgSetting;
15106        final int uid = Binder.getCallingUid();
15107        final int permission = mContext.checkCallingOrSelfPermission(
15108                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15109        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15110        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15111        boolean sendNow = false;
15112        boolean isApp = (className == null);
15113        String componentName = isApp ? packageName : className;
15114        int packageUid = -1;
15115        ArrayList<String> components;
15116
15117        // writer
15118        synchronized (mPackages) {
15119            pkgSetting = mSettings.mPackages.get(packageName);
15120            if (pkgSetting == null) {
15121                if (className == null) {
15122                    throw new IllegalArgumentException("Unknown package: " + packageName);
15123                }
15124                throw new IllegalArgumentException(
15125                        "Unknown component: " + packageName + "/" + className);
15126            }
15127            // Allow root and verify that userId is not being specified by a different user
15128            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15129                throw new SecurityException(
15130                        "Permission Denial: attempt to change component state from pid="
15131                        + Binder.getCallingPid()
15132                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15133            }
15134            if (className == null) {
15135                // We're dealing with an application/package level state change
15136                if (pkgSetting.getEnabled(userId) == newState) {
15137                    // Nothing to do
15138                    return;
15139                }
15140                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15141                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15142                    // Don't care about who enables an app.
15143                    callingPackage = null;
15144                }
15145                pkgSetting.setEnabled(newState, userId, callingPackage);
15146                // pkgSetting.pkg.mSetEnabled = newState;
15147            } else {
15148                // We're dealing with a component level state change
15149                // First, verify that this is a valid class name.
15150                PackageParser.Package pkg = pkgSetting.pkg;
15151                if (pkg == null || !pkg.hasComponentClassName(className)) {
15152                    if (pkg != null &&
15153                            pkg.applicationInfo.targetSdkVersion >=
15154                                    Build.VERSION_CODES.JELLY_BEAN) {
15155                        throw new IllegalArgumentException("Component class " + className
15156                                + " does not exist in " + packageName);
15157                    } else {
15158                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15159                                + className + " does not exist in " + packageName);
15160                    }
15161                }
15162                switch (newState) {
15163                case COMPONENT_ENABLED_STATE_ENABLED:
15164                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15165                        return;
15166                    }
15167                    break;
15168                case COMPONENT_ENABLED_STATE_DISABLED:
15169                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15170                        return;
15171                    }
15172                    break;
15173                case COMPONENT_ENABLED_STATE_DEFAULT:
15174                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15175                        return;
15176                    }
15177                    break;
15178                default:
15179                    Slog.e(TAG, "Invalid new component state: " + newState);
15180                    return;
15181                }
15182            }
15183            scheduleWritePackageRestrictionsLocked(userId);
15184            components = mPendingBroadcasts.get(userId, packageName);
15185            final boolean newPackage = components == null;
15186            if (newPackage) {
15187                components = new ArrayList<String>();
15188            }
15189            if (!components.contains(componentName)) {
15190                components.add(componentName);
15191            }
15192            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15193                sendNow = true;
15194                // Purge entry from pending broadcast list if another one exists already
15195                // since we are sending one right away.
15196                mPendingBroadcasts.remove(userId, packageName);
15197            } else {
15198                if (newPackage) {
15199                    mPendingBroadcasts.put(userId, packageName, components);
15200                }
15201                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15202                    // Schedule a message
15203                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15204                }
15205            }
15206        }
15207
15208        long callingId = Binder.clearCallingIdentity();
15209        try {
15210            if (sendNow) {
15211                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15212                sendPackageChangedBroadcast(packageName,
15213                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15214            }
15215        } finally {
15216            Binder.restoreCallingIdentity(callingId);
15217        }
15218    }
15219
15220    private void sendPackageChangedBroadcast(String packageName,
15221            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15222        if (DEBUG_INSTALL)
15223            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15224                    + componentNames);
15225        Bundle extras = new Bundle(4);
15226        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15227        String nameList[] = new String[componentNames.size()];
15228        componentNames.toArray(nameList);
15229        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15230        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15231        extras.putInt(Intent.EXTRA_UID, packageUid);
15232        // If this is not reporting a change of the overall package, then only send it
15233        // to registered receivers.  We don't want to launch a swath of apps for every
15234        // little component state change.
15235        final int flags = !componentNames.contains(packageName)
15236                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15237        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15238                new int[] {UserHandle.getUserId(packageUid)});
15239    }
15240
15241    @Override
15242    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15243        if (!sUserManager.exists(userId)) return;
15244        final int uid = Binder.getCallingUid();
15245        final int permission = mContext.checkCallingOrSelfPermission(
15246                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15247        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15248        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15249        // writer
15250        synchronized (mPackages) {
15251            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15252                    allowedByPermission, uid, userId)) {
15253                scheduleWritePackageRestrictionsLocked(userId);
15254            }
15255        }
15256    }
15257
15258    @Override
15259    public String getInstallerPackageName(String packageName) {
15260        // reader
15261        synchronized (mPackages) {
15262            return mSettings.getInstallerPackageNameLPr(packageName);
15263        }
15264    }
15265
15266    @Override
15267    public int getApplicationEnabledSetting(String packageName, int userId) {
15268        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15269        int uid = Binder.getCallingUid();
15270        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15271        // reader
15272        synchronized (mPackages) {
15273            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15274        }
15275    }
15276
15277    @Override
15278    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15279        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15280        int uid = Binder.getCallingUid();
15281        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15282        // reader
15283        synchronized (mPackages) {
15284            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15285        }
15286    }
15287
15288    @Override
15289    public void enterSafeMode() {
15290        enforceSystemOrRoot("Only the system can request entering safe mode");
15291
15292        if (!mSystemReady) {
15293            mSafeMode = true;
15294        }
15295    }
15296
15297    @Override
15298    public void systemReady() {
15299        mSystemReady = true;
15300
15301        // Read the compatibilty setting when the system is ready.
15302        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15303                mContext.getContentResolver(),
15304                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15305        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15306        if (DEBUG_SETTINGS) {
15307            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15308        }
15309
15310        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15311
15312        synchronized (mPackages) {
15313            // Verify that all of the preferred activity components actually
15314            // exist.  It is possible for applications to be updated and at
15315            // that point remove a previously declared activity component that
15316            // had been set as a preferred activity.  We try to clean this up
15317            // the next time we encounter that preferred activity, but it is
15318            // possible for the user flow to never be able to return to that
15319            // situation so here we do a sanity check to make sure we haven't
15320            // left any junk around.
15321            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15322            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15323                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15324                removed.clear();
15325                for (PreferredActivity pa : pir.filterSet()) {
15326                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15327                        removed.add(pa);
15328                    }
15329                }
15330                if (removed.size() > 0) {
15331                    for (int r=0; r<removed.size(); r++) {
15332                        PreferredActivity pa = removed.get(r);
15333                        Slog.w(TAG, "Removing dangling preferred activity: "
15334                                + pa.mPref.mComponent);
15335                        pir.removeFilter(pa);
15336                    }
15337                    mSettings.writePackageRestrictionsLPr(
15338                            mSettings.mPreferredActivities.keyAt(i));
15339                }
15340            }
15341
15342            for (int userId : UserManagerService.getInstance().getUserIds()) {
15343                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15344                    grantPermissionsUserIds = ArrayUtils.appendInt(
15345                            grantPermissionsUserIds, userId);
15346                }
15347            }
15348        }
15349        sUserManager.systemReady();
15350
15351        // If we upgraded grant all default permissions before kicking off.
15352        for (int userId : grantPermissionsUserIds) {
15353            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15354        }
15355
15356        // Kick off any messages waiting for system ready
15357        if (mPostSystemReadyMessages != null) {
15358            for (Message msg : mPostSystemReadyMessages) {
15359                msg.sendToTarget();
15360            }
15361            mPostSystemReadyMessages = null;
15362        }
15363
15364        // Watch for external volumes that come and go over time
15365        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15366        storage.registerListener(mStorageListener);
15367
15368        mInstallerService.systemReady();
15369        mPackageDexOptimizer.systemReady();
15370
15371        MountServiceInternal mountServiceInternal = LocalServices.getService(
15372                MountServiceInternal.class);
15373        mountServiceInternal.addExternalStoragePolicy(
15374                new MountServiceInternal.ExternalStorageMountPolicy() {
15375            @Override
15376            public int getMountMode(int uid, String packageName) {
15377                if (Process.isIsolated(uid)) {
15378                    return Zygote.MOUNT_EXTERNAL_NONE;
15379                }
15380                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15381                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15382                }
15383                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15384                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15385                }
15386                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15387                    return Zygote.MOUNT_EXTERNAL_READ;
15388                }
15389                return Zygote.MOUNT_EXTERNAL_WRITE;
15390            }
15391
15392            @Override
15393            public boolean hasExternalStorage(int uid, String packageName) {
15394                return true;
15395            }
15396        });
15397    }
15398
15399    @Override
15400    public boolean isSafeMode() {
15401        return mSafeMode;
15402    }
15403
15404    @Override
15405    public boolean hasSystemUidErrors() {
15406        return mHasSystemUidErrors;
15407    }
15408
15409    static String arrayToString(int[] array) {
15410        StringBuffer buf = new StringBuffer(128);
15411        buf.append('[');
15412        if (array != null) {
15413            for (int i=0; i<array.length; i++) {
15414                if (i > 0) buf.append(", ");
15415                buf.append(array[i]);
15416            }
15417        }
15418        buf.append(']');
15419        return buf.toString();
15420    }
15421
15422    static class DumpState {
15423        public static final int DUMP_LIBS = 1 << 0;
15424        public static final int DUMP_FEATURES = 1 << 1;
15425        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15426        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15427        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15428        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15429        public static final int DUMP_PERMISSIONS = 1 << 6;
15430        public static final int DUMP_PACKAGES = 1 << 7;
15431        public static final int DUMP_SHARED_USERS = 1 << 8;
15432        public static final int DUMP_MESSAGES = 1 << 9;
15433        public static final int DUMP_PROVIDERS = 1 << 10;
15434        public static final int DUMP_VERIFIERS = 1 << 11;
15435        public static final int DUMP_PREFERRED = 1 << 12;
15436        public static final int DUMP_PREFERRED_XML = 1 << 13;
15437        public static final int DUMP_KEYSETS = 1 << 14;
15438        public static final int DUMP_VERSION = 1 << 15;
15439        public static final int DUMP_INSTALLS = 1 << 16;
15440        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15441        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15442
15443        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15444
15445        private int mTypes;
15446
15447        private int mOptions;
15448
15449        private boolean mTitlePrinted;
15450
15451        private SharedUserSetting mSharedUser;
15452
15453        public boolean isDumping(int type) {
15454            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15455                return true;
15456            }
15457
15458            return (mTypes & type) != 0;
15459        }
15460
15461        public void setDump(int type) {
15462            mTypes |= type;
15463        }
15464
15465        public boolean isOptionEnabled(int option) {
15466            return (mOptions & option) != 0;
15467        }
15468
15469        public void setOptionEnabled(int option) {
15470            mOptions |= option;
15471        }
15472
15473        public boolean onTitlePrinted() {
15474            final boolean printed = mTitlePrinted;
15475            mTitlePrinted = true;
15476            return printed;
15477        }
15478
15479        public boolean getTitlePrinted() {
15480            return mTitlePrinted;
15481        }
15482
15483        public void setTitlePrinted(boolean enabled) {
15484            mTitlePrinted = enabled;
15485        }
15486
15487        public SharedUserSetting getSharedUser() {
15488            return mSharedUser;
15489        }
15490
15491        public void setSharedUser(SharedUserSetting user) {
15492            mSharedUser = user;
15493        }
15494    }
15495
15496    @Override
15497    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15498            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15499        (new PackageManagerShellCommand(this)).exec(
15500                this, in, out, err, args, resultReceiver);
15501    }
15502
15503    @Override
15504    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15505        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15506                != PackageManager.PERMISSION_GRANTED) {
15507            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15508                    + Binder.getCallingPid()
15509                    + ", uid=" + Binder.getCallingUid()
15510                    + " without permission "
15511                    + android.Manifest.permission.DUMP);
15512            return;
15513        }
15514
15515        DumpState dumpState = new DumpState();
15516        boolean fullPreferred = false;
15517        boolean checkin = false;
15518
15519        String packageName = null;
15520        ArraySet<String> permissionNames = null;
15521
15522        int opti = 0;
15523        while (opti < args.length) {
15524            String opt = args[opti];
15525            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15526                break;
15527            }
15528            opti++;
15529
15530            if ("-a".equals(opt)) {
15531                // Right now we only know how to print all.
15532            } else if ("-h".equals(opt)) {
15533                pw.println("Package manager dump options:");
15534                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15535                pw.println("    --checkin: dump for a checkin");
15536                pw.println("    -f: print details of intent filters");
15537                pw.println("    -h: print this help");
15538                pw.println("  cmd may be one of:");
15539                pw.println("    l[ibraries]: list known shared libraries");
15540                pw.println("    f[eatures]: list device features");
15541                pw.println("    k[eysets]: print known keysets");
15542                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15543                pw.println("    perm[issions]: dump permissions");
15544                pw.println("    permission [name ...]: dump declaration and use of given permission");
15545                pw.println("    pref[erred]: print preferred package settings");
15546                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15547                pw.println("    prov[iders]: dump content providers");
15548                pw.println("    p[ackages]: dump installed packages");
15549                pw.println("    s[hared-users]: dump shared user IDs");
15550                pw.println("    m[essages]: print collected runtime messages");
15551                pw.println("    v[erifiers]: print package verifier info");
15552                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15553                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15554                pw.println("    version: print database version info");
15555                pw.println("    write: write current settings now");
15556                pw.println("    installs: details about install sessions");
15557                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15558                pw.println("    <package.name>: info about given package");
15559                return;
15560            } else if ("--checkin".equals(opt)) {
15561                checkin = true;
15562            } else if ("-f".equals(opt)) {
15563                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15564            } else {
15565                pw.println("Unknown argument: " + opt + "; use -h for help");
15566            }
15567        }
15568
15569        // Is the caller requesting to dump a particular piece of data?
15570        if (opti < args.length) {
15571            String cmd = args[opti];
15572            opti++;
15573            // Is this a package name?
15574            if ("android".equals(cmd) || cmd.contains(".")) {
15575                packageName = cmd;
15576                // When dumping a single package, we always dump all of its
15577                // filter information since the amount of data will be reasonable.
15578                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15579            } else if ("check-permission".equals(cmd)) {
15580                if (opti >= args.length) {
15581                    pw.println("Error: check-permission missing permission argument");
15582                    return;
15583                }
15584                String perm = args[opti];
15585                opti++;
15586                if (opti >= args.length) {
15587                    pw.println("Error: check-permission missing package argument");
15588                    return;
15589                }
15590                String pkg = args[opti];
15591                opti++;
15592                int user = UserHandle.getUserId(Binder.getCallingUid());
15593                if (opti < args.length) {
15594                    try {
15595                        user = Integer.parseInt(args[opti]);
15596                    } catch (NumberFormatException e) {
15597                        pw.println("Error: check-permission user argument is not a number: "
15598                                + args[opti]);
15599                        return;
15600                    }
15601                }
15602                pw.println(checkPermission(perm, pkg, user));
15603                return;
15604            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15605                dumpState.setDump(DumpState.DUMP_LIBS);
15606            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15607                dumpState.setDump(DumpState.DUMP_FEATURES);
15608            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15609                if (opti >= args.length) {
15610                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15611                            | DumpState.DUMP_SERVICE_RESOLVERS
15612                            | DumpState.DUMP_RECEIVER_RESOLVERS
15613                            | DumpState.DUMP_CONTENT_RESOLVERS);
15614                } else {
15615                    while (opti < args.length) {
15616                        String name = args[opti];
15617                        if ("a".equals(name) || "activity".equals(name)) {
15618                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15619                        } else if ("s".equals(name) || "service".equals(name)) {
15620                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15621                        } else if ("r".equals(name) || "receiver".equals(name)) {
15622                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15623                        } else if ("c".equals(name) || "content".equals(name)) {
15624                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15625                        } else {
15626                            pw.println("Error: unknown resolver table type: " + name);
15627                            return;
15628                        }
15629                        opti++;
15630                    }
15631                }
15632            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15633                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15634            } else if ("permission".equals(cmd)) {
15635                if (opti >= args.length) {
15636                    pw.println("Error: permission requires permission name");
15637                    return;
15638                }
15639                permissionNames = new ArraySet<>();
15640                while (opti < args.length) {
15641                    permissionNames.add(args[opti]);
15642                    opti++;
15643                }
15644                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15645                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15646            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15647                dumpState.setDump(DumpState.DUMP_PREFERRED);
15648            } else if ("preferred-xml".equals(cmd)) {
15649                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15650                if (opti < args.length && "--full".equals(args[opti])) {
15651                    fullPreferred = true;
15652                    opti++;
15653                }
15654            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15655                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15656            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15657                dumpState.setDump(DumpState.DUMP_PACKAGES);
15658            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15659                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15660            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15661                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15662            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15663                dumpState.setDump(DumpState.DUMP_MESSAGES);
15664            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15665                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15666            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15667                    || "intent-filter-verifiers".equals(cmd)) {
15668                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15669            } else if ("version".equals(cmd)) {
15670                dumpState.setDump(DumpState.DUMP_VERSION);
15671            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15672                dumpState.setDump(DumpState.DUMP_KEYSETS);
15673            } else if ("installs".equals(cmd)) {
15674                dumpState.setDump(DumpState.DUMP_INSTALLS);
15675            } else if ("write".equals(cmd)) {
15676                synchronized (mPackages) {
15677                    mSettings.writeLPr();
15678                    pw.println("Settings written.");
15679                    return;
15680                }
15681            }
15682        }
15683
15684        if (checkin) {
15685            pw.println("vers,1");
15686        }
15687
15688        // reader
15689        synchronized (mPackages) {
15690            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15691                if (!checkin) {
15692                    if (dumpState.onTitlePrinted())
15693                        pw.println();
15694                    pw.println("Database versions:");
15695                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15696                }
15697            }
15698
15699            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15700                if (!checkin) {
15701                    if (dumpState.onTitlePrinted())
15702                        pw.println();
15703                    pw.println("Verifiers:");
15704                    pw.print("  Required: ");
15705                    pw.print(mRequiredVerifierPackage);
15706                    pw.print(" (uid=");
15707                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15708                            UserHandle.USER_SYSTEM));
15709                    pw.println(")");
15710                } else if (mRequiredVerifierPackage != null) {
15711                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15712                    pw.print(",");
15713                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15714                            UserHandle.USER_SYSTEM));
15715                }
15716            }
15717
15718            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15719                    packageName == null) {
15720                if (mIntentFilterVerifierComponent != null) {
15721                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15722                    if (!checkin) {
15723                        if (dumpState.onTitlePrinted())
15724                            pw.println();
15725                        pw.println("Intent Filter Verifier:");
15726                        pw.print("  Using: ");
15727                        pw.print(verifierPackageName);
15728                        pw.print(" (uid=");
15729                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15730                                UserHandle.USER_SYSTEM));
15731                        pw.println(")");
15732                    } else if (verifierPackageName != null) {
15733                        pw.print("ifv,"); pw.print(verifierPackageName);
15734                        pw.print(",");
15735                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15736                                UserHandle.USER_SYSTEM));
15737                    }
15738                } else {
15739                    pw.println();
15740                    pw.println("No Intent Filter Verifier available!");
15741                }
15742            }
15743
15744            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15745                boolean printedHeader = false;
15746                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15747                while (it.hasNext()) {
15748                    String name = it.next();
15749                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15750                    if (!checkin) {
15751                        if (!printedHeader) {
15752                            if (dumpState.onTitlePrinted())
15753                                pw.println();
15754                            pw.println("Libraries:");
15755                            printedHeader = true;
15756                        }
15757                        pw.print("  ");
15758                    } else {
15759                        pw.print("lib,");
15760                    }
15761                    pw.print(name);
15762                    if (!checkin) {
15763                        pw.print(" -> ");
15764                    }
15765                    if (ent.path != null) {
15766                        if (!checkin) {
15767                            pw.print("(jar) ");
15768                            pw.print(ent.path);
15769                        } else {
15770                            pw.print(",jar,");
15771                            pw.print(ent.path);
15772                        }
15773                    } else {
15774                        if (!checkin) {
15775                            pw.print("(apk) ");
15776                            pw.print(ent.apk);
15777                        } else {
15778                            pw.print(",apk,");
15779                            pw.print(ent.apk);
15780                        }
15781                    }
15782                    pw.println();
15783                }
15784            }
15785
15786            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15787                if (dumpState.onTitlePrinted())
15788                    pw.println();
15789                if (!checkin) {
15790                    pw.println("Features:");
15791                }
15792                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15793                while (it.hasNext()) {
15794                    String name = it.next();
15795                    if (!checkin) {
15796                        pw.print("  ");
15797                    } else {
15798                        pw.print("feat,");
15799                    }
15800                    pw.println(name);
15801                }
15802            }
15803
15804            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15805                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15806                        : "Activity Resolver Table:", "  ", packageName,
15807                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15808                    dumpState.setTitlePrinted(true);
15809                }
15810            }
15811            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15812                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15813                        : "Receiver Resolver Table:", "  ", packageName,
15814                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15815                    dumpState.setTitlePrinted(true);
15816                }
15817            }
15818            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15819                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15820                        : "Service Resolver Table:", "  ", packageName,
15821                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15822                    dumpState.setTitlePrinted(true);
15823                }
15824            }
15825            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15826                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15827                        : "Provider Resolver Table:", "  ", packageName,
15828                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15829                    dumpState.setTitlePrinted(true);
15830                }
15831            }
15832
15833            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15834                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15835                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15836                    int user = mSettings.mPreferredActivities.keyAt(i);
15837                    if (pir.dump(pw,
15838                            dumpState.getTitlePrinted()
15839                                ? "\nPreferred Activities User " + user + ":"
15840                                : "Preferred Activities User " + user + ":", "  ",
15841                            packageName, true, false)) {
15842                        dumpState.setTitlePrinted(true);
15843                    }
15844                }
15845            }
15846
15847            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15848                pw.flush();
15849                FileOutputStream fout = new FileOutputStream(fd);
15850                BufferedOutputStream str = new BufferedOutputStream(fout);
15851                XmlSerializer serializer = new FastXmlSerializer();
15852                try {
15853                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15854                    serializer.startDocument(null, true);
15855                    serializer.setFeature(
15856                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15857                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15858                    serializer.endDocument();
15859                    serializer.flush();
15860                } catch (IllegalArgumentException e) {
15861                    pw.println("Failed writing: " + e);
15862                } catch (IllegalStateException e) {
15863                    pw.println("Failed writing: " + e);
15864                } catch (IOException e) {
15865                    pw.println("Failed writing: " + e);
15866                }
15867            }
15868
15869            if (!checkin
15870                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15871                    && packageName == null) {
15872                pw.println();
15873                int count = mSettings.mPackages.size();
15874                if (count == 0) {
15875                    pw.println("No applications!");
15876                    pw.println();
15877                } else {
15878                    final String prefix = "  ";
15879                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15880                    if (allPackageSettings.size() == 0) {
15881                        pw.println("No domain preferred apps!");
15882                        pw.println();
15883                    } else {
15884                        pw.println("App verification status:");
15885                        pw.println();
15886                        count = 0;
15887                        for (PackageSetting ps : allPackageSettings) {
15888                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15889                            if (ivi == null || ivi.getPackageName() == null) continue;
15890                            pw.println(prefix + "Package: " + ivi.getPackageName());
15891                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15892                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15893                            pw.println();
15894                            count++;
15895                        }
15896                        if (count == 0) {
15897                            pw.println(prefix + "No app verification established.");
15898                            pw.println();
15899                        }
15900                        for (int userId : sUserManager.getUserIds()) {
15901                            pw.println("App linkages for user " + userId + ":");
15902                            pw.println();
15903                            count = 0;
15904                            for (PackageSetting ps : allPackageSettings) {
15905                                final long status = ps.getDomainVerificationStatusForUser(userId);
15906                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15907                                    continue;
15908                                }
15909                                pw.println(prefix + "Package: " + ps.name);
15910                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15911                                String statusStr = IntentFilterVerificationInfo.
15912                                        getStatusStringFromValue(status);
15913                                pw.println(prefix + "Status:  " + statusStr);
15914                                pw.println();
15915                                count++;
15916                            }
15917                            if (count == 0) {
15918                                pw.println(prefix + "No configured app linkages.");
15919                                pw.println();
15920                            }
15921                        }
15922                    }
15923                }
15924            }
15925
15926            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15927                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15928                if (packageName == null && permissionNames == null) {
15929                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15930                        if (iperm == 0) {
15931                            if (dumpState.onTitlePrinted())
15932                                pw.println();
15933                            pw.println("AppOp Permissions:");
15934                        }
15935                        pw.print("  AppOp Permission ");
15936                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15937                        pw.println(":");
15938                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15939                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15940                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15941                        }
15942                    }
15943                }
15944            }
15945
15946            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15947                boolean printedSomething = false;
15948                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15949                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15950                        continue;
15951                    }
15952                    if (!printedSomething) {
15953                        if (dumpState.onTitlePrinted())
15954                            pw.println();
15955                        pw.println("Registered ContentProviders:");
15956                        printedSomething = true;
15957                    }
15958                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15959                    pw.print("    "); pw.println(p.toString());
15960                }
15961                printedSomething = false;
15962                for (Map.Entry<String, PackageParser.Provider> entry :
15963                        mProvidersByAuthority.entrySet()) {
15964                    PackageParser.Provider p = entry.getValue();
15965                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15966                        continue;
15967                    }
15968                    if (!printedSomething) {
15969                        if (dumpState.onTitlePrinted())
15970                            pw.println();
15971                        pw.println("ContentProvider Authorities:");
15972                        printedSomething = true;
15973                    }
15974                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15975                    pw.print("    "); pw.println(p.toString());
15976                    if (p.info != null && p.info.applicationInfo != null) {
15977                        final String appInfo = p.info.applicationInfo.toString();
15978                        pw.print("      applicationInfo="); pw.println(appInfo);
15979                    }
15980                }
15981            }
15982
15983            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15984                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15985            }
15986
15987            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15988                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15989            }
15990
15991            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15992                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15993            }
15994
15995            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15996                // XXX should handle packageName != null by dumping only install data that
15997                // the given package is involved with.
15998                if (dumpState.onTitlePrinted()) pw.println();
15999                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16000            }
16001
16002            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16003                if (dumpState.onTitlePrinted()) pw.println();
16004                mSettings.dumpReadMessagesLPr(pw, dumpState);
16005
16006                pw.println();
16007                pw.println("Package warning messages:");
16008                BufferedReader in = null;
16009                String line = null;
16010                try {
16011                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16012                    while ((line = in.readLine()) != null) {
16013                        if (line.contains("ignored: updated version")) continue;
16014                        pw.println(line);
16015                    }
16016                } catch (IOException ignored) {
16017                } finally {
16018                    IoUtils.closeQuietly(in);
16019                }
16020            }
16021
16022            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16023                BufferedReader in = null;
16024                String line = null;
16025                try {
16026                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16027                    while ((line = in.readLine()) != null) {
16028                        if (line.contains("ignored: updated version")) continue;
16029                        pw.print("msg,");
16030                        pw.println(line);
16031                    }
16032                } catch (IOException ignored) {
16033                } finally {
16034                    IoUtils.closeQuietly(in);
16035                }
16036            }
16037        }
16038    }
16039
16040    private String dumpDomainString(String packageName) {
16041        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16042        List<IntentFilter> filters = getAllIntentFilters(packageName);
16043
16044        ArraySet<String> result = new ArraySet<>();
16045        if (iviList.size() > 0) {
16046            for (IntentFilterVerificationInfo ivi : iviList) {
16047                for (String host : ivi.getDomains()) {
16048                    result.add(host);
16049                }
16050            }
16051        }
16052        if (filters != null && filters.size() > 0) {
16053            for (IntentFilter filter : filters) {
16054                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16055                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16056                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16057                    result.addAll(filter.getHostsList());
16058                }
16059            }
16060        }
16061
16062        StringBuilder sb = new StringBuilder(result.size() * 16);
16063        for (String domain : result) {
16064            if (sb.length() > 0) sb.append(" ");
16065            sb.append(domain);
16066        }
16067        return sb.toString();
16068    }
16069
16070    // ------- apps on sdcard specific code -------
16071    static final boolean DEBUG_SD_INSTALL = false;
16072
16073    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16074
16075    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16076
16077    private boolean mMediaMounted = false;
16078
16079    static String getEncryptKey() {
16080        try {
16081            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16082                    SD_ENCRYPTION_KEYSTORE_NAME);
16083            if (sdEncKey == null) {
16084                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16085                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16086                if (sdEncKey == null) {
16087                    Slog.e(TAG, "Failed to create encryption keys");
16088                    return null;
16089                }
16090            }
16091            return sdEncKey;
16092        } catch (NoSuchAlgorithmException nsae) {
16093            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16094            return null;
16095        } catch (IOException ioe) {
16096            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16097            return null;
16098        }
16099    }
16100
16101    /*
16102     * Update media status on PackageManager.
16103     */
16104    @Override
16105    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16106        int callingUid = Binder.getCallingUid();
16107        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16108            throw new SecurityException("Media status can only be updated by the system");
16109        }
16110        // reader; this apparently protects mMediaMounted, but should probably
16111        // be a different lock in that case.
16112        synchronized (mPackages) {
16113            Log.i(TAG, "Updating external media status from "
16114                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16115                    + (mediaStatus ? "mounted" : "unmounted"));
16116            if (DEBUG_SD_INSTALL)
16117                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16118                        + ", mMediaMounted=" + mMediaMounted);
16119            if (mediaStatus == mMediaMounted) {
16120                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16121                        : 0, -1);
16122                mHandler.sendMessage(msg);
16123                return;
16124            }
16125            mMediaMounted = mediaStatus;
16126        }
16127        // Queue up an async operation since the package installation may take a
16128        // little while.
16129        mHandler.post(new Runnable() {
16130            public void run() {
16131                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16132            }
16133        });
16134    }
16135
16136    /**
16137     * Called by MountService when the initial ASECs to scan are available.
16138     * Should block until all the ASEC containers are finished being scanned.
16139     */
16140    public void scanAvailableAsecs() {
16141        updateExternalMediaStatusInner(true, false, false);
16142        if (mShouldRestoreconData) {
16143            SELinuxMMAC.setRestoreconDone();
16144            mShouldRestoreconData = false;
16145        }
16146    }
16147
16148    /*
16149     * Collect information of applications on external media, map them against
16150     * existing containers and update information based on current mount status.
16151     * Please note that we always have to report status if reportStatus has been
16152     * set to true especially when unloading packages.
16153     */
16154    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16155            boolean externalStorage) {
16156        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16157        int[] uidArr = EmptyArray.INT;
16158
16159        final String[] list = PackageHelper.getSecureContainerList();
16160        if (ArrayUtils.isEmpty(list)) {
16161            Log.i(TAG, "No secure containers found");
16162        } else {
16163            // Process list of secure containers and categorize them
16164            // as active or stale based on their package internal state.
16165
16166            // reader
16167            synchronized (mPackages) {
16168                for (String cid : list) {
16169                    // Leave stages untouched for now; installer service owns them
16170                    if (PackageInstallerService.isStageName(cid)) continue;
16171
16172                    if (DEBUG_SD_INSTALL)
16173                        Log.i(TAG, "Processing container " + cid);
16174                    String pkgName = getAsecPackageName(cid);
16175                    if (pkgName == null) {
16176                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16177                        continue;
16178                    }
16179                    if (DEBUG_SD_INSTALL)
16180                        Log.i(TAG, "Looking for pkg : " + pkgName);
16181
16182                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16183                    if (ps == null) {
16184                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16185                        continue;
16186                    }
16187
16188                    /*
16189                     * Skip packages that are not external if we're unmounting
16190                     * external storage.
16191                     */
16192                    if (externalStorage && !isMounted && !isExternal(ps)) {
16193                        continue;
16194                    }
16195
16196                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16197                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16198                    // The package status is changed only if the code path
16199                    // matches between settings and the container id.
16200                    if (ps.codePathString != null
16201                            && ps.codePathString.startsWith(args.getCodePath())) {
16202                        if (DEBUG_SD_INSTALL) {
16203                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16204                                    + " at code path: " + ps.codePathString);
16205                        }
16206
16207                        // We do have a valid package installed on sdcard
16208                        processCids.put(args, ps.codePathString);
16209                        final int uid = ps.appId;
16210                        if (uid != -1) {
16211                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16212                        }
16213                    } else {
16214                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16215                                + ps.codePathString);
16216                    }
16217                }
16218            }
16219
16220            Arrays.sort(uidArr);
16221        }
16222
16223        // Process packages with valid entries.
16224        if (isMounted) {
16225            if (DEBUG_SD_INSTALL)
16226                Log.i(TAG, "Loading packages");
16227            loadMediaPackages(processCids, uidArr, externalStorage);
16228            startCleaningPackages();
16229            mInstallerService.onSecureContainersAvailable();
16230        } else {
16231            if (DEBUG_SD_INSTALL)
16232                Log.i(TAG, "Unloading packages");
16233            unloadMediaPackages(processCids, uidArr, reportStatus);
16234        }
16235    }
16236
16237    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16238            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16239        final int size = infos.size();
16240        final String[] packageNames = new String[size];
16241        final int[] packageUids = new int[size];
16242        for (int i = 0; i < size; i++) {
16243            final ApplicationInfo info = infos.get(i);
16244            packageNames[i] = info.packageName;
16245            packageUids[i] = info.uid;
16246        }
16247        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16248                finishedReceiver);
16249    }
16250
16251    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16252            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16253        sendResourcesChangedBroadcast(mediaStatus, replacing,
16254                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16255    }
16256
16257    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16258            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16259        int size = pkgList.length;
16260        if (size > 0) {
16261            // Send broadcasts here
16262            Bundle extras = new Bundle();
16263            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16264            if (uidArr != null) {
16265                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16266            }
16267            if (replacing) {
16268                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16269            }
16270            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16271                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16272            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16273        }
16274    }
16275
16276   /*
16277     * Look at potentially valid container ids from processCids If package
16278     * information doesn't match the one on record or package scanning fails,
16279     * the cid is added to list of removeCids. We currently don't delete stale
16280     * containers.
16281     */
16282    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16283            boolean externalStorage) {
16284        ArrayList<String> pkgList = new ArrayList<String>();
16285        Set<AsecInstallArgs> keys = processCids.keySet();
16286
16287        for (AsecInstallArgs args : keys) {
16288            String codePath = processCids.get(args);
16289            if (DEBUG_SD_INSTALL)
16290                Log.i(TAG, "Loading container : " + args.cid);
16291            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16292            try {
16293                // Make sure there are no container errors first.
16294                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16295                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16296                            + " when installing from sdcard");
16297                    continue;
16298                }
16299                // Check code path here.
16300                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16301                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16302                            + " does not match one in settings " + codePath);
16303                    continue;
16304                }
16305                // Parse package
16306                int parseFlags = mDefParseFlags;
16307                if (args.isExternalAsec()) {
16308                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16309                }
16310                if (args.isFwdLocked()) {
16311                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16312                }
16313
16314                synchronized (mInstallLock) {
16315                    PackageParser.Package pkg = null;
16316                    try {
16317                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16318                    } catch (PackageManagerException e) {
16319                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16320                    }
16321                    // Scan the package
16322                    if (pkg != null) {
16323                        /*
16324                         * TODO why is the lock being held? doPostInstall is
16325                         * called in other places without the lock. This needs
16326                         * to be straightened out.
16327                         */
16328                        // writer
16329                        synchronized (mPackages) {
16330                            retCode = PackageManager.INSTALL_SUCCEEDED;
16331                            pkgList.add(pkg.packageName);
16332                            // Post process args
16333                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16334                                    pkg.applicationInfo.uid);
16335                        }
16336                    } else {
16337                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16338                    }
16339                }
16340
16341            } finally {
16342                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16343                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16344                }
16345            }
16346        }
16347        // writer
16348        synchronized (mPackages) {
16349            // If the platform SDK has changed since the last time we booted,
16350            // we need to re-grant app permission to catch any new ones that
16351            // appear. This is really a hack, and means that apps can in some
16352            // cases get permissions that the user didn't initially explicitly
16353            // allow... it would be nice to have some better way to handle
16354            // this situation.
16355            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16356                    : mSettings.getInternalVersion();
16357            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16358                    : StorageManager.UUID_PRIVATE_INTERNAL;
16359
16360            int updateFlags = UPDATE_PERMISSIONS_ALL;
16361            if (ver.sdkVersion != mSdkVersion) {
16362                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16363                        + mSdkVersion + "; regranting permissions for external");
16364                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16365            }
16366            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16367
16368            // Yay, everything is now upgraded
16369            ver.forceCurrent();
16370
16371            // can downgrade to reader
16372            // Persist settings
16373            mSettings.writeLPr();
16374        }
16375        // Send a broadcast to let everyone know we are done processing
16376        if (pkgList.size() > 0) {
16377            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16378        }
16379    }
16380
16381   /*
16382     * Utility method to unload a list of specified containers
16383     */
16384    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16385        // Just unmount all valid containers.
16386        for (AsecInstallArgs arg : cidArgs) {
16387            synchronized (mInstallLock) {
16388                arg.doPostDeleteLI(false);
16389           }
16390       }
16391   }
16392
16393    /*
16394     * Unload packages mounted on external media. This involves deleting package
16395     * data from internal structures, sending broadcasts about diabled packages,
16396     * gc'ing to free up references, unmounting all secure containers
16397     * corresponding to packages on external media, and posting a
16398     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16399     * that we always have to post this message if status has been requested no
16400     * matter what.
16401     */
16402    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16403            final boolean reportStatus) {
16404        if (DEBUG_SD_INSTALL)
16405            Log.i(TAG, "unloading media packages");
16406        ArrayList<String> pkgList = new ArrayList<String>();
16407        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16408        final Set<AsecInstallArgs> keys = processCids.keySet();
16409        for (AsecInstallArgs args : keys) {
16410            String pkgName = args.getPackageName();
16411            if (DEBUG_SD_INSTALL)
16412                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16413            // Delete package internally
16414            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16415            synchronized (mInstallLock) {
16416                boolean res = deletePackageLI(pkgName, null, false, null, null,
16417                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16418                if (res) {
16419                    pkgList.add(pkgName);
16420                } else {
16421                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16422                    failedList.add(args);
16423                }
16424            }
16425        }
16426
16427        // reader
16428        synchronized (mPackages) {
16429            // We didn't update the settings after removing each package;
16430            // write them now for all packages.
16431            mSettings.writeLPr();
16432        }
16433
16434        // We have to absolutely send UPDATED_MEDIA_STATUS only
16435        // after confirming that all the receivers processed the ordered
16436        // broadcast when packages get disabled, force a gc to clean things up.
16437        // and unload all the containers.
16438        if (pkgList.size() > 0) {
16439            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16440                    new IIntentReceiver.Stub() {
16441                public void performReceive(Intent intent, int resultCode, String data,
16442                        Bundle extras, boolean ordered, boolean sticky,
16443                        int sendingUser) throws RemoteException {
16444                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16445                            reportStatus ? 1 : 0, 1, keys);
16446                    mHandler.sendMessage(msg);
16447                }
16448            });
16449        } else {
16450            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16451                    keys);
16452            mHandler.sendMessage(msg);
16453        }
16454    }
16455
16456    private void loadPrivatePackages(final VolumeInfo vol) {
16457        mHandler.post(new Runnable() {
16458            @Override
16459            public void run() {
16460                loadPrivatePackagesInner(vol);
16461            }
16462        });
16463    }
16464
16465    private void loadPrivatePackagesInner(VolumeInfo vol) {
16466        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16467        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16468
16469        final VersionInfo ver;
16470        final List<PackageSetting> packages;
16471        synchronized (mPackages) {
16472            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16473            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16474        }
16475
16476        for (PackageSetting ps : packages) {
16477            synchronized (mInstallLock) {
16478                final PackageParser.Package pkg;
16479                try {
16480                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16481                    loaded.add(pkg.applicationInfo);
16482                } catch (PackageManagerException e) {
16483                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16484                }
16485
16486                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16487                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16488                }
16489            }
16490        }
16491
16492        synchronized (mPackages) {
16493            int updateFlags = UPDATE_PERMISSIONS_ALL;
16494            if (ver.sdkVersion != mSdkVersion) {
16495                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16496                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16497                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16498            }
16499            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16500
16501            // Yay, everything is now upgraded
16502            ver.forceCurrent();
16503
16504            mSettings.writeLPr();
16505        }
16506
16507        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16508        sendResourcesChangedBroadcast(true, false, loaded, null);
16509    }
16510
16511    private void unloadPrivatePackages(final VolumeInfo vol) {
16512        mHandler.post(new Runnable() {
16513            @Override
16514            public void run() {
16515                unloadPrivatePackagesInner(vol);
16516            }
16517        });
16518    }
16519
16520    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16521        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16522        synchronized (mInstallLock) {
16523        synchronized (mPackages) {
16524            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16525            for (PackageSetting ps : packages) {
16526                if (ps.pkg == null) continue;
16527
16528                final ApplicationInfo info = ps.pkg.applicationInfo;
16529                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16530                if (deletePackageLI(ps.name, null, false, null, null,
16531                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16532                    unloaded.add(info);
16533                } else {
16534                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16535                }
16536            }
16537
16538            mSettings.writeLPr();
16539        }
16540        }
16541
16542        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16543        sendResourcesChangedBroadcast(false, false, unloaded, null);
16544    }
16545
16546    /**
16547     * Examine all users present on given mounted volume, and destroy data
16548     * belonging to users that are no longer valid, or whose user ID has been
16549     * recycled.
16550     */
16551    private void reconcileUsers(String volumeUuid) {
16552        final File[] files = FileUtils
16553                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16554        for (File file : files) {
16555            if (!file.isDirectory()) continue;
16556
16557            final int userId;
16558            final UserInfo info;
16559            try {
16560                userId = Integer.parseInt(file.getName());
16561                info = sUserManager.getUserInfo(userId);
16562            } catch (NumberFormatException e) {
16563                Slog.w(TAG, "Invalid user directory " + file);
16564                continue;
16565            }
16566
16567            boolean destroyUser = false;
16568            if (info == null) {
16569                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16570                        + " because no matching user was found");
16571                destroyUser = true;
16572            } else {
16573                try {
16574                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16575                } catch (IOException e) {
16576                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16577                            + " because we failed to enforce serial number: " + e);
16578                    destroyUser = true;
16579                }
16580            }
16581
16582            if (destroyUser) {
16583                synchronized (mInstallLock) {
16584                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16585                }
16586            }
16587        }
16588
16589        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16590        final UserManager um = mContext.getSystemService(UserManager.class);
16591        for (UserInfo user : um.getUsers()) {
16592            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16593            if (userDir.exists()) continue;
16594
16595            try {
16596                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16597                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16598            } catch (IOException e) {
16599                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16600            }
16601        }
16602    }
16603
16604    /**
16605     * Examine all apps present on given mounted volume, and destroy apps that
16606     * aren't expected, either due to uninstallation or reinstallation on
16607     * another volume.
16608     */
16609    private void reconcileApps(String volumeUuid) {
16610        final File[] files = FileUtils
16611                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16612        for (File file : files) {
16613            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16614                    && !PackageInstallerService.isStageName(file.getName());
16615            if (!isPackage) {
16616                // Ignore entries which are not packages
16617                continue;
16618            }
16619
16620            boolean destroyApp = false;
16621            String packageName = null;
16622            try {
16623                final PackageLite pkg = PackageParser.parsePackageLite(file,
16624                        PackageParser.PARSE_MUST_BE_APK);
16625                packageName = pkg.packageName;
16626
16627                synchronized (mPackages) {
16628                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16629                    if (ps == null) {
16630                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16631                                + volumeUuid + " because we found no install record");
16632                        destroyApp = true;
16633                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16634                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16635                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16636                        destroyApp = true;
16637                    }
16638                }
16639
16640            } catch (PackageParserException e) {
16641                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16642                destroyApp = true;
16643            }
16644
16645            if (destroyApp) {
16646                synchronized (mInstallLock) {
16647                    if (packageName != null) {
16648                        removeDataDirsLI(volumeUuid, packageName);
16649                    }
16650                    if (file.isDirectory()) {
16651                        mInstaller.rmPackageDir(file.getAbsolutePath());
16652                    } else {
16653                        file.delete();
16654                    }
16655                }
16656            }
16657        }
16658    }
16659
16660    private void unfreezePackage(String packageName) {
16661        synchronized (mPackages) {
16662            final PackageSetting ps = mSettings.mPackages.get(packageName);
16663            if (ps != null) {
16664                ps.frozen = false;
16665            }
16666        }
16667    }
16668
16669    @Override
16670    public int movePackage(final String packageName, final String volumeUuid) {
16671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16672
16673        final int moveId = mNextMoveId.getAndIncrement();
16674        mHandler.post(new Runnable() {
16675            @Override
16676            public void run() {
16677                try {
16678                    movePackageInternal(packageName, volumeUuid, moveId);
16679                } catch (PackageManagerException e) {
16680                    Slog.w(TAG, "Failed to move " + packageName, e);
16681                    mMoveCallbacks.notifyStatusChanged(moveId,
16682                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16683                }
16684            }
16685        });
16686        return moveId;
16687    }
16688
16689    private void movePackageInternal(final String packageName, final String volumeUuid,
16690            final int moveId) throws PackageManagerException {
16691        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16692        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16693        final PackageManager pm = mContext.getPackageManager();
16694
16695        final boolean currentAsec;
16696        final String currentVolumeUuid;
16697        final File codeFile;
16698        final String installerPackageName;
16699        final String packageAbiOverride;
16700        final int appId;
16701        final String seinfo;
16702        final String label;
16703
16704        // reader
16705        synchronized (mPackages) {
16706            final PackageParser.Package pkg = mPackages.get(packageName);
16707            final PackageSetting ps = mSettings.mPackages.get(packageName);
16708            if (pkg == null || ps == null) {
16709                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16710            }
16711
16712            if (pkg.applicationInfo.isSystemApp()) {
16713                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16714                        "Cannot move system application");
16715            }
16716
16717            if (pkg.applicationInfo.isExternalAsec()) {
16718                currentAsec = true;
16719                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16720            } else if (pkg.applicationInfo.isForwardLocked()) {
16721                currentAsec = true;
16722                currentVolumeUuid = "forward_locked";
16723            } else {
16724                currentAsec = false;
16725                currentVolumeUuid = ps.volumeUuid;
16726
16727                final File probe = new File(pkg.codePath);
16728                final File probeOat = new File(probe, "oat");
16729                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16730                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16731                            "Move only supported for modern cluster style installs");
16732                }
16733            }
16734
16735            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16736                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16737                        "Package already moved to " + volumeUuid);
16738            }
16739
16740            if (ps.frozen) {
16741                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16742                        "Failed to move already frozen package");
16743            }
16744            ps.frozen = true;
16745
16746            codeFile = new File(pkg.codePath);
16747            installerPackageName = ps.installerPackageName;
16748            packageAbiOverride = ps.cpuAbiOverrideString;
16749            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16750            seinfo = pkg.applicationInfo.seinfo;
16751            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16752        }
16753
16754        // Now that we're guarded by frozen state, kill app during move
16755        final long token = Binder.clearCallingIdentity();
16756        try {
16757            killApplication(packageName, appId, "move pkg");
16758        } finally {
16759            Binder.restoreCallingIdentity(token);
16760        }
16761
16762        final Bundle extras = new Bundle();
16763        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16764        extras.putString(Intent.EXTRA_TITLE, label);
16765        mMoveCallbacks.notifyCreated(moveId, extras);
16766
16767        int installFlags;
16768        final boolean moveCompleteApp;
16769        final File measurePath;
16770
16771        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16772            installFlags = INSTALL_INTERNAL;
16773            moveCompleteApp = !currentAsec;
16774            measurePath = Environment.getDataAppDirectory(volumeUuid);
16775        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16776            installFlags = INSTALL_EXTERNAL;
16777            moveCompleteApp = false;
16778            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16779        } else {
16780            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16781            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16782                    || !volume.isMountedWritable()) {
16783                unfreezePackage(packageName);
16784                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16785                        "Move location not mounted private volume");
16786            }
16787
16788            Preconditions.checkState(!currentAsec);
16789
16790            installFlags = INSTALL_INTERNAL;
16791            moveCompleteApp = true;
16792            measurePath = Environment.getDataAppDirectory(volumeUuid);
16793        }
16794
16795        final PackageStats stats = new PackageStats(null, -1);
16796        synchronized (mInstaller) {
16797            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16798                unfreezePackage(packageName);
16799                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16800                        "Failed to measure package size");
16801            }
16802        }
16803
16804        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16805                + stats.dataSize);
16806
16807        final long startFreeBytes = measurePath.getFreeSpace();
16808        final long sizeBytes;
16809        if (moveCompleteApp) {
16810            sizeBytes = stats.codeSize + stats.dataSize;
16811        } else {
16812            sizeBytes = stats.codeSize;
16813        }
16814
16815        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16816            unfreezePackage(packageName);
16817            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16818                    "Not enough free space to move");
16819        }
16820
16821        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16822
16823        final CountDownLatch installedLatch = new CountDownLatch(1);
16824        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16825            @Override
16826            public void onUserActionRequired(Intent intent) throws RemoteException {
16827                throw new IllegalStateException();
16828            }
16829
16830            @Override
16831            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16832                    Bundle extras) throws RemoteException {
16833                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16834                        + PackageManager.installStatusToString(returnCode, msg));
16835
16836                installedLatch.countDown();
16837
16838                // Regardless of success or failure of the move operation,
16839                // always unfreeze the package
16840                unfreezePackage(packageName);
16841
16842                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16843                switch (status) {
16844                    case PackageInstaller.STATUS_SUCCESS:
16845                        mMoveCallbacks.notifyStatusChanged(moveId,
16846                                PackageManager.MOVE_SUCCEEDED);
16847                        break;
16848                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16849                        mMoveCallbacks.notifyStatusChanged(moveId,
16850                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16851                        break;
16852                    default:
16853                        mMoveCallbacks.notifyStatusChanged(moveId,
16854                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16855                        break;
16856                }
16857            }
16858        };
16859
16860        final MoveInfo move;
16861        if (moveCompleteApp) {
16862            // Kick off a thread to report progress estimates
16863            new Thread() {
16864                @Override
16865                public void run() {
16866                    while (true) {
16867                        try {
16868                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16869                                break;
16870                            }
16871                        } catch (InterruptedException ignored) {
16872                        }
16873
16874                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16875                        final int progress = 10 + (int) MathUtils.constrain(
16876                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16877                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16878                    }
16879                }
16880            }.start();
16881
16882            final String dataAppName = codeFile.getName();
16883            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16884                    dataAppName, appId, seinfo);
16885        } else {
16886            move = null;
16887        }
16888
16889        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16890
16891        final Message msg = mHandler.obtainMessage(INIT_COPY);
16892        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16893        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16894                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16895        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16896        msg.obj = params;
16897
16898        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16899                System.identityHashCode(msg.obj));
16900        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16901                System.identityHashCode(msg.obj));
16902
16903        mHandler.sendMessage(msg);
16904    }
16905
16906    @Override
16907    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16908        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16909
16910        final int realMoveId = mNextMoveId.getAndIncrement();
16911        final Bundle extras = new Bundle();
16912        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16913        mMoveCallbacks.notifyCreated(realMoveId, extras);
16914
16915        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16916            @Override
16917            public void onCreated(int moveId, Bundle extras) {
16918                // Ignored
16919            }
16920
16921            @Override
16922            public void onStatusChanged(int moveId, int status, long estMillis) {
16923                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16924            }
16925        };
16926
16927        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16928        storage.setPrimaryStorageUuid(volumeUuid, callback);
16929        return realMoveId;
16930    }
16931
16932    @Override
16933    public int getMoveStatus(int moveId) {
16934        mContext.enforceCallingOrSelfPermission(
16935                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16936        return mMoveCallbacks.mLastStatus.get(moveId);
16937    }
16938
16939    @Override
16940    public void registerMoveCallback(IPackageMoveObserver callback) {
16941        mContext.enforceCallingOrSelfPermission(
16942                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16943        mMoveCallbacks.register(callback);
16944    }
16945
16946    @Override
16947    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16948        mContext.enforceCallingOrSelfPermission(
16949                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16950        mMoveCallbacks.unregister(callback);
16951    }
16952
16953    @Override
16954    public boolean setInstallLocation(int loc) {
16955        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16956                null);
16957        if (getInstallLocation() == loc) {
16958            return true;
16959        }
16960        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16961                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16962            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16963                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16964            return true;
16965        }
16966        return false;
16967   }
16968
16969    @Override
16970    public int getInstallLocation() {
16971        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16972                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16973                PackageHelper.APP_INSTALL_AUTO);
16974    }
16975
16976    /** Called by UserManagerService */
16977    void cleanUpUser(UserManagerService userManager, int userHandle) {
16978        synchronized (mPackages) {
16979            mDirtyUsers.remove(userHandle);
16980            mUserNeedsBadging.delete(userHandle);
16981            mSettings.removeUserLPw(userHandle);
16982            mPendingBroadcasts.remove(userHandle);
16983            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16984        }
16985        synchronized (mInstallLock) {
16986            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16987            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16988                final String volumeUuid = vol.getFsUuid();
16989                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16990                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16991            }
16992            synchronized (mPackages) {
16993                removeUnusedPackagesLILPw(userManager, userHandle);
16994            }
16995        }
16996    }
16997
16998    /**
16999     * We're removing userHandle and would like to remove any downloaded packages
17000     * that are no longer in use by any other user.
17001     * @param userHandle the user being removed
17002     */
17003    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17004        final boolean DEBUG_CLEAN_APKS = false;
17005        int [] users = userManager.getUserIds();
17006        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17007        while (psit.hasNext()) {
17008            PackageSetting ps = psit.next();
17009            if (ps.pkg == null) {
17010                continue;
17011            }
17012            final String packageName = ps.pkg.packageName;
17013            // Skip over if system app
17014            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17015                continue;
17016            }
17017            if (DEBUG_CLEAN_APKS) {
17018                Slog.i(TAG, "Checking package " + packageName);
17019            }
17020            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17021            if (keep) {
17022                if (DEBUG_CLEAN_APKS) {
17023                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17024                }
17025            } else {
17026                for (int i = 0; i < users.length; i++) {
17027                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17028                        keep = true;
17029                        if (DEBUG_CLEAN_APKS) {
17030                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17031                                    + users[i]);
17032                        }
17033                        break;
17034                    }
17035                }
17036            }
17037            if (!keep) {
17038                if (DEBUG_CLEAN_APKS) {
17039                    Slog.i(TAG, "  Removing package " + packageName);
17040                }
17041                mHandler.post(new Runnable() {
17042                    public void run() {
17043                        deletePackageX(packageName, userHandle, 0);
17044                    } //end run
17045                });
17046            }
17047        }
17048    }
17049
17050    /** Called by UserManagerService */
17051    void createNewUser(int userHandle) {
17052        synchronized (mInstallLock) {
17053            mInstaller.createUserConfig(userHandle);
17054            mSettings.createNewUserLI(this, mInstaller, userHandle);
17055        }
17056        synchronized (mPackages) {
17057            applyFactoryDefaultBrowserLPw(userHandle);
17058            primeDomainVerificationsLPw(userHandle);
17059        }
17060    }
17061
17062    void newUserCreated(final int userHandle) {
17063        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17064        // If permission review for legacy apps is required, we represent
17065        // dagerous permissions for such apps as always granted runtime
17066        // permissions to keep per user flag state whether review is needed.
17067        // Hence, if a new user is added we have to propagate dangerous
17068        // permission grants for these legacy apps.
17069        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17070            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17071                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17072        }
17073    }
17074
17075    @Override
17076    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17077        mContext.enforceCallingOrSelfPermission(
17078                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17079                "Only package verification agents can read the verifier device identity");
17080
17081        synchronized (mPackages) {
17082            return mSettings.getVerifierDeviceIdentityLPw();
17083        }
17084    }
17085
17086    @Override
17087    public void setPermissionEnforced(String permission, boolean enforced) {
17088        // TODO: Now that we no longer change GID for storage, this should to away.
17089        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17090                "setPermissionEnforced");
17091        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17092            synchronized (mPackages) {
17093                if (mSettings.mReadExternalStorageEnforced == null
17094                        || mSettings.mReadExternalStorageEnforced != enforced) {
17095                    mSettings.mReadExternalStorageEnforced = enforced;
17096                    mSettings.writeLPr();
17097                }
17098            }
17099            // kill any non-foreground processes so we restart them and
17100            // grant/revoke the GID.
17101            final IActivityManager am = ActivityManagerNative.getDefault();
17102            if (am != null) {
17103                final long token = Binder.clearCallingIdentity();
17104                try {
17105                    am.killProcessesBelowForeground("setPermissionEnforcement");
17106                } catch (RemoteException e) {
17107                } finally {
17108                    Binder.restoreCallingIdentity(token);
17109                }
17110            }
17111        } else {
17112            throw new IllegalArgumentException("No selective enforcement for " + permission);
17113        }
17114    }
17115
17116    @Override
17117    @Deprecated
17118    public boolean isPermissionEnforced(String permission) {
17119        return true;
17120    }
17121
17122    @Override
17123    public boolean isStorageLow() {
17124        final long token = Binder.clearCallingIdentity();
17125        try {
17126            final DeviceStorageMonitorInternal
17127                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17128            if (dsm != null) {
17129                return dsm.isMemoryLow();
17130            } else {
17131                return false;
17132            }
17133        } finally {
17134            Binder.restoreCallingIdentity(token);
17135        }
17136    }
17137
17138    @Override
17139    public IPackageInstaller getPackageInstaller() {
17140        return mInstallerService;
17141    }
17142
17143    private boolean userNeedsBadging(int userId) {
17144        int index = mUserNeedsBadging.indexOfKey(userId);
17145        if (index < 0) {
17146            final UserInfo userInfo;
17147            final long token = Binder.clearCallingIdentity();
17148            try {
17149                userInfo = sUserManager.getUserInfo(userId);
17150            } finally {
17151                Binder.restoreCallingIdentity(token);
17152            }
17153            final boolean b;
17154            if (userInfo != null && userInfo.isManagedProfile()) {
17155                b = true;
17156            } else {
17157                b = false;
17158            }
17159            mUserNeedsBadging.put(userId, b);
17160            return b;
17161        }
17162        return mUserNeedsBadging.valueAt(index);
17163    }
17164
17165    @Override
17166    public KeySet getKeySetByAlias(String packageName, String alias) {
17167        if (packageName == null || alias == null) {
17168            return null;
17169        }
17170        synchronized(mPackages) {
17171            final PackageParser.Package pkg = mPackages.get(packageName);
17172            if (pkg == null) {
17173                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17174                throw new IllegalArgumentException("Unknown package: " + packageName);
17175            }
17176            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17177            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17178        }
17179    }
17180
17181    @Override
17182    public KeySet getSigningKeySet(String packageName) {
17183        if (packageName == null) {
17184            return null;
17185        }
17186        synchronized(mPackages) {
17187            final PackageParser.Package pkg = mPackages.get(packageName);
17188            if (pkg == null) {
17189                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17190                throw new IllegalArgumentException("Unknown package: " + packageName);
17191            }
17192            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17193                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17194                throw new SecurityException("May not access signing KeySet of other apps.");
17195            }
17196            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17197            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17198        }
17199    }
17200
17201    @Override
17202    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17203        if (packageName == null || ks == null) {
17204            return false;
17205        }
17206        synchronized(mPackages) {
17207            final PackageParser.Package pkg = mPackages.get(packageName);
17208            if (pkg == null) {
17209                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17210                throw new IllegalArgumentException("Unknown package: " + packageName);
17211            }
17212            IBinder ksh = ks.getToken();
17213            if (ksh instanceof KeySetHandle) {
17214                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17215                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17216            }
17217            return false;
17218        }
17219    }
17220
17221    @Override
17222    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17223        if (packageName == null || ks == null) {
17224            return false;
17225        }
17226        synchronized(mPackages) {
17227            final PackageParser.Package pkg = mPackages.get(packageName);
17228            if (pkg == null) {
17229                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17230                throw new IllegalArgumentException("Unknown package: " + packageName);
17231            }
17232            IBinder ksh = ks.getToken();
17233            if (ksh instanceof KeySetHandle) {
17234                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17235                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17236            }
17237            return false;
17238        }
17239    }
17240
17241    private void deletePackageIfUnusedLPr(final String packageName) {
17242        PackageSetting ps = mSettings.mPackages.get(packageName);
17243        if (ps == null) {
17244            return;
17245        }
17246        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17247            // TODO Implement atomic delete if package is unused
17248            // It is currently possible that the package will be deleted even if it is installed
17249            // after this method returns.
17250            mHandler.post(new Runnable() {
17251                public void run() {
17252                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17253                }
17254            });
17255        }
17256    }
17257
17258    /**
17259     * Check and throw if the given before/after packages would be considered a
17260     * downgrade.
17261     */
17262    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17263            throws PackageManagerException {
17264        if (after.versionCode < before.mVersionCode) {
17265            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17266                    "Update version code " + after.versionCode + " is older than current "
17267                    + before.mVersionCode);
17268        } else if (after.versionCode == before.mVersionCode) {
17269            if (after.baseRevisionCode < before.baseRevisionCode) {
17270                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17271                        "Update base revision code " + after.baseRevisionCode
17272                        + " is older than current " + before.baseRevisionCode);
17273            }
17274
17275            if (!ArrayUtils.isEmpty(after.splitNames)) {
17276                for (int i = 0; i < after.splitNames.length; i++) {
17277                    final String splitName = after.splitNames[i];
17278                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17279                    if (j != -1) {
17280                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17281                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17282                                    "Update split " + splitName + " revision code "
17283                                    + after.splitRevisionCodes[i] + " is older than current "
17284                                    + before.splitRevisionCodes[j]);
17285                        }
17286                    }
17287                }
17288            }
17289        }
17290    }
17291
17292    private static class MoveCallbacks extends Handler {
17293        private static final int MSG_CREATED = 1;
17294        private static final int MSG_STATUS_CHANGED = 2;
17295
17296        private final RemoteCallbackList<IPackageMoveObserver>
17297                mCallbacks = new RemoteCallbackList<>();
17298
17299        private final SparseIntArray mLastStatus = new SparseIntArray();
17300
17301        public MoveCallbacks(Looper looper) {
17302            super(looper);
17303        }
17304
17305        public void register(IPackageMoveObserver callback) {
17306            mCallbacks.register(callback);
17307        }
17308
17309        public void unregister(IPackageMoveObserver callback) {
17310            mCallbacks.unregister(callback);
17311        }
17312
17313        @Override
17314        public void handleMessage(Message msg) {
17315            final SomeArgs args = (SomeArgs) msg.obj;
17316            final int n = mCallbacks.beginBroadcast();
17317            for (int i = 0; i < n; i++) {
17318                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17319                try {
17320                    invokeCallback(callback, msg.what, args);
17321                } catch (RemoteException ignored) {
17322                }
17323            }
17324            mCallbacks.finishBroadcast();
17325            args.recycle();
17326        }
17327
17328        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17329                throws RemoteException {
17330            switch (what) {
17331                case MSG_CREATED: {
17332                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17333                    break;
17334                }
17335                case MSG_STATUS_CHANGED: {
17336                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17337                    break;
17338                }
17339            }
17340        }
17341
17342        private void notifyCreated(int moveId, Bundle extras) {
17343            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17344
17345            final SomeArgs args = SomeArgs.obtain();
17346            args.argi1 = moveId;
17347            args.arg2 = extras;
17348            obtainMessage(MSG_CREATED, args).sendToTarget();
17349        }
17350
17351        private void notifyStatusChanged(int moveId, int status) {
17352            notifyStatusChanged(moveId, status, -1);
17353        }
17354
17355        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17356            Slog.v(TAG, "Move " + moveId + " status " + status);
17357
17358            final SomeArgs args = SomeArgs.obtain();
17359            args.argi1 = moveId;
17360            args.argi2 = status;
17361            args.arg3 = estMillis;
17362            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17363
17364            synchronized (mLastStatus) {
17365                mLastStatus.put(moveId, status);
17366            }
17367        }
17368    }
17369
17370    private final static class OnPermissionChangeListeners extends Handler {
17371        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17372
17373        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17374                new RemoteCallbackList<>();
17375
17376        public OnPermissionChangeListeners(Looper looper) {
17377            super(looper);
17378        }
17379
17380        @Override
17381        public void handleMessage(Message msg) {
17382            switch (msg.what) {
17383                case MSG_ON_PERMISSIONS_CHANGED: {
17384                    final int uid = msg.arg1;
17385                    handleOnPermissionsChanged(uid);
17386                } break;
17387            }
17388        }
17389
17390        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17391            mPermissionListeners.register(listener);
17392
17393        }
17394
17395        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17396            mPermissionListeners.unregister(listener);
17397        }
17398
17399        public void onPermissionsChanged(int uid) {
17400            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17401                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17402            }
17403        }
17404
17405        private void handleOnPermissionsChanged(int uid) {
17406            final int count = mPermissionListeners.beginBroadcast();
17407            try {
17408                for (int i = 0; i < count; i++) {
17409                    IOnPermissionsChangeListener callback = mPermissionListeners
17410                            .getBroadcastItem(i);
17411                    try {
17412                        callback.onPermissionsChanged(uid);
17413                    } catch (RemoteException e) {
17414                        Log.e(TAG, "Permission listener is dead", e);
17415                    }
17416                }
17417            } finally {
17418                mPermissionListeners.finishBroadcast();
17419            }
17420        }
17421    }
17422
17423    private class PackageManagerInternalImpl extends PackageManagerInternal {
17424        @Override
17425        public void setLocationPackagesProvider(PackagesProvider provider) {
17426            synchronized (mPackages) {
17427                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17428            }
17429        }
17430
17431        @Override
17432        public void setImePackagesProvider(PackagesProvider provider) {
17433            synchronized (mPackages) {
17434                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17435            }
17436        }
17437
17438        @Override
17439        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17440            synchronized (mPackages) {
17441                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17442            }
17443        }
17444
17445        @Override
17446        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17447            synchronized (mPackages) {
17448                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17449            }
17450        }
17451
17452        @Override
17453        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17454            synchronized (mPackages) {
17455                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17456            }
17457        }
17458
17459        @Override
17460        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17461            synchronized (mPackages) {
17462                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17463            }
17464        }
17465
17466        @Override
17467        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17468            synchronized (mPackages) {
17469                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17470            }
17471        }
17472
17473        @Override
17474        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17475            synchronized (mPackages) {
17476                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17477                        packageName, userId);
17478            }
17479        }
17480
17481        @Override
17482        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17483            synchronized (mPackages) {
17484                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17485                        packageName, userId);
17486            }
17487        }
17488
17489        @Override
17490        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17491            synchronized (mPackages) {
17492                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17493                        packageName, userId);
17494            }
17495        }
17496
17497        @Override
17498        public void setKeepUninstalledPackages(final List<String> packageList) {
17499            Preconditions.checkNotNull(packageList);
17500            List<String> removedFromList = null;
17501            synchronized (mPackages) {
17502                if (mKeepUninstalledPackages != null) {
17503                    final int packagesCount = mKeepUninstalledPackages.size();
17504                    for (int i = 0; i < packagesCount; i++) {
17505                        String oldPackage = mKeepUninstalledPackages.get(i);
17506                        if (packageList != null && packageList.contains(oldPackage)) {
17507                            continue;
17508                        }
17509                        if (removedFromList == null) {
17510                            removedFromList = new ArrayList<>();
17511                        }
17512                        removedFromList.add(oldPackage);
17513                    }
17514                }
17515                mKeepUninstalledPackages = new ArrayList<>(packageList);
17516                if (removedFromList != null) {
17517                    final int removedCount = removedFromList.size();
17518                    for (int i = 0; i < removedCount; i++) {
17519                        deletePackageIfUnusedLPr(removedFromList.get(i));
17520                    }
17521                }
17522            }
17523        }
17524
17525        @Override
17526        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17527            synchronized (mPackages) {
17528                // If we do not support permission review, done.
17529                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17530                    return false;
17531                }
17532
17533                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17534                if (packageSetting == null) {
17535                    return false;
17536                }
17537
17538                // Permission review applies only to apps not supporting the new permission model.
17539                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17540                    return false;
17541                }
17542
17543                // Legacy apps have the permission and get user consent on launch.
17544                PermissionsState permissionsState = packageSetting.getPermissionsState();
17545                return permissionsState.isPermissionReviewRequired(userId);
17546            }
17547        }
17548    }
17549
17550    @Override
17551    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17552        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17553        synchronized (mPackages) {
17554            final long identity = Binder.clearCallingIdentity();
17555            try {
17556                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17557                        packageNames, userId);
17558            } finally {
17559                Binder.restoreCallingIdentity(identity);
17560            }
17561        }
17562    }
17563
17564    private static void enforceSystemOrPhoneCaller(String tag) {
17565        int callingUid = Binder.getCallingUid();
17566        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17567            throw new SecurityException(
17568                    "Cannot call " + tag + " from UID " + callingUid);
17569        }
17570    }
17571}
17572