PackageManagerService.java revision 1990221c93499f3be64ba119c4c2def884df9cd9
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_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
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.text.TextUtils;
196import android.text.format.DateUtils;
197import android.util.ArrayMap;
198import android.util.ArraySet;
199import android.util.AtomicFile;
200import android.util.DisplayMetrics;
201import android.util.EventLog;
202import android.util.ExceptionUtils;
203import android.util.Log;
204import android.util.LogPrinter;
205import android.util.MathUtils;
206import android.util.PrintStreamPrinter;
207import android.util.Slog;
208import android.util.SparseArray;
209import android.util.SparseBooleanArray;
210import android.util.SparseIntArray;
211import android.util.Xml;
212import android.view.Display;
213
214import com.android.internal.R;
215import com.android.internal.annotations.GuardedBy;
216import com.android.internal.app.IMediaContainerService;
217import com.android.internal.app.ResolverActivity;
218import com.android.internal.content.NativeLibraryHelper;
219import com.android.internal.content.PackageHelper;
220import com.android.internal.os.IParcelFileDescriptorFactory;
221import com.android.internal.os.InstallerConnection.InstallerException;
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.internal.util.XmlUtils;
230import com.android.server.EventLogTags;
231import com.android.server.FgThread;
232import com.android.server.IntentResolver;
233import com.android.server.LocalServices;
234import com.android.server.ServiceThread;
235import com.android.server.SystemConfig;
236import com.android.server.Watchdog;
237import com.android.server.pm.Installer.StorageFlags;
238import com.android.server.pm.PermissionsState.PermissionState;
239import com.android.server.pm.Settings.DatabaseVersion;
240import com.android.server.pm.Settings.VersionInfo;
241import com.android.server.storage.DeviceStorageMonitorInternal;
242
243import dalvik.system.DexFile;
244import dalvik.system.VMRuntime;
245
246import libcore.io.IoUtils;
247import libcore.util.EmptyArray;
248
249import org.xmlpull.v1.XmlPullParser;
250import org.xmlpull.v1.XmlPullParserException;
251import org.xmlpull.v1.XmlSerializer;
252
253import java.io.BufferedInputStream;
254import java.io.BufferedOutputStream;
255import java.io.BufferedReader;
256import java.io.ByteArrayInputStream;
257import java.io.ByteArrayOutputStream;
258import java.io.File;
259import java.io.FileDescriptor;
260import java.io.FileNotFoundException;
261import java.io.FileOutputStream;
262import java.io.FileReader;
263import java.io.FilenameFilter;
264import java.io.IOException;
265import java.io.InputStream;
266import java.io.PrintWriter;
267import java.nio.charset.StandardCharsets;
268import java.security.MessageDigest;
269import java.security.NoSuchAlgorithmException;
270import java.security.PublicKey;
271import java.security.cert.CertificateEncodingException;
272import java.security.cert.CertificateException;
273import java.text.SimpleDateFormat;
274import java.util.ArrayList;
275import java.util.Arrays;
276import java.util.Collection;
277import java.util.Collections;
278import java.util.Comparator;
279import java.util.Date;
280import java.util.Iterator;
281import java.util.List;
282import java.util.Map;
283import java.util.Objects;
284import java.util.Set;
285import java.util.concurrent.CountDownLatch;
286import java.util.concurrent.TimeUnit;
287import java.util.concurrent.atomic.AtomicBoolean;
288import java.util.concurrent.atomic.AtomicInteger;
289import java.util.concurrent.atomic.AtomicLong;
290
291/**
292 * Keep track of all those .apks everywhere.
293 *
294 * This is very central to the platform's security; please run the unit
295 * tests whenever making modifications here:
296 *
297runtest -c android.content.pm.PackageManagerTests frameworks-core
298 *
299 * {@hide}
300 */
301public class PackageManagerService extends IPackageManager.Stub {
302    static final String TAG = "PackageManager";
303    static final boolean DEBUG_SETTINGS = false;
304    static final boolean DEBUG_PREFERRED = false;
305    static final boolean DEBUG_UPGRADE = false;
306    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
307    private static final boolean DEBUG_BACKUP = false;
308    private static final boolean DEBUG_INSTALL = false;
309    private static final boolean DEBUG_REMOVE = false;
310    private static final boolean DEBUG_BROADCASTS = false;
311    private static final boolean DEBUG_SHOW_INFO = false;
312    private static final boolean DEBUG_PACKAGE_INFO = false;
313    private static final boolean DEBUG_INTENT_MATCHING = false;
314    private static final boolean DEBUG_PACKAGE_SCANNING = false;
315    private static final boolean DEBUG_VERIFY = false;
316    private static final boolean DEBUG_DEXOPT = false;
317    private static final boolean DEBUG_ABI_SELECTION = false;
318    private static final boolean DEBUG_EPHEMERAL = false;
319    private static final boolean DEBUG_TRIAGED_MISSING = false;
320    private static final boolean DEBUG_APP_DATA = false;
321
322    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
323
324    private static final boolean DISABLE_EPHEMERAL_APPS = true;
325
326    private static final int RADIO_UID = Process.PHONE_UID;
327    private static final int LOG_UID = Process.LOG_UID;
328    private static final int NFC_UID = Process.NFC_UID;
329    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
330    private static final int SHELL_UID = Process.SHELL_UID;
331
332    // Cap the size of permission trees that 3rd party apps can define
333    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
334
335    // Suffix used during package installation when copying/moving
336    // package apks to install directory.
337    private static final String INSTALL_PACKAGE_SUFFIX = "-";
338
339    static final int SCAN_NO_DEX = 1<<1;
340    static final int SCAN_FORCE_DEX = 1<<2;
341    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
342    static final int SCAN_NEW_INSTALL = 1<<4;
343    static final int SCAN_NO_PATHS = 1<<5;
344    static final int SCAN_UPDATE_TIME = 1<<6;
345    static final int SCAN_DEFER_DEX = 1<<7;
346    static final int SCAN_BOOTING = 1<<8;
347    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
348    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
349    static final int SCAN_REPLACING = 1<<11;
350    static final int SCAN_REQUIRE_KNOWN = 1<<12;
351    static final int SCAN_MOVE = 1<<13;
352    static final int SCAN_INITIAL = 1<<14;
353
354    static final int REMOVE_CHATTY = 1<<16;
355
356    private static final int[] EMPTY_INT_ARRAY = new int[0];
357
358    /**
359     * Timeout (in milliseconds) after which the watchdog should declare that
360     * our handler thread is wedged.  The usual default for such things is one
361     * minute but we sometimes do very lengthy I/O operations on this thread,
362     * such as installing multi-gigabyte applications, so ours needs to be longer.
363     */
364    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
365
366    /**
367     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
368     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
369     * settings entry if available, otherwise we use the hardcoded default.  If it's been
370     * more than this long since the last fstrim, we force one during the boot sequence.
371     *
372     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
373     * one gets run at the next available charging+idle time.  This final mandatory
374     * no-fstrim check kicks in only of the other scheduling criteria is never met.
375     */
376    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
377
378    /**
379     * Whether verification is enabled by default.
380     */
381    private static final boolean DEFAULT_VERIFY_ENABLE = true;
382
383    /**
384     * The default maximum time to wait for the verification agent to return in
385     * milliseconds.
386     */
387    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
388
389    /**
390     * The default response for package verification timeout.
391     *
392     * This can be either PackageManager.VERIFICATION_ALLOW or
393     * PackageManager.VERIFICATION_REJECT.
394     */
395    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
396
397    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
398
399    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
400            DEFAULT_CONTAINER_PACKAGE,
401            "com.android.defcontainer.DefaultContainerService");
402
403    private static final String KILL_APP_REASON_GIDS_CHANGED =
404            "permission grant or revoke changed gids";
405
406    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
407            "permissions revoked";
408
409    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
410
411    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
412
413    /** Permission grant: not grant the permission. */
414    private static final int GRANT_DENIED = 1;
415
416    /** Permission grant: grant the permission as an install permission. */
417    private static final int GRANT_INSTALL = 2;
418
419    /** Permission grant: grant the permission as a runtime one. */
420    private static final int GRANT_RUNTIME = 3;
421
422    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
423    private static final int GRANT_UPGRADE = 4;
424
425    /** Canonical intent used to identify what counts as a "web browser" app */
426    private static final Intent sBrowserIntent;
427    static {
428        sBrowserIntent = new Intent();
429        sBrowserIntent.setAction(Intent.ACTION_VIEW);
430        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
431        sBrowserIntent.setData(Uri.parse("http:"));
432    }
433
434    final ServiceThread mHandlerThread;
435
436    final PackageHandler mHandler;
437
438    /**
439     * Messages for {@link #mHandler} that need to wait for system ready before
440     * being dispatched.
441     */
442    private ArrayList<Message> mPostSystemReadyMessages;
443
444    final int mSdkVersion = Build.VERSION.SDK_INT;
445
446    final Context mContext;
447    final boolean mFactoryTest;
448    final boolean mOnlyCore;
449    final DisplayMetrics mMetrics;
450    final int mDefParseFlags;
451    final String[] mSeparateProcesses;
452    final boolean mIsUpgrade;
453
454    /** The location for ASEC container files on internal storage. */
455    final String mAsecInternalPath;
456
457    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
458    // LOCK HELD.  Can be called with mInstallLock held.
459    @GuardedBy("mInstallLock")
460    final Installer mInstaller;
461
462    /** Directory where installed third-party apps stored */
463    final File mAppInstallDir;
464    final File mEphemeralInstallDir;
465
466    /**
467     * Directory to which applications installed internally have their
468     * 32 bit native libraries copied.
469     */
470    private File mAppLib32InstallDir;
471
472    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
473    // apps.
474    final File mDrmAppPrivateInstallDir;
475
476    // ----------------------------------------------------------------
477
478    // Lock for state used when installing and doing other long running
479    // operations.  Methods that must be called with this lock held have
480    // the suffix "LI".
481    final Object mInstallLock = new Object();
482
483    // ----------------------------------------------------------------
484
485    // Keys are String (package name), values are Package.  This also serves
486    // as the lock for the global state.  Methods that must be called with
487    // this lock held have the prefix "LP".
488    @GuardedBy("mPackages")
489    final ArrayMap<String, PackageParser.Package> mPackages =
490            new ArrayMap<String, PackageParser.Package>();
491
492    // Tracks available target package names -> overlay package paths.
493    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
494        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
495
496    /**
497     * Tracks new system packages [received in an OTA] that we expect to
498     * find updated user-installed versions. Keys are package name, values
499     * are package location.
500     */
501    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
502
503    /**
504     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
505     */
506    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
507    /**
508     * Whether or not system app permissions should be promoted from install to runtime.
509     */
510    boolean mPromoteSystemApps;
511
512    final Settings mSettings;
513    boolean mRestoredSettings;
514
515    // System configuration read by SystemConfig.
516    final int[] mGlobalGids;
517    final SparseArray<ArraySet<String>> mSystemPermissions;
518    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
519
520    // If mac_permissions.xml was found for seinfo labeling.
521    boolean mFoundPolicyFile;
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 boolean mUseJitProfiles =
633            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
634
635    private static class IFVerificationParams {
636        PackageParser.Package pkg;
637        boolean replacing;
638        int userId;
639        int verifierUid;
640
641        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
642                int _userId, int _verifierUid) {
643            pkg = _pkg;
644            replacing = _replacing;
645            userId = _userId;
646            replacing = _replacing;
647            verifierUid = _verifierUid;
648        }
649    }
650
651    private interface IntentFilterVerifier<T extends IntentFilter> {
652        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
653                                               T filter, String packageName);
654        void startVerifications(int userId);
655        void receiveVerificationResponse(int verificationId);
656    }
657
658    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
659        private Context mContext;
660        private ComponentName mIntentFilterVerifierComponent;
661        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
662
663        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
664            mContext = context;
665            mIntentFilterVerifierComponent = verifierComponent;
666        }
667
668        private String getDefaultScheme() {
669            return IntentFilter.SCHEME_HTTPS;
670        }
671
672        @Override
673        public void startVerifications(int userId) {
674            // Launch verifications requests
675            int count = mCurrentIntentFilterVerifications.size();
676            for (int n=0; n<count; n++) {
677                int verificationId = mCurrentIntentFilterVerifications.get(n);
678                final IntentFilterVerificationState ivs =
679                        mIntentFilterVerificationStates.get(verificationId);
680
681                String packageName = ivs.getPackageName();
682
683                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
684                final int filterCount = filters.size();
685                ArraySet<String> domainsSet = new ArraySet<>();
686                for (int m=0; m<filterCount; m++) {
687                    PackageParser.ActivityIntentInfo filter = filters.get(m);
688                    domainsSet.addAll(filter.getHostsList());
689                }
690                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
691                synchronized (mPackages) {
692                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
693                            packageName, domainsList) != null) {
694                        scheduleWriteSettingsLocked();
695                    }
696                }
697                sendVerificationRequest(userId, verificationId, ivs);
698            }
699            mCurrentIntentFilterVerifications.clear();
700        }
701
702        private void sendVerificationRequest(int userId, int verificationId,
703                IntentFilterVerificationState ivs) {
704
705            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
706            verificationIntent.putExtra(
707                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
708                    verificationId);
709            verificationIntent.putExtra(
710                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
711                    getDefaultScheme());
712            verificationIntent.putExtra(
713                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
714                    ivs.getHostsString());
715            verificationIntent.putExtra(
716                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
717                    ivs.getPackageName());
718            verificationIntent.setComponent(mIntentFilterVerifierComponent);
719            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
720
721            UserHandle user = new UserHandle(userId);
722            mContext.sendBroadcastAsUser(verificationIntent, user);
723            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
724                    "Sending IntentFilter verification broadcast");
725        }
726
727        public void receiveVerificationResponse(int verificationId) {
728            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
729
730            final boolean verified = ivs.isVerified();
731
732            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
733            final int count = filters.size();
734            if (DEBUG_DOMAIN_VERIFICATION) {
735                Slog.i(TAG, "Received verification response " + verificationId
736                        + " for " + count + " filters, verified=" + verified);
737            }
738            for (int n=0; n<count; n++) {
739                PackageParser.ActivityIntentInfo filter = filters.get(n);
740                filter.setVerified(verified);
741
742                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
743                        + " verified with result:" + verified + " and hosts:"
744                        + ivs.getHostsString());
745            }
746
747            mIntentFilterVerificationStates.remove(verificationId);
748
749            final String packageName = ivs.getPackageName();
750            IntentFilterVerificationInfo ivi = null;
751
752            synchronized (mPackages) {
753                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
754            }
755            if (ivi == null) {
756                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
757                        + verificationId + " packageName:" + packageName);
758                return;
759            }
760            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
761                    "Updating IntentFilterVerificationInfo for package " + packageName
762                            +" verificationId:" + verificationId);
763
764            synchronized (mPackages) {
765                if (verified) {
766                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
767                } else {
768                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
769                }
770                scheduleWriteSettingsLocked();
771
772                final int userId = ivs.getUserId();
773                if (userId != UserHandle.USER_ALL) {
774                    final int userStatus =
775                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
776
777                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
778                    boolean needUpdate = false;
779
780                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
781                    // already been set by the User thru the Disambiguation dialog
782                    switch (userStatus) {
783                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
784                            if (verified) {
785                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
786                            } else {
787                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
788                            }
789                            needUpdate = true;
790                            break;
791
792                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
793                            if (verified) {
794                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
795                                needUpdate = true;
796                            }
797                            break;
798
799                        default:
800                            // Nothing to do
801                    }
802
803                    if (needUpdate) {
804                        mSettings.updateIntentFilterVerificationStatusLPw(
805                                packageName, updatedStatus, userId);
806                        scheduleWritePackageRestrictionsLocked(userId);
807                    }
808                }
809            }
810        }
811
812        @Override
813        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
814                    ActivityIntentInfo filter, String packageName) {
815            if (!hasValidDomains(filter)) {
816                return false;
817            }
818            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
819            if (ivs == null) {
820                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
821                        packageName);
822            }
823            if (DEBUG_DOMAIN_VERIFICATION) {
824                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
825            }
826            ivs.addFilter(filter);
827            return true;
828        }
829
830        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
831                int userId, int verificationId, String packageName) {
832            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
833                    verifierUid, userId, packageName);
834            ivs.setPendingState();
835            synchronized (mPackages) {
836                mIntentFilterVerificationStates.append(verificationId, ivs);
837                mCurrentIntentFilterVerifications.add(verificationId);
838            }
839            return ivs;
840        }
841    }
842
843    private static boolean hasValidDomains(ActivityIntentInfo filter) {
844        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
845                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
846                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
847    }
848
849    // Set of pending broadcasts for aggregating enable/disable of components.
850    static class PendingPackageBroadcasts {
851        // for each user id, a map of <package name -> components within that package>
852        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
853
854        public PendingPackageBroadcasts() {
855            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
856        }
857
858        public ArrayList<String> get(int userId, String packageName) {
859            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
860            return packages.get(packageName);
861        }
862
863        public void put(int userId, String packageName, ArrayList<String> components) {
864            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
865            packages.put(packageName, components);
866        }
867
868        public void remove(int userId, String packageName) {
869            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
870            if (packages != null) {
871                packages.remove(packageName);
872            }
873        }
874
875        public void remove(int userId) {
876            mUidMap.remove(userId);
877        }
878
879        public int userIdCount() {
880            return mUidMap.size();
881        }
882
883        public int userIdAt(int n) {
884            return mUidMap.keyAt(n);
885        }
886
887        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
888            return mUidMap.get(userId);
889        }
890
891        public int size() {
892            // total number of pending broadcast entries across all userIds
893            int num = 0;
894            for (int i = 0; i< mUidMap.size(); i++) {
895                num += mUidMap.valueAt(i).size();
896            }
897            return num;
898        }
899
900        public void clear() {
901            mUidMap.clear();
902        }
903
904        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
905            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
906            if (map == null) {
907                map = new ArrayMap<String, ArrayList<String>>();
908                mUidMap.put(userId, map);
909            }
910            return map;
911        }
912    }
913    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
914
915    // Service Connection to remote media container service to copy
916    // package uri's from external media onto secure containers
917    // or internal storage.
918    private IMediaContainerService mContainerService = null;
919
920    static final int SEND_PENDING_BROADCAST = 1;
921    static final int MCS_BOUND = 3;
922    static final int END_COPY = 4;
923    static final int INIT_COPY = 5;
924    static final int MCS_UNBIND = 6;
925    static final int START_CLEANING_PACKAGE = 7;
926    static final int FIND_INSTALL_LOC = 8;
927    static final int POST_INSTALL = 9;
928    static final int MCS_RECONNECT = 10;
929    static final int MCS_GIVE_UP = 11;
930    static final int UPDATED_MEDIA_STATUS = 12;
931    static final int WRITE_SETTINGS = 13;
932    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
933    static final int PACKAGE_VERIFIED = 15;
934    static final int CHECK_PENDING_VERIFICATION = 16;
935    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
936    static final int INTENT_FILTER_VERIFIED = 18;
937
938    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
939
940    // Delay time in millisecs
941    static final int BROADCAST_DELAY = 10 * 1000;
942
943    static UserManagerService sUserManager;
944
945    // Stores a list of users whose package restrictions file needs to be updated
946    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
947
948    final private DefaultContainerConnection mDefContainerConn =
949            new DefaultContainerConnection();
950    class DefaultContainerConnection implements ServiceConnection {
951        public void onServiceConnected(ComponentName name, IBinder service) {
952            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
953            IMediaContainerService imcs =
954                IMediaContainerService.Stub.asInterface(service);
955            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
956        }
957
958        public void onServiceDisconnected(ComponentName name) {
959            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
960        }
961    }
962
963    // Recordkeeping of restore-after-install operations that are currently in flight
964    // between the Package Manager and the Backup Manager
965    static class PostInstallData {
966        public InstallArgs args;
967        public PackageInstalledInfo res;
968
969        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
970            args = _a;
971            res = _r;
972        }
973    }
974
975    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
976    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
977
978    // XML tags for backup/restore of various bits of state
979    private static final String TAG_PREFERRED_BACKUP = "pa";
980    private static final String TAG_DEFAULT_APPS = "da";
981    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
982
983    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
984    private static final String TAG_ALL_GRANTS = "rt-grants";
985    private static final String TAG_GRANT = "grant";
986    private static final String ATTR_PACKAGE_NAME = "pkg";
987
988    private static final String TAG_PERMISSION = "perm";
989    private static final String ATTR_PERMISSION_NAME = "name";
990    private static final String ATTR_IS_GRANTED = "g";
991    private static final String ATTR_USER_SET = "set";
992    private static final String ATTR_USER_FIXED = "fixed";
993    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
994
995    // System/policy permission grants are not backed up
996    private static final int SYSTEM_RUNTIME_GRANT_MASK =
997            FLAG_PERMISSION_POLICY_FIXED
998            | FLAG_PERMISSION_SYSTEM_FIXED
999            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1000
1001    // And we back up these user-adjusted states
1002    private static final int USER_RUNTIME_GRANT_MASK =
1003            FLAG_PERMISSION_USER_SET
1004            | FLAG_PERMISSION_USER_FIXED
1005            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1006
1007    final @Nullable String mRequiredVerifierPackage;
1008    final @Nullable String mRequiredInstallerPackage;
1009
1010    private final PackageUsage mPackageUsage = new PackageUsage();
1011
1012    private class PackageUsage {
1013        private static final int WRITE_INTERVAL
1014            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1015
1016        private final Object mFileLock = new Object();
1017        private final AtomicLong mLastWritten = new AtomicLong(0);
1018        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1019
1020        private boolean mIsHistoricalPackageUsageAvailable = true;
1021
1022        boolean isHistoricalPackageUsageAvailable() {
1023            return mIsHistoricalPackageUsageAvailable;
1024        }
1025
1026        void write(boolean force) {
1027            if (force) {
1028                writeInternal();
1029                return;
1030            }
1031            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1032                && !DEBUG_DEXOPT) {
1033                return;
1034            }
1035            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1036                new Thread("PackageUsage_DiskWriter") {
1037                    @Override
1038                    public void run() {
1039                        try {
1040                            writeInternal();
1041                        } finally {
1042                            mBackgroundWriteRunning.set(false);
1043                        }
1044                    }
1045                }.start();
1046            }
1047        }
1048
1049        private void writeInternal() {
1050            synchronized (mPackages) {
1051                synchronized (mFileLock) {
1052                    AtomicFile file = getFile();
1053                    FileOutputStream f = null;
1054                    try {
1055                        f = file.startWrite();
1056                        BufferedOutputStream out = new BufferedOutputStream(f);
1057                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1058                        StringBuilder sb = new StringBuilder();
1059                        for (PackageParser.Package pkg : mPackages.values()) {
1060                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1061                                continue;
1062                            }
1063                            sb.setLength(0);
1064                            sb.append(pkg.packageName);
1065                            sb.append(' ');
1066                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1067                            sb.append('\n');
1068                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1069                        }
1070                        out.flush();
1071                        file.finishWrite(f);
1072                    } catch (IOException e) {
1073                        if (f != null) {
1074                            file.failWrite(f);
1075                        }
1076                        Log.e(TAG, "Failed to write package usage times", e);
1077                    }
1078                }
1079            }
1080            mLastWritten.set(SystemClock.elapsedRealtime());
1081        }
1082
1083        void readLP() {
1084            synchronized (mFileLock) {
1085                AtomicFile file = getFile();
1086                BufferedInputStream in = null;
1087                try {
1088                    in = new BufferedInputStream(file.openRead());
1089                    StringBuffer sb = new StringBuffer();
1090                    while (true) {
1091                        String packageName = readToken(in, sb, ' ');
1092                        if (packageName == null) {
1093                            break;
1094                        }
1095                        String timeInMillisString = readToken(in, sb, '\n');
1096                        if (timeInMillisString == null) {
1097                            throw new IOException("Failed to find last usage time for package "
1098                                                  + packageName);
1099                        }
1100                        PackageParser.Package pkg = mPackages.get(packageName);
1101                        if (pkg == null) {
1102                            continue;
1103                        }
1104                        long timeInMillis;
1105                        try {
1106                            timeInMillis = Long.parseLong(timeInMillisString);
1107                        } catch (NumberFormatException e) {
1108                            throw new IOException("Failed to parse " + timeInMillisString
1109                                                  + " as a long.", e);
1110                        }
1111                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1112                    }
1113                } catch (FileNotFoundException expected) {
1114                    mIsHistoricalPackageUsageAvailable = false;
1115                } catch (IOException e) {
1116                    Log.w(TAG, "Failed to read package usage times", e);
1117                } finally {
1118                    IoUtils.closeQuietly(in);
1119                }
1120            }
1121            mLastWritten.set(SystemClock.elapsedRealtime());
1122        }
1123
1124        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1125                throws IOException {
1126            sb.setLength(0);
1127            while (true) {
1128                int ch = in.read();
1129                if (ch == -1) {
1130                    if (sb.length() == 0) {
1131                        return null;
1132                    }
1133                    throw new IOException("Unexpected EOF");
1134                }
1135                if (ch == endOfToken) {
1136                    return sb.toString();
1137                }
1138                sb.append((char)ch);
1139            }
1140        }
1141
1142        private AtomicFile getFile() {
1143            File dataDir = Environment.getDataDirectory();
1144            File systemDir = new File(dataDir, "system");
1145            File fname = new File(systemDir, "package-usage.list");
1146            return new AtomicFile(fname);
1147        }
1148    }
1149
1150    class PackageHandler extends Handler {
1151        private boolean mBound = false;
1152        final ArrayList<HandlerParams> mPendingInstalls =
1153            new ArrayList<HandlerParams>();
1154
1155        private boolean connectToService() {
1156            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1157                    " DefaultContainerService");
1158            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1159            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1160            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1161                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1162                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1163                mBound = true;
1164                return true;
1165            }
1166            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1167            return false;
1168        }
1169
1170        private void disconnectService() {
1171            mContainerService = null;
1172            mBound = false;
1173            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1174            mContext.unbindService(mDefContainerConn);
1175            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1176        }
1177
1178        PackageHandler(Looper looper) {
1179            super(looper);
1180        }
1181
1182        public void handleMessage(Message msg) {
1183            try {
1184                doHandleMessage(msg);
1185            } finally {
1186                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1187            }
1188        }
1189
1190        void doHandleMessage(Message msg) {
1191            switch (msg.what) {
1192                case INIT_COPY: {
1193                    HandlerParams params = (HandlerParams) msg.obj;
1194                    int idx = mPendingInstalls.size();
1195                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1196                    // If a bind was already initiated we dont really
1197                    // need to do anything. The pending install
1198                    // will be processed later on.
1199                    if (!mBound) {
1200                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1201                                System.identityHashCode(mHandler));
1202                        // If this is the only one pending we might
1203                        // have to bind to the service again.
1204                        if (!connectToService()) {
1205                            Slog.e(TAG, "Failed to bind to media container service");
1206                            params.serviceError();
1207                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1208                                    System.identityHashCode(mHandler));
1209                            if (params.traceMethod != null) {
1210                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1211                                        params.traceCookie);
1212                            }
1213                            return;
1214                        } else {
1215                            // Once we bind to the service, the first
1216                            // pending request will be processed.
1217                            mPendingInstalls.add(idx, params);
1218                        }
1219                    } else {
1220                        mPendingInstalls.add(idx, params);
1221                        // Already bound to the service. Just make
1222                        // sure we trigger off processing the first request.
1223                        if (idx == 0) {
1224                            mHandler.sendEmptyMessage(MCS_BOUND);
1225                        }
1226                    }
1227                    break;
1228                }
1229                case MCS_BOUND: {
1230                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1231                    if (msg.obj != null) {
1232                        mContainerService = (IMediaContainerService) msg.obj;
1233                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1234                                System.identityHashCode(mHandler));
1235                    }
1236                    if (mContainerService == null) {
1237                        if (!mBound) {
1238                            // Something seriously wrong since we are not bound and we are not
1239                            // waiting for connection. Bail out.
1240                            Slog.e(TAG, "Cannot bind to media container service");
1241                            for (HandlerParams params : mPendingInstalls) {
1242                                // Indicate service bind error
1243                                params.serviceError();
1244                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1245                                        System.identityHashCode(params));
1246                                if (params.traceMethod != null) {
1247                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1248                                            params.traceMethod, params.traceCookie);
1249                                }
1250                                return;
1251                            }
1252                            mPendingInstalls.clear();
1253                        } else {
1254                            Slog.w(TAG, "Waiting to connect to media container service");
1255                        }
1256                    } else if (mPendingInstalls.size() > 0) {
1257                        HandlerParams params = mPendingInstalls.get(0);
1258                        if (params != null) {
1259                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1260                                    System.identityHashCode(params));
1261                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1262                            if (params.startCopy()) {
1263                                // We are done...  look for more work or to
1264                                // go idle.
1265                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1266                                        "Checking for more work or unbind...");
1267                                // Delete pending install
1268                                if (mPendingInstalls.size() > 0) {
1269                                    mPendingInstalls.remove(0);
1270                                }
1271                                if (mPendingInstalls.size() == 0) {
1272                                    if (mBound) {
1273                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1274                                                "Posting delayed MCS_UNBIND");
1275                                        removeMessages(MCS_UNBIND);
1276                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1277                                        // Unbind after a little delay, to avoid
1278                                        // continual thrashing.
1279                                        sendMessageDelayed(ubmsg, 10000);
1280                                    }
1281                                } else {
1282                                    // There are more pending requests in queue.
1283                                    // Just post MCS_BOUND message to trigger processing
1284                                    // of next pending install.
1285                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1286                                            "Posting MCS_BOUND for next work");
1287                                    mHandler.sendEmptyMessage(MCS_BOUND);
1288                                }
1289                            }
1290                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1291                        }
1292                    } else {
1293                        // Should never happen ideally.
1294                        Slog.w(TAG, "Empty queue");
1295                    }
1296                    break;
1297                }
1298                case MCS_RECONNECT: {
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1300                    if (mPendingInstalls.size() > 0) {
1301                        if (mBound) {
1302                            disconnectService();
1303                        }
1304                        if (!connectToService()) {
1305                            Slog.e(TAG, "Failed to bind to media container service");
1306                            for (HandlerParams params : mPendingInstalls) {
1307                                // Indicate service bind error
1308                                params.serviceError();
1309                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1310                                        System.identityHashCode(params));
1311                            }
1312                            mPendingInstalls.clear();
1313                        }
1314                    }
1315                    break;
1316                }
1317                case MCS_UNBIND: {
1318                    // If there is no actual work left, then time to unbind.
1319                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1320
1321                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1322                        if (mBound) {
1323                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1324
1325                            disconnectService();
1326                        }
1327                    } else if (mPendingInstalls.size() > 0) {
1328                        // There are more pending requests in queue.
1329                        // Just post MCS_BOUND message to trigger processing
1330                        // of next pending install.
1331                        mHandler.sendEmptyMessage(MCS_BOUND);
1332                    }
1333
1334                    break;
1335                }
1336                case MCS_GIVE_UP: {
1337                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1338                    HandlerParams params = mPendingInstalls.remove(0);
1339                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1340                            System.identityHashCode(params));
1341                    break;
1342                }
1343                case SEND_PENDING_BROADCAST: {
1344                    String packages[];
1345                    ArrayList<String> components[];
1346                    int size = 0;
1347                    int uids[];
1348                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1349                    synchronized (mPackages) {
1350                        if (mPendingBroadcasts == null) {
1351                            return;
1352                        }
1353                        size = mPendingBroadcasts.size();
1354                        if (size <= 0) {
1355                            // Nothing to be done. Just return
1356                            return;
1357                        }
1358                        packages = new String[size];
1359                        components = new ArrayList[size];
1360                        uids = new int[size];
1361                        int i = 0;  // filling out the above arrays
1362
1363                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1364                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1365                            Iterator<Map.Entry<String, ArrayList<String>>> it
1366                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1367                                            .entrySet().iterator();
1368                            while (it.hasNext() && i < size) {
1369                                Map.Entry<String, ArrayList<String>> ent = it.next();
1370                                packages[i] = ent.getKey();
1371                                components[i] = ent.getValue();
1372                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1373                                uids[i] = (ps != null)
1374                                        ? UserHandle.getUid(packageUserId, ps.appId)
1375                                        : -1;
1376                                i++;
1377                            }
1378                        }
1379                        size = i;
1380                        mPendingBroadcasts.clear();
1381                    }
1382                    // Send broadcasts
1383                    for (int i = 0; i < size; i++) {
1384                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1385                    }
1386                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387                    break;
1388                }
1389                case START_CLEANING_PACKAGE: {
1390                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1391                    final String packageName = (String)msg.obj;
1392                    final int userId = msg.arg1;
1393                    final boolean andCode = msg.arg2 != 0;
1394                    synchronized (mPackages) {
1395                        if (userId == UserHandle.USER_ALL) {
1396                            int[] users = sUserManager.getUserIds();
1397                            for (int user : users) {
1398                                mSettings.addPackageToCleanLPw(
1399                                        new PackageCleanItem(user, packageName, andCode));
1400                            }
1401                        } else {
1402                            mSettings.addPackageToCleanLPw(
1403                                    new PackageCleanItem(userId, packageName, andCode));
1404                        }
1405                    }
1406                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1407                    startCleaningPackages();
1408                } break;
1409                case POST_INSTALL: {
1410                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1411
1412                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1413                    mRunningInstalls.delete(msg.arg1);
1414                    boolean deleteOld = false;
1415
1416                    if (data != null) {
1417                        InstallArgs args = data.args;
1418                        PackageInstalledInfo res = data.res;
1419
1420                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1421                            final String packageName = res.pkg.applicationInfo.packageName;
1422                            res.removedInfo.sendBroadcast(false, true, false);
1423                            Bundle extras = new Bundle(1);
1424                            extras.putInt(Intent.EXTRA_UID, res.uid);
1425
1426                            // Now that we successfully installed the package, grant runtime
1427                            // permissions if requested before broadcasting the install.
1428                            if ((args.installFlags
1429                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1430                                    && res.pkg.applicationInfo.targetSdkVersion
1431                                            >= Build.VERSION_CODES.M) {
1432                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1433                                        args.installGrantPermissions);
1434                            }
1435
1436                            synchronized (mPackages) {
1437                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1438                            }
1439
1440                            // Determine the set of users who are adding this
1441                            // package for the first time vs. those who are seeing
1442                            // an update.
1443                            int[] firstUsers;
1444                            int[] updateUsers = new int[0];
1445                            if (res.origUsers == null || res.origUsers.length == 0) {
1446                                firstUsers = res.newUsers;
1447                            } else {
1448                                firstUsers = new int[0];
1449                                for (int i=0; i<res.newUsers.length; i++) {
1450                                    int user = res.newUsers[i];
1451                                    boolean isNew = true;
1452                                    for (int j=0; j<res.origUsers.length; j++) {
1453                                        if (res.origUsers[j] == user) {
1454                                            isNew = false;
1455                                            break;
1456                                        }
1457                                    }
1458                                    if (isNew) {
1459                                        int[] newFirst = new int[firstUsers.length+1];
1460                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1461                                                firstUsers.length);
1462                                        newFirst[firstUsers.length] = user;
1463                                        firstUsers = newFirst;
1464                                    } else {
1465                                        int[] newUpdate = new int[updateUsers.length+1];
1466                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1467                                                updateUsers.length);
1468                                        newUpdate[updateUsers.length] = user;
1469                                        updateUsers = newUpdate;
1470                                    }
1471                                }
1472                            }
1473                            // don't broadcast for ephemeral installs/updates
1474                            final boolean isEphemeral = isEphemeral(res.pkg);
1475                            if (!isEphemeral) {
1476                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1477                                        extras, 0 /*flags*/, null /*targetPackage*/,
1478                                        null /*finishedReceiver*/, firstUsers);
1479                            }
1480                            final boolean update = res.removedInfo.removedPackage != null;
1481                            if (update) {
1482                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1483                            }
1484                            if (!isEphemeral) {
1485                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1486                                        extras, 0 /*flags*/, null /*targetPackage*/,
1487                                        null /*finishedReceiver*/, updateUsers);
1488                            }
1489                            if (update) {
1490                                if (!isEphemeral) {
1491                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1492                                            packageName, extras, 0 /*flags*/,
1493                                            null /*targetPackage*/, null /*finishedReceiver*/,
1494                                            updateUsers);
1495                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1496                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1497                                            packageName /*targetPackage*/,
1498                                            null /*finishedReceiver*/, updateUsers);
1499                                }
1500
1501                                // treat asec-hosted packages like removable media on upgrade
1502                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1503                                    if (DEBUG_INSTALL) {
1504                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1505                                                + " is ASEC-hosted -> AVAILABLE");
1506                                    }
1507                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1508                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1509                                    pkgList.add(packageName);
1510                                    sendResourcesChangedBroadcast(true, true,
1511                                            pkgList,uidArray, null);
1512                                }
1513                            }
1514                            if (res.removedInfo.args != null) {
1515                                // Remove the replaced package's older resources safely now
1516                                deleteOld = true;
1517                            }
1518
1519
1520                            // Work that needs to happen on first install within each user
1521                            if (firstUsers.length > 0) {
1522                                for (int userId : firstUsers) {
1523                                    synchronized (mPackages) {
1524                                        // If this app is a browser and it's newly-installed for
1525                                        // some users, clear any default-browser state in those
1526                                        // users.  The app's nature doesn't depend on the user,
1527                                        // so we can just check its browser nature in any user
1528                                        // and generalize.
1529                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1530                                            mSettings.setDefaultBrowserPackageNameLPw(
1531                                                    null, userId);
1532                                        }
1533
1534                                        // We may also need to apply pending (restored) runtime
1535                                        // permission grants within these users.
1536                                        mSettings.applyPendingPermissionGrantsLPw(
1537                                                packageName, userId);
1538                                    }
1539                                }
1540                            }
1541                            // Log current value of "unknown sources" setting
1542                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1543                                getUnknownSourcesSettings());
1544                        }
1545                        // Force a gc to clear up things
1546                        Runtime.getRuntime().gc();
1547                        // We delete after a gc for applications  on sdcard.
1548                        if (deleteOld) {
1549                            synchronized (mInstallLock) {
1550                                res.removedInfo.args.doPostDeleteLI(true);
1551                            }
1552                        }
1553                        if (args.observer != null) {
1554                            try {
1555                                Bundle extras = extrasForInstallResult(res);
1556                                args.observer.onPackageInstalled(res.name, res.returnCode,
1557                                        res.returnMsg, extras);
1558                            } catch (RemoteException e) {
1559                                Slog.i(TAG, "Observer no longer exists.");
1560                            }
1561                        }
1562                        if (args.traceMethod != null) {
1563                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1564                                    args.traceCookie);
1565                        }
1566                        return;
1567                    } else {
1568                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1569                    }
1570
1571                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1572                } break;
1573                case UPDATED_MEDIA_STATUS: {
1574                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1575                    boolean reportStatus = msg.arg1 == 1;
1576                    boolean doGc = msg.arg2 == 1;
1577                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1578                    if (doGc) {
1579                        // Force a gc to clear up stale containers.
1580                        Runtime.getRuntime().gc();
1581                    }
1582                    if (msg.obj != null) {
1583                        @SuppressWarnings("unchecked")
1584                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1585                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1586                        // Unload containers
1587                        unloadAllContainers(args);
1588                    }
1589                    if (reportStatus) {
1590                        try {
1591                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1592                            PackageHelper.getMountService().finishMediaUpdate();
1593                        } catch (RemoteException e) {
1594                            Log.e(TAG, "MountService not running?");
1595                        }
1596                    }
1597                } break;
1598                case WRITE_SETTINGS: {
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1600                    synchronized (mPackages) {
1601                        removeMessages(WRITE_SETTINGS);
1602                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1603                        mSettings.writeLPr();
1604                        mDirtyUsers.clear();
1605                    }
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1607                } break;
1608                case WRITE_PACKAGE_RESTRICTIONS: {
1609                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1610                    synchronized (mPackages) {
1611                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1612                        for (int userId : mDirtyUsers) {
1613                            mSettings.writePackageRestrictionsLPr(userId);
1614                        }
1615                        mDirtyUsers.clear();
1616                    }
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1618                } break;
1619                case CHECK_PENDING_VERIFICATION: {
1620                    final int verificationId = msg.arg1;
1621                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1622
1623                    if ((state != null) && !state.timeoutExtended()) {
1624                        final InstallArgs args = state.getInstallArgs();
1625                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1626
1627                        Slog.i(TAG, "Verification timed out for " + originUri);
1628                        mPendingVerification.remove(verificationId);
1629
1630                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1631
1632                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1633                            Slog.i(TAG, "Continuing with installation of " + originUri);
1634                            state.setVerifierResponse(Binder.getCallingUid(),
1635                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1636                            broadcastPackageVerified(verificationId, originUri,
1637                                    PackageManager.VERIFICATION_ALLOW,
1638                                    state.getInstallArgs().getUser());
1639                            try {
1640                                ret = args.copyApk(mContainerService, true);
1641                            } catch (RemoteException e) {
1642                                Slog.e(TAG, "Could not contact the ContainerService");
1643                            }
1644                        } else {
1645                            broadcastPackageVerified(verificationId, originUri,
1646                                    PackageManager.VERIFICATION_REJECT,
1647                                    state.getInstallArgs().getUser());
1648                        }
1649
1650                        Trace.asyncTraceEnd(
1651                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1652
1653                        processPendingInstall(args, ret);
1654                        mHandler.sendEmptyMessage(MCS_UNBIND);
1655                    }
1656                    break;
1657                }
1658                case PACKAGE_VERIFIED: {
1659                    final int verificationId = msg.arg1;
1660
1661                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1662                    if (state == null) {
1663                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1664                        break;
1665                    }
1666
1667                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1668
1669                    state.setVerifierResponse(response.callerUid, response.code);
1670
1671                    if (state.isVerificationComplete()) {
1672                        mPendingVerification.remove(verificationId);
1673
1674                        final InstallArgs args = state.getInstallArgs();
1675                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1676
1677                        int ret;
1678                        if (state.isInstallAllowed()) {
1679                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1680                            broadcastPackageVerified(verificationId, originUri,
1681                                    response.code, state.getInstallArgs().getUser());
1682                            try {
1683                                ret = args.copyApk(mContainerService, true);
1684                            } catch (RemoteException e) {
1685                                Slog.e(TAG, "Could not contact the ContainerService");
1686                            }
1687                        } else {
1688                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1689                        }
1690
1691                        Trace.asyncTraceEnd(
1692                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1693
1694                        processPendingInstall(args, ret);
1695                        mHandler.sendEmptyMessage(MCS_UNBIND);
1696                    }
1697
1698                    break;
1699                }
1700                case START_INTENT_FILTER_VERIFICATIONS: {
1701                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1702                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1703                            params.replacing, params.pkg);
1704                    break;
1705                }
1706                case INTENT_FILTER_VERIFIED: {
1707                    final int verificationId = msg.arg1;
1708
1709                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1710                            verificationId);
1711                    if (state == null) {
1712                        Slog.w(TAG, "Invalid IntentFilter verification token "
1713                                + verificationId + " received");
1714                        break;
1715                    }
1716
1717                    final int userId = state.getUserId();
1718
1719                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1720                            "Processing IntentFilter verification with token:"
1721                            + verificationId + " and userId:" + userId);
1722
1723                    final IntentFilterVerificationResponse response =
1724                            (IntentFilterVerificationResponse) msg.obj;
1725
1726                    state.setVerifierResponse(response.callerUid, response.code);
1727
1728                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1729                            "IntentFilter verification with token:" + verificationId
1730                            + " and userId:" + userId
1731                            + " is settings verifier response with response code:"
1732                            + response.code);
1733
1734                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1735                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1736                                + response.getFailedDomainsString());
1737                    }
1738
1739                    if (state.isVerificationComplete()) {
1740                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1741                    } else {
1742                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1743                                "IntentFilter verification with token:" + verificationId
1744                                + " was not said to be complete");
1745                    }
1746
1747                    break;
1748                }
1749            }
1750        }
1751    }
1752
1753    private StorageEventListener mStorageListener = new StorageEventListener() {
1754        @Override
1755        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1756            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1757                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1758                    final String volumeUuid = vol.getFsUuid();
1759
1760                    // Clean up any users or apps that were removed or recreated
1761                    // while this volume was missing
1762                    reconcileUsers(volumeUuid);
1763                    reconcileApps(volumeUuid);
1764
1765                    // Clean up any install sessions that expired or were
1766                    // cancelled while this volume was missing
1767                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1768
1769                    loadPrivatePackages(vol);
1770
1771                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1772                    unloadPrivatePackages(vol);
1773                }
1774            }
1775
1776            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1777                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1778                    updateExternalMediaStatus(true, false);
1779                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1780                    updateExternalMediaStatus(false, false);
1781                }
1782            }
1783        }
1784
1785        @Override
1786        public void onVolumeForgotten(String fsUuid) {
1787            if (TextUtils.isEmpty(fsUuid)) {
1788                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1789                return;
1790            }
1791
1792            // Remove any apps installed on the forgotten volume
1793            synchronized (mPackages) {
1794                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1795                for (PackageSetting ps : packages) {
1796                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1797                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1798                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1799                }
1800
1801                mSettings.onVolumeForgotten(fsUuid);
1802                mSettings.writeLPr();
1803            }
1804        }
1805    };
1806
1807    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1808            String[] grantedPermissions) {
1809        if (userId >= UserHandle.USER_SYSTEM) {
1810            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1811        } else if (userId == UserHandle.USER_ALL) {
1812            final int[] userIds;
1813            synchronized (mPackages) {
1814                userIds = UserManagerService.getInstance().getUserIds();
1815            }
1816            for (int someUserId : userIds) {
1817                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1818            }
1819        }
1820
1821        // We could have touched GID membership, so flush out packages.list
1822        synchronized (mPackages) {
1823            mSettings.writePackageListLPr();
1824        }
1825    }
1826
1827    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1828            String[] grantedPermissions) {
1829        SettingBase sb = (SettingBase) pkg.mExtras;
1830        if (sb == null) {
1831            return;
1832        }
1833
1834        PermissionsState permissionsState = sb.getPermissionsState();
1835
1836        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1837                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1838
1839        synchronized (mPackages) {
1840            for (String permission : pkg.requestedPermissions) {
1841                BasePermission bp = mSettings.mPermissions.get(permission);
1842                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1843                        && (grantedPermissions == null
1844                               || ArrayUtils.contains(grantedPermissions, permission))) {
1845                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1846                    // Installer cannot change immutable permissions.
1847                    if ((flags & immutableFlags) == 0) {
1848                        grantRuntimePermission(pkg.packageName, permission, userId);
1849                    }
1850                }
1851            }
1852        }
1853    }
1854
1855    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1856        Bundle extras = null;
1857        switch (res.returnCode) {
1858            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1859                extras = new Bundle();
1860                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1861                        res.origPermission);
1862                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1863                        res.origPackage);
1864                break;
1865            }
1866            case PackageManager.INSTALL_SUCCEEDED: {
1867                extras = new Bundle();
1868                extras.putBoolean(Intent.EXTRA_REPLACING,
1869                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1870                break;
1871            }
1872        }
1873        return extras;
1874    }
1875
1876    void scheduleWriteSettingsLocked() {
1877        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1878            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1879        }
1880    }
1881
1882    void scheduleWritePackageRestrictionsLocked(int userId) {
1883        if (!sUserManager.exists(userId)) return;
1884        mDirtyUsers.add(userId);
1885        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1886            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1887        }
1888    }
1889
1890    public static PackageManagerService main(Context context, Installer installer,
1891            boolean factoryTest, boolean onlyCore) {
1892        PackageManagerService m = new PackageManagerService(context, installer,
1893                factoryTest, onlyCore);
1894        m.enableSystemUserPackages();
1895        ServiceManager.addService("package", m);
1896        return m;
1897    }
1898
1899    private void enableSystemUserPackages() {
1900        if (!UserManager.isSplitSystemUser()) {
1901            return;
1902        }
1903        // For system user, enable apps based on the following conditions:
1904        // - app is whitelisted or belong to one of these groups:
1905        //   -- system app which has no launcher icons
1906        //   -- system app which has INTERACT_ACROSS_USERS permission
1907        //   -- system IME app
1908        // - app is not in the blacklist
1909        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1910        Set<String> enableApps = new ArraySet<>();
1911        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1912                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1913                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1914        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1915        enableApps.addAll(wlApps);
1916        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1917                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1918        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1919        enableApps.removeAll(blApps);
1920        Log.i(TAG, "Applications installed for system user: " + enableApps);
1921        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1922                UserHandle.SYSTEM);
1923        final int allAppsSize = allAps.size();
1924        synchronized (mPackages) {
1925            for (int i = 0; i < allAppsSize; i++) {
1926                String pName = allAps.get(i);
1927                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1928                // Should not happen, but we shouldn't be failing if it does
1929                if (pkgSetting == null) {
1930                    continue;
1931                }
1932                boolean install = enableApps.contains(pName);
1933                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1934                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1935                            + " for system user");
1936                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1937                }
1938            }
1939        }
1940    }
1941
1942    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1943        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1944                Context.DISPLAY_SERVICE);
1945        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1946    }
1947
1948    public PackageManagerService(Context context, Installer installer,
1949            boolean factoryTest, boolean onlyCore) {
1950        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1951                SystemClock.uptimeMillis());
1952
1953        if (mSdkVersion <= 0) {
1954            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1955        }
1956
1957        mContext = context;
1958        mFactoryTest = factoryTest;
1959        mOnlyCore = onlyCore;
1960        mMetrics = new DisplayMetrics();
1961        mSettings = new Settings(mPackages);
1962        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1963                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1964        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1965                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1966        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1967                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1968        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1969                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1970        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1971                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1972        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1973                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1974
1975        String separateProcesses = SystemProperties.get("debug.separate_processes");
1976        if (separateProcesses != null && separateProcesses.length() > 0) {
1977            if ("*".equals(separateProcesses)) {
1978                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1979                mSeparateProcesses = null;
1980                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1981            } else {
1982                mDefParseFlags = 0;
1983                mSeparateProcesses = separateProcesses.split(",");
1984                Slog.w(TAG, "Running with debug.separate_processes: "
1985                        + separateProcesses);
1986            }
1987        } else {
1988            mDefParseFlags = 0;
1989            mSeparateProcesses = null;
1990        }
1991
1992        mInstaller = installer;
1993        mPackageDexOptimizer = new PackageDexOptimizer(this);
1994        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1995
1996        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1997                FgThread.get().getLooper());
1998
1999        getDefaultDisplayMetrics(context, mMetrics);
2000
2001        SystemConfig systemConfig = SystemConfig.getInstance();
2002        mGlobalGids = systemConfig.getGlobalGids();
2003        mSystemPermissions = systemConfig.getSystemPermissions();
2004        mAvailableFeatures = systemConfig.getAvailableFeatures();
2005
2006        synchronized (mInstallLock) {
2007        // writer
2008        synchronized (mPackages) {
2009            mHandlerThread = new ServiceThread(TAG,
2010                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2011            mHandlerThread.start();
2012            mHandler = new PackageHandler(mHandlerThread.getLooper());
2013            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2014
2015            File dataDir = Environment.getDataDirectory();
2016            mAppInstallDir = new File(dataDir, "app");
2017            mAppLib32InstallDir = new File(dataDir, "app-lib");
2018            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2019            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2020            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2021
2022            sUserManager = new UserManagerService(context, this, mPackages);
2023
2024            // Propagate permission configuration in to package manager.
2025            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2026                    = systemConfig.getPermissions();
2027            for (int i=0; i<permConfig.size(); i++) {
2028                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2029                BasePermission bp = mSettings.mPermissions.get(perm.name);
2030                if (bp == null) {
2031                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2032                    mSettings.mPermissions.put(perm.name, bp);
2033                }
2034                if (perm.gids != null) {
2035                    bp.setGids(perm.gids, perm.perUser);
2036                }
2037            }
2038
2039            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2040            for (int i=0; i<libConfig.size(); i++) {
2041                mSharedLibraries.put(libConfig.keyAt(i),
2042                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2043            }
2044
2045            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2046
2047            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2048
2049            String customResolverActivity = Resources.getSystem().getString(
2050                    R.string.config_customResolverActivity);
2051            if (TextUtils.isEmpty(customResolverActivity)) {
2052                customResolverActivity = null;
2053            } else {
2054                mCustomResolverComponentName = ComponentName.unflattenFromString(
2055                        customResolverActivity);
2056            }
2057
2058            long startTime = SystemClock.uptimeMillis();
2059
2060            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2061                    startTime);
2062
2063            // Set flag to monitor and not change apk file paths when
2064            // scanning install directories.
2065            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2066
2067            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2068            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2069
2070            if (bootClassPath == null) {
2071                Slog.w(TAG, "No BOOTCLASSPATH found!");
2072            }
2073
2074            if (systemServerClassPath == null) {
2075                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2076            }
2077
2078            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2079            final String[] dexCodeInstructionSets =
2080                    getDexCodeInstructionSets(
2081                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2082
2083            /**
2084             * Ensure all external libraries have had dexopt run on them.
2085             */
2086            if (mSharedLibraries.size() > 0) {
2087                // NOTE: For now, we're compiling these system "shared libraries"
2088                // (and framework jars) into all available architectures. It's possible
2089                // to compile them only when we come across an app that uses them (there's
2090                // already logic for that in scanPackageLI) but that adds some complexity.
2091                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2092                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2093                        final String lib = libEntry.path;
2094                        if (lib == null) {
2095                            continue;
2096                        }
2097
2098                        try {
2099                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2100                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2101                                // Shared libraries do not have profiles so we perform a full
2102                                // AOT compilation.
2103                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2104                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2105                                        StorageManager.UUID_PRIVATE_INTERNAL,
2106                                        false /*useProfiles*/);
2107                            }
2108                        } catch (FileNotFoundException e) {
2109                            Slog.w(TAG, "Library not found: " + lib);
2110                        } catch (IOException | InstallerException e) {
2111                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2112                                    + e.getMessage());
2113                        }
2114                    }
2115                }
2116            }
2117
2118            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2119
2120            final VersionInfo ver = mSettings.getInternalVersion();
2121            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2122            // when upgrading from pre-M, promote system app permissions from install to runtime
2123            mPromoteSystemApps =
2124                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2125
2126            // save off the names of pre-existing system packages prior to scanning; we don't
2127            // want to automatically grant runtime permissions for new system apps
2128            if (mPromoteSystemApps) {
2129                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2130                while (pkgSettingIter.hasNext()) {
2131                    PackageSetting ps = pkgSettingIter.next();
2132                    if (isSystemApp(ps)) {
2133                        mExistingSystemPackages.add(ps.name);
2134                    }
2135                }
2136            }
2137
2138            // Collect vendor overlay packages.
2139            // (Do this before scanning any apps.)
2140            // For security and version matching reason, only consider
2141            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2142            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2143            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2144                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2145
2146            // Find base frameworks (resource packages without code).
2147            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2148                    | PackageParser.PARSE_IS_SYSTEM_DIR
2149                    | PackageParser.PARSE_IS_PRIVILEGED,
2150                    scanFlags | SCAN_NO_DEX, 0);
2151
2152            // Collected privileged system packages.
2153            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2154            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2155                    | PackageParser.PARSE_IS_SYSTEM_DIR
2156                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2157
2158            // Collect ordinary system packages.
2159            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2160            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2161                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2162
2163            // Collect all vendor packages.
2164            File vendorAppDir = new File("/vendor/app");
2165            try {
2166                vendorAppDir = vendorAppDir.getCanonicalFile();
2167            } catch (IOException e) {
2168                // failed to look up canonical path, continue with original one
2169            }
2170            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2171                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2172
2173            // Collect all OEM packages.
2174            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2175            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2176                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2177
2178            // Prune any system packages that no longer exist.
2179            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2180            if (!mOnlyCore) {
2181                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2182                while (psit.hasNext()) {
2183                    PackageSetting ps = psit.next();
2184
2185                    /*
2186                     * If this is not a system app, it can't be a
2187                     * disable system app.
2188                     */
2189                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2190                        continue;
2191                    }
2192
2193                    /*
2194                     * If the package is scanned, it's not erased.
2195                     */
2196                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2197                    if (scannedPkg != null) {
2198                        /*
2199                         * If the system app is both scanned and in the
2200                         * disabled packages list, then it must have been
2201                         * added via OTA. Remove it from the currently
2202                         * scanned package so the previously user-installed
2203                         * application can be scanned.
2204                         */
2205                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2206                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2207                                    + ps.name + "; removing system app.  Last known codePath="
2208                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2209                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2210                                    + scannedPkg.mVersionCode);
2211                            removePackageLI(ps, true);
2212                            mExpectingBetter.put(ps.name, ps.codePath);
2213                        }
2214
2215                        continue;
2216                    }
2217
2218                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2219                        psit.remove();
2220                        logCriticalInfo(Log.WARN, "System package " + ps.name
2221                                + " no longer exists; wiping its data");
2222                        removeDataDirsLI(null, ps.name);
2223                    } else {
2224                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2225                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2226                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2227                        }
2228                    }
2229                }
2230            }
2231
2232            //look for any incomplete package installations
2233            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2234            //clean up list
2235            for(int i = 0; i < deletePkgsList.size(); i++) {
2236                //clean up here
2237                cleanupInstallFailedPackage(deletePkgsList.get(i));
2238            }
2239            //delete tmp files
2240            deleteTempPackageFiles();
2241
2242            // Remove any shared userIDs that have no associated packages
2243            mSettings.pruneSharedUsersLPw();
2244
2245            if (!mOnlyCore) {
2246                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2247                        SystemClock.uptimeMillis());
2248                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2249
2250                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2251                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2252
2253                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2254                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2255
2256                /**
2257                 * Remove disable package settings for any updated system
2258                 * apps that were removed via an OTA. If they're not a
2259                 * previously-updated app, remove them completely.
2260                 * Otherwise, just revoke their system-level permissions.
2261                 */
2262                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2263                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2264                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2265
2266                    String msg;
2267                    if (deletedPkg == null) {
2268                        msg = "Updated system package " + deletedAppName
2269                                + " no longer exists; wiping its data";
2270                        removeDataDirsLI(null, deletedAppName);
2271                    } else {
2272                        msg = "Updated system app + " + deletedAppName
2273                                + " no longer present; removing system privileges for "
2274                                + deletedAppName;
2275
2276                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2277
2278                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2279                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2280                    }
2281                    logCriticalInfo(Log.WARN, msg);
2282                }
2283
2284                /**
2285                 * Make sure all system apps that we expected to appear on
2286                 * the userdata partition actually showed up. If they never
2287                 * appeared, crawl back and revive the system version.
2288                 */
2289                for (int i = 0; i < mExpectingBetter.size(); i++) {
2290                    final String packageName = mExpectingBetter.keyAt(i);
2291                    if (!mPackages.containsKey(packageName)) {
2292                        final File scanFile = mExpectingBetter.valueAt(i);
2293
2294                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2295                                + " but never showed up; reverting to system");
2296
2297                        final int reparseFlags;
2298                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2299                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2300                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2301                                    | PackageParser.PARSE_IS_PRIVILEGED;
2302                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2303                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2304                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2305                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2306                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2307                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2308                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2309                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2310                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2311                        } else {
2312                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2313                            continue;
2314                        }
2315
2316                        mSettings.enableSystemPackageLPw(packageName);
2317
2318                        try {
2319                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2320                        } catch (PackageManagerException e) {
2321                            Slog.e(TAG, "Failed to parse original system package: "
2322                                    + e.getMessage());
2323                        }
2324                    }
2325                }
2326            }
2327            mExpectingBetter.clear();
2328
2329            // Now that we know all of the shared libraries, update all clients to have
2330            // the correct library paths.
2331            updateAllSharedLibrariesLPw();
2332
2333            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2334                // NOTE: We ignore potential failures here during a system scan (like
2335                // the rest of the commands above) because there's precious little we
2336                // can do about it. A settings error is reported, though.
2337                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2338                        false /* boot complete */);
2339            }
2340
2341            // Now that we know all the packages we are keeping,
2342            // read and update their last usage times.
2343            mPackageUsage.readLP();
2344
2345            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2346                    SystemClock.uptimeMillis());
2347            Slog.i(TAG, "Time to scan packages: "
2348                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2349                    + " seconds");
2350
2351            // If the platform SDK has changed since the last time we booted,
2352            // we need to re-grant app permission to catch any new ones that
2353            // appear.  This is really a hack, and means that apps can in some
2354            // cases get permissions that the user didn't initially explicitly
2355            // allow...  it would be nice to have some better way to handle
2356            // this situation.
2357            int updateFlags = UPDATE_PERMISSIONS_ALL;
2358            if (ver.sdkVersion != mSdkVersion) {
2359                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2360                        + mSdkVersion + "; regranting permissions for internal storage");
2361                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2362            }
2363            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2364            ver.sdkVersion = mSdkVersion;
2365
2366            // If this is the first boot or an update from pre-M, and it is a normal
2367            // boot, then we need to initialize the default preferred apps across
2368            // all defined users.
2369            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2370                for (UserInfo user : sUserManager.getUsers(true)) {
2371                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2372                    applyFactoryDefaultBrowserLPw(user.id);
2373                    primeDomainVerificationsLPw(user.id);
2374                }
2375            }
2376
2377            // Prepare storage for system user really early during boot,
2378            // since core system apps like SettingsProvider and SystemUI
2379            // can't wait for user to start
2380            final int flags;
2381            if (StorageManager.isFileBasedEncryptionEnabled()) {
2382                flags = Installer.FLAG_DE_STORAGE;
2383            } else {
2384                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
2385            }
2386            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2387
2388            // If this is first boot after an OTA, and a normal boot, then
2389            // we need to clear code cache directories.
2390            if (mIsUpgrade && !onlyCore) {
2391                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2392                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2393                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2394                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2395                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2396                    }
2397                }
2398                ver.fingerprint = Build.FINGERPRINT;
2399            }
2400
2401            checkDefaultBrowser();
2402
2403            // clear only after permissions and other defaults have been updated
2404            mExistingSystemPackages.clear();
2405            mPromoteSystemApps = false;
2406
2407            // All the changes are done during package scanning.
2408            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2409
2410            // can downgrade to reader
2411            mSettings.writeLPr();
2412
2413            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2414                    SystemClock.uptimeMillis());
2415
2416            if (!mOnlyCore) {
2417                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2418                mRequiredInstallerPackage = getRequiredInstallerLPr();
2419                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2420                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2421                        mIntentFilterVerifierComponent);
2422            } else {
2423                mRequiredVerifierPackage = null;
2424                mRequiredInstallerPackage = null;
2425                mIntentFilterVerifierComponent = null;
2426                mIntentFilterVerifier = null;
2427            }
2428
2429            mInstallerService = new PackageInstallerService(context, this);
2430
2431            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2432            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2433            // both the installer and resolver must be present to enable ephemeral
2434            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2435                if (DEBUG_EPHEMERAL) {
2436                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2437                            + " installer:" + ephemeralInstallerComponent);
2438                }
2439                mEphemeralResolverComponent = ephemeralResolverComponent;
2440                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2441                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2442                mEphemeralResolverConnection =
2443                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2444            } else {
2445                if (DEBUG_EPHEMERAL) {
2446                    final String missingComponent =
2447                            (ephemeralResolverComponent == null)
2448                            ? (ephemeralInstallerComponent == null)
2449                                    ? "resolver and installer"
2450                                    : "resolver"
2451                            : "installer";
2452                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2453                }
2454                mEphemeralResolverComponent = null;
2455                mEphemeralInstallerComponent = null;
2456                mEphemeralResolverConnection = null;
2457            }
2458
2459            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2460        } // synchronized (mPackages)
2461        } // synchronized (mInstallLock)
2462
2463        // Now after opening every single application zip, make sure they
2464        // are all flushed.  Not really needed, but keeps things nice and
2465        // tidy.
2466        Runtime.getRuntime().gc();
2467
2468        // The initial scanning above does many calls into installd while
2469        // holding the mPackages lock, but we're mostly interested in yelling
2470        // once we have a booted system.
2471        mInstaller.setWarnIfHeld(mPackages);
2472
2473        // Expose private service for system components to use.
2474        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2475    }
2476
2477    @Override
2478    public boolean isFirstBoot() {
2479        return !mRestoredSettings;
2480    }
2481
2482    @Override
2483    public boolean isOnlyCoreApps() {
2484        return mOnlyCore;
2485    }
2486
2487    @Override
2488    public boolean isUpgrade() {
2489        return mIsUpgrade;
2490    }
2491
2492    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2493        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2494
2495        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2496                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2497        if (matches.size() == 1) {
2498            return matches.get(0).getComponentInfo().packageName;
2499        } else {
2500            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2501            return null;
2502        }
2503    }
2504
2505    private @NonNull String getRequiredInstallerLPr() {
2506        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2507        intent.addCategory(Intent.CATEGORY_DEFAULT);
2508        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2509
2510        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2511                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2512        if (matches.size() == 1) {
2513            return matches.get(0).getComponentInfo().packageName;
2514        } else {
2515            throw new RuntimeException("There must be exactly one installer; found " + matches);
2516        }
2517    }
2518
2519    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2520        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2521
2522        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2523                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2524        ResolveInfo best = null;
2525        final int N = matches.size();
2526        for (int i = 0; i < N; i++) {
2527            final ResolveInfo cur = matches.get(i);
2528            final String packageName = cur.getComponentInfo().packageName;
2529            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2530                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2531                continue;
2532            }
2533
2534            if (best == null || cur.priority > best.priority) {
2535                best = cur;
2536            }
2537        }
2538
2539        if (best != null) {
2540            return best.getComponentInfo().getComponentName();
2541        } else {
2542            throw new RuntimeException("There must be at least one intent filter verifier");
2543        }
2544    }
2545
2546    private @Nullable ComponentName getEphemeralResolverLPr() {
2547        final String[] packageArray =
2548                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2549        if (packageArray.length == 0) {
2550            if (DEBUG_EPHEMERAL) {
2551                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2552            }
2553            return null;
2554        }
2555
2556        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2557        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2558                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2559
2560        final int N = resolvers.size();
2561        if (N == 0) {
2562            if (DEBUG_EPHEMERAL) {
2563                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2564            }
2565            return null;
2566        }
2567
2568        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2569        for (int i = 0; i < N; i++) {
2570            final ResolveInfo info = resolvers.get(i);
2571
2572            if (info.serviceInfo == null) {
2573                continue;
2574            }
2575
2576            final String packageName = info.serviceInfo.packageName;
2577            if (!possiblePackages.contains(packageName)) {
2578                if (DEBUG_EPHEMERAL) {
2579                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2580                            + " pkg: " + packageName + ", info:" + info);
2581                }
2582                continue;
2583            }
2584
2585            if (DEBUG_EPHEMERAL) {
2586                Slog.v(TAG, "Ephemeral resolver found;"
2587                        + " pkg: " + packageName + ", info:" + info);
2588            }
2589            return new ComponentName(packageName, info.serviceInfo.name);
2590        }
2591        if (DEBUG_EPHEMERAL) {
2592            Slog.v(TAG, "Ephemeral resolver NOT found");
2593        }
2594        return null;
2595    }
2596
2597    private @Nullable ComponentName getEphemeralInstallerLPr() {
2598        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2599        intent.addCategory(Intent.CATEGORY_DEFAULT);
2600        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2601
2602        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2603                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2604        if (matches.size() == 0) {
2605            return null;
2606        } else if (matches.size() == 1) {
2607            return matches.get(0).getComponentInfo().getComponentName();
2608        } else {
2609            throw new RuntimeException(
2610                    "There must be at most one ephemeral installer; found " + matches);
2611        }
2612    }
2613
2614    private void primeDomainVerificationsLPw(int userId) {
2615        if (DEBUG_DOMAIN_VERIFICATION) {
2616            Slog.d(TAG, "Priming domain verifications in user " + userId);
2617        }
2618
2619        SystemConfig systemConfig = SystemConfig.getInstance();
2620        ArraySet<String> packages = systemConfig.getLinkedApps();
2621        ArraySet<String> domains = new ArraySet<String>();
2622
2623        for (String packageName : packages) {
2624            PackageParser.Package pkg = mPackages.get(packageName);
2625            if (pkg != null) {
2626                if (!pkg.isSystemApp()) {
2627                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2628                    continue;
2629                }
2630
2631                domains.clear();
2632                for (PackageParser.Activity a : pkg.activities) {
2633                    for (ActivityIntentInfo filter : a.intents) {
2634                        if (hasValidDomains(filter)) {
2635                            domains.addAll(filter.getHostsList());
2636                        }
2637                    }
2638                }
2639
2640                if (domains.size() > 0) {
2641                    if (DEBUG_DOMAIN_VERIFICATION) {
2642                        Slog.v(TAG, "      + " + packageName);
2643                    }
2644                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2645                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2646                    // and then 'always' in the per-user state actually used for intent resolution.
2647                    final IntentFilterVerificationInfo ivi;
2648                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2649                            new ArrayList<String>(domains));
2650                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2651                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2652                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2653                } else {
2654                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2655                            + "' does not handle web links");
2656                }
2657            } else {
2658                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2659            }
2660        }
2661
2662        scheduleWritePackageRestrictionsLocked(userId);
2663        scheduleWriteSettingsLocked();
2664    }
2665
2666    private void applyFactoryDefaultBrowserLPw(int userId) {
2667        // The default browser app's package name is stored in a string resource,
2668        // with a product-specific overlay used for vendor customization.
2669        String browserPkg = mContext.getResources().getString(
2670                com.android.internal.R.string.default_browser);
2671        if (!TextUtils.isEmpty(browserPkg)) {
2672            // non-empty string => required to be a known package
2673            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2674            if (ps == null) {
2675                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2676                browserPkg = null;
2677            } else {
2678                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2679            }
2680        }
2681
2682        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2683        // default.  If there's more than one, just leave everything alone.
2684        if (browserPkg == null) {
2685            calculateDefaultBrowserLPw(userId);
2686        }
2687    }
2688
2689    private void calculateDefaultBrowserLPw(int userId) {
2690        List<String> allBrowsers = resolveAllBrowserApps(userId);
2691        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2692        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2693    }
2694
2695    private List<String> resolveAllBrowserApps(int userId) {
2696        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2697        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2698                PackageManager.MATCH_ALL, userId);
2699
2700        final int count = list.size();
2701        List<String> result = new ArrayList<String>(count);
2702        for (int i=0; i<count; i++) {
2703            ResolveInfo info = list.get(i);
2704            if (info.activityInfo == null
2705                    || !info.handleAllWebDataURI
2706                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2707                    || result.contains(info.activityInfo.packageName)) {
2708                continue;
2709            }
2710            result.add(info.activityInfo.packageName);
2711        }
2712
2713        return result;
2714    }
2715
2716    private boolean packageIsBrowser(String packageName, int userId) {
2717        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2718                PackageManager.MATCH_ALL, userId);
2719        final int N = list.size();
2720        for (int i = 0; i < N; i++) {
2721            ResolveInfo info = list.get(i);
2722            if (packageName.equals(info.activityInfo.packageName)) {
2723                return true;
2724            }
2725        }
2726        return false;
2727    }
2728
2729    private void checkDefaultBrowser() {
2730        final int myUserId = UserHandle.myUserId();
2731        final String packageName = getDefaultBrowserPackageName(myUserId);
2732        if (packageName != null) {
2733            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2734            if (info == null) {
2735                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2736                synchronized (mPackages) {
2737                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2738                }
2739            }
2740        }
2741    }
2742
2743    @Override
2744    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2745            throws RemoteException {
2746        try {
2747            return super.onTransact(code, data, reply, flags);
2748        } catch (RuntimeException e) {
2749            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2750                Slog.wtf(TAG, "Package Manager Crash", e);
2751            }
2752            throw e;
2753        }
2754    }
2755
2756    void cleanupInstallFailedPackage(PackageSetting ps) {
2757        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2758
2759        removeDataDirsLI(ps.volumeUuid, ps.name);
2760        if (ps.codePath != null) {
2761            removeCodePathLI(ps.codePath);
2762        }
2763        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2764            if (ps.resourcePath.isDirectory()) {
2765                FileUtils.deleteContents(ps.resourcePath);
2766            }
2767            ps.resourcePath.delete();
2768        }
2769        mSettings.removePackageLPw(ps.name);
2770    }
2771
2772    static int[] appendInts(int[] cur, int[] add) {
2773        if (add == null) return cur;
2774        if (cur == null) return add;
2775        final int N = add.length;
2776        for (int i=0; i<N; i++) {
2777            cur = appendInt(cur, add[i]);
2778        }
2779        return cur;
2780    }
2781
2782    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2783        if (!sUserManager.exists(userId)) return null;
2784        final PackageSetting ps = (PackageSetting) p.mExtras;
2785        if (ps == null) {
2786            return null;
2787        }
2788
2789        final PermissionsState permissionsState = ps.getPermissionsState();
2790
2791        final int[] gids = permissionsState.computeGids(userId);
2792        final Set<String> permissions = permissionsState.getPermissions(userId);
2793        final PackageUserState state = ps.readUserState(userId);
2794
2795        return PackageParser.generatePackageInfo(p, gids, flags,
2796                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2797    }
2798
2799    @Override
2800    public void checkPackageStartable(String packageName, int userId) {
2801        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2802
2803        synchronized (mPackages) {
2804            final PackageSetting ps = mSettings.mPackages.get(packageName);
2805            if (ps == null) {
2806                throw new SecurityException("Package " + packageName + " was not found!");
2807            }
2808
2809            if (ps.frozen) {
2810                throw new SecurityException("Package " + packageName + " is currently frozen!");
2811            }
2812
2813            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2814                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2815                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2816            }
2817        }
2818    }
2819
2820    @Override
2821    public boolean isPackageAvailable(String packageName, int userId) {
2822        if (!sUserManager.exists(userId)) return false;
2823        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2824        synchronized (mPackages) {
2825            PackageParser.Package p = mPackages.get(packageName);
2826            if (p != null) {
2827                final PackageSetting ps = (PackageSetting) p.mExtras;
2828                if (ps != null) {
2829                    final PackageUserState state = ps.readUserState(userId);
2830                    if (state != null) {
2831                        return PackageParser.isAvailable(state);
2832                    }
2833                }
2834            }
2835        }
2836        return false;
2837    }
2838
2839    @Override
2840    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2841        if (!sUserManager.exists(userId)) return null;
2842        flags = updateFlagsForPackage(flags, userId, packageName);
2843        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2844        // reader
2845        synchronized (mPackages) {
2846            PackageParser.Package p = mPackages.get(packageName);
2847            if (DEBUG_PACKAGE_INFO)
2848                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2849            if (p != null) {
2850                return generatePackageInfo(p, flags, userId);
2851            }
2852            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2853                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2854            }
2855        }
2856        return null;
2857    }
2858
2859    @Override
2860    public String[] currentToCanonicalPackageNames(String[] names) {
2861        String[] out = new String[names.length];
2862        // reader
2863        synchronized (mPackages) {
2864            for (int i=names.length-1; i>=0; i--) {
2865                PackageSetting ps = mSettings.mPackages.get(names[i]);
2866                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2867            }
2868        }
2869        return out;
2870    }
2871
2872    @Override
2873    public String[] canonicalToCurrentPackageNames(String[] names) {
2874        String[] out = new String[names.length];
2875        // reader
2876        synchronized (mPackages) {
2877            for (int i=names.length-1; i>=0; i--) {
2878                String cur = mSettings.mRenamedPackages.get(names[i]);
2879                out[i] = cur != null ? cur : names[i];
2880            }
2881        }
2882        return out;
2883    }
2884
2885    @Override
2886    public int getPackageUid(String packageName, int flags, int userId) {
2887        if (!sUserManager.exists(userId)) return -1;
2888        flags = updateFlagsForPackage(flags, userId, packageName);
2889        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2890
2891        // reader
2892        synchronized (mPackages) {
2893            final PackageParser.Package p = mPackages.get(packageName);
2894            if (p != null && p.isMatch(flags)) {
2895                return UserHandle.getUid(userId, p.applicationInfo.uid);
2896            }
2897            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2898                final PackageSetting ps = mSettings.mPackages.get(packageName);
2899                if (ps != null && ps.isMatch(flags)) {
2900                    return UserHandle.getUid(userId, ps.appId);
2901                }
2902            }
2903        }
2904
2905        return -1;
2906    }
2907
2908    @Override
2909    public int[] getPackageGids(String packageName, int flags, int userId) {
2910        if (!sUserManager.exists(userId)) return null;
2911        flags = updateFlagsForPackage(flags, userId, packageName);
2912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2913                "getPackageGids");
2914
2915        // reader
2916        synchronized (mPackages) {
2917            final PackageParser.Package p = mPackages.get(packageName);
2918            if (p != null && p.isMatch(flags)) {
2919                PackageSetting ps = (PackageSetting) p.mExtras;
2920                return ps.getPermissionsState().computeGids(userId);
2921            }
2922            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2923                final PackageSetting ps = mSettings.mPackages.get(packageName);
2924                if (ps != null && ps.isMatch(flags)) {
2925                    return ps.getPermissionsState().computeGids(userId);
2926                }
2927            }
2928        }
2929
2930        return null;
2931    }
2932
2933    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2934        if (bp.perm != null) {
2935            return PackageParser.generatePermissionInfo(bp.perm, flags);
2936        }
2937        PermissionInfo pi = new PermissionInfo();
2938        pi.name = bp.name;
2939        pi.packageName = bp.sourcePackage;
2940        pi.nonLocalizedLabel = bp.name;
2941        pi.protectionLevel = bp.protectionLevel;
2942        return pi;
2943    }
2944
2945    @Override
2946    public PermissionInfo getPermissionInfo(String name, int flags) {
2947        // reader
2948        synchronized (mPackages) {
2949            final BasePermission p = mSettings.mPermissions.get(name);
2950            if (p != null) {
2951                return generatePermissionInfo(p, flags);
2952            }
2953            return null;
2954        }
2955    }
2956
2957    @Override
2958    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2959        // reader
2960        synchronized (mPackages) {
2961            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2962            for (BasePermission p : mSettings.mPermissions.values()) {
2963                if (group == null) {
2964                    if (p.perm == null || p.perm.info.group == null) {
2965                        out.add(generatePermissionInfo(p, flags));
2966                    }
2967                } else {
2968                    if (p.perm != null && group.equals(p.perm.info.group)) {
2969                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2970                    }
2971                }
2972            }
2973
2974            if (out.size() > 0) {
2975                return out;
2976            }
2977            return mPermissionGroups.containsKey(group) ? out : null;
2978        }
2979    }
2980
2981    @Override
2982    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2983        // reader
2984        synchronized (mPackages) {
2985            return PackageParser.generatePermissionGroupInfo(
2986                    mPermissionGroups.get(name), flags);
2987        }
2988    }
2989
2990    @Override
2991    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2992        // reader
2993        synchronized (mPackages) {
2994            final int N = mPermissionGroups.size();
2995            ArrayList<PermissionGroupInfo> out
2996                    = new ArrayList<PermissionGroupInfo>(N);
2997            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2998                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2999            }
3000            return out;
3001        }
3002    }
3003
3004    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3005            int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        PackageSetting ps = mSettings.mPackages.get(packageName);
3008        if (ps != null) {
3009            if (ps.pkg == null) {
3010                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3011                        flags, userId);
3012                if (pInfo != null) {
3013                    return pInfo.applicationInfo;
3014                }
3015                return null;
3016            }
3017            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3018                    ps.readUserState(userId), userId);
3019        }
3020        return null;
3021    }
3022
3023    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3024            int userId) {
3025        if (!sUserManager.exists(userId)) return null;
3026        PackageSetting ps = mSettings.mPackages.get(packageName);
3027        if (ps != null) {
3028            PackageParser.Package pkg = ps.pkg;
3029            if (pkg == null) {
3030                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3031                    return null;
3032                }
3033                // Only data remains, so we aren't worried about code paths
3034                pkg = new PackageParser.Package(packageName);
3035                pkg.applicationInfo.packageName = packageName;
3036                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3037                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3038                pkg.applicationInfo.uid = ps.appId;
3039                pkg.applicationInfo.initForUser(userId);
3040                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3041                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3042            }
3043            return generatePackageInfo(pkg, flags, userId);
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3050        if (!sUserManager.exists(userId)) return null;
3051        flags = updateFlagsForApplication(flags, userId, packageName);
3052        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3053        // writer
3054        synchronized (mPackages) {
3055            PackageParser.Package p = mPackages.get(packageName);
3056            if (DEBUG_PACKAGE_INFO) Log.v(
3057                    TAG, "getApplicationInfo " + packageName
3058                    + ": " + p);
3059            if (p != null) {
3060                PackageSetting ps = mSettings.mPackages.get(packageName);
3061                if (ps == null) return null;
3062                // Note: isEnabledLP() does not apply here - always return info
3063                return PackageParser.generateApplicationInfo(
3064                        p, flags, ps.readUserState(userId), userId);
3065            }
3066            if ("android".equals(packageName)||"system".equals(packageName)) {
3067                return mAndroidApplication;
3068            }
3069            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3070                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3071            }
3072        }
3073        return null;
3074    }
3075
3076    @Override
3077    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3078            final IPackageDataObserver observer) {
3079        mContext.enforceCallingOrSelfPermission(
3080                android.Manifest.permission.CLEAR_APP_CACHE, null);
3081        // Queue up an async operation since clearing cache may take a little while.
3082        mHandler.post(new Runnable() {
3083            public void run() {
3084                mHandler.removeCallbacks(this);
3085                boolean success = true;
3086                synchronized (mInstallLock) {
3087                    try {
3088                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3089                    } catch (InstallerException e) {
3090                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3091                        success = false;
3092                    }
3093                }
3094                if (observer != null) {
3095                    try {
3096                        observer.onRemoveCompleted(null, success);
3097                    } catch (RemoteException e) {
3098                        Slog.w(TAG, "RemoveException when invoking call back");
3099                    }
3100                }
3101            }
3102        });
3103    }
3104
3105    @Override
3106    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3107            final IntentSender pi) {
3108        mContext.enforceCallingOrSelfPermission(
3109                android.Manifest.permission.CLEAR_APP_CACHE, null);
3110        // Queue up an async operation since clearing cache may take a little while.
3111        mHandler.post(new Runnable() {
3112            public void run() {
3113                mHandler.removeCallbacks(this);
3114                boolean success = true;
3115                synchronized (mInstallLock) {
3116                    try {
3117                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3118                    } catch (InstallerException e) {
3119                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3120                        success = false;
3121                    }
3122                }
3123                if(pi != null) {
3124                    try {
3125                        // Callback via pending intent
3126                        int code = success ? 1 : 0;
3127                        pi.sendIntent(null, code, null,
3128                                null, null);
3129                    } catch (SendIntentException e1) {
3130                        Slog.i(TAG, "Failed to send pending intent");
3131                    }
3132                }
3133            }
3134        });
3135    }
3136
3137    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3138        synchronized (mInstallLock) {
3139            try {
3140                mInstaller.freeCache(volumeUuid, freeStorageSize);
3141            } catch (InstallerException e) {
3142                throw new IOException("Failed to free enough space", e);
3143            }
3144        }
3145    }
3146
3147    /**
3148     * Return if the user key is currently unlocked.
3149     */
3150    private boolean isUserKeyUnlocked(int userId) {
3151        if (StorageManager.isFileBasedEncryptionEnabled()) {
3152            final IMountService mount = IMountService.Stub
3153                    .asInterface(ServiceManager.getService("mount"));
3154            if (mount == null) {
3155                Slog.w(TAG, "Early during boot, assuming locked");
3156                return false;
3157            }
3158            final long token = Binder.clearCallingIdentity();
3159            try {
3160                return mount.isUserKeyUnlocked(userId);
3161            } catch (RemoteException e) {
3162                throw e.rethrowAsRuntimeException();
3163            } finally {
3164                Binder.restoreCallingIdentity(token);
3165            }
3166        } else {
3167            return true;
3168        }
3169    }
3170
3171    /**
3172     * Update given flags based on encryption status of current user.
3173     */
3174    private int updateFlags(int flags, int userId) {
3175        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3176                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3177            // Caller expressed an explicit opinion about what encryption
3178            // aware/unaware components they want to see, so fall through and
3179            // give them what they want
3180        } else {
3181            // Caller expressed no opinion, so match based on user state
3182            if (isUserKeyUnlocked(userId)) {
3183                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3184            } else {
3185                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3186            }
3187        }
3188
3189        // Safe mode means we should ignore any third-party apps
3190        if (mSafeMode) {
3191            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3192        }
3193
3194        return flags;
3195    }
3196
3197    /**
3198     * Update given flags when being used to request {@link PackageInfo}.
3199     */
3200    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3201        boolean triaged = true;
3202        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3203                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3204            // Caller is asking for component details, so they'd better be
3205            // asking for specific encryption matching behavior, or be triaged
3206            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3207                    | PackageManager.MATCH_ENCRYPTION_AWARE
3208                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3209                triaged = false;
3210            }
3211        }
3212        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3213                | PackageManager.MATCH_SYSTEM_ONLY
3214                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3215            triaged = false;
3216        }
3217        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3218            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3219                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3220        }
3221        return updateFlags(flags, userId);
3222    }
3223
3224    /**
3225     * Update given flags when being used to request {@link ApplicationInfo}.
3226     */
3227    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3228        return updateFlagsForPackage(flags, userId, cookie);
3229    }
3230
3231    /**
3232     * Update given flags when being used to request {@link ComponentInfo}.
3233     */
3234    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3235        if (cookie instanceof Intent) {
3236            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3237                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3238            }
3239        }
3240
3241        boolean triaged = true;
3242        // Caller is asking for component details, so they'd better be
3243        // asking for specific encryption matching behavior, or be triaged
3244        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3245                | PackageManager.MATCH_ENCRYPTION_AWARE
3246                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3247            triaged = false;
3248        }
3249        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3250            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3251                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3252        }
3253        return updateFlags(flags, userId);
3254    }
3255
3256    /**
3257     * Update given flags when being used to request {@link ResolveInfo}.
3258     */
3259    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3260        return updateFlagsForComponent(flags, userId, cookie);
3261    }
3262
3263    @Override
3264    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3265        if (!sUserManager.exists(userId)) return null;
3266        flags = updateFlagsForComponent(flags, userId, component);
3267        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3268        synchronized (mPackages) {
3269            PackageParser.Activity a = mActivities.mActivities.get(component);
3270
3271            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3272            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3273                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3274                if (ps == null) return null;
3275                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3276                        userId);
3277            }
3278            if (mResolveComponentName.equals(component)) {
3279                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3280                        new PackageUserState(), userId);
3281            }
3282        }
3283        return null;
3284    }
3285
3286    @Override
3287    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3288            String resolvedType) {
3289        synchronized (mPackages) {
3290            if (component.equals(mResolveComponentName)) {
3291                // The resolver supports EVERYTHING!
3292                return true;
3293            }
3294            PackageParser.Activity a = mActivities.mActivities.get(component);
3295            if (a == null) {
3296                return false;
3297            }
3298            for (int i=0; i<a.intents.size(); i++) {
3299                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3300                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3301                    return true;
3302                }
3303            }
3304            return false;
3305        }
3306    }
3307
3308    @Override
3309    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3310        if (!sUserManager.exists(userId)) return null;
3311        flags = updateFlagsForComponent(flags, userId, component);
3312        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3313        synchronized (mPackages) {
3314            PackageParser.Activity a = mReceivers.mActivities.get(component);
3315            if (DEBUG_PACKAGE_INFO) Log.v(
3316                TAG, "getReceiverInfo " + component + ": " + a);
3317            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3318                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3319                if (ps == null) return null;
3320                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3321                        userId);
3322            }
3323        }
3324        return null;
3325    }
3326
3327    @Override
3328    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3329        if (!sUserManager.exists(userId)) return null;
3330        flags = updateFlagsForComponent(flags, userId, component);
3331        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3332        synchronized (mPackages) {
3333            PackageParser.Service s = mServices.mServices.get(component);
3334            if (DEBUG_PACKAGE_INFO) Log.v(
3335                TAG, "getServiceInfo " + component + ": " + s);
3336            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3337                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3338                if (ps == null) return null;
3339                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3340                        userId);
3341            }
3342        }
3343        return null;
3344    }
3345
3346    @Override
3347    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3348        if (!sUserManager.exists(userId)) return null;
3349        flags = updateFlagsForComponent(flags, userId, component);
3350        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3351        synchronized (mPackages) {
3352            PackageParser.Provider p = mProviders.mProviders.get(component);
3353            if (DEBUG_PACKAGE_INFO) Log.v(
3354                TAG, "getProviderInfo " + component + ": " + p);
3355            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3356                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3357                if (ps == null) return null;
3358                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3359                        userId);
3360            }
3361        }
3362        return null;
3363    }
3364
3365    @Override
3366    public String[] getSystemSharedLibraryNames() {
3367        Set<String> libSet;
3368        synchronized (mPackages) {
3369            libSet = mSharedLibraries.keySet();
3370            int size = libSet.size();
3371            if (size > 0) {
3372                String[] libs = new String[size];
3373                libSet.toArray(libs);
3374                return libs;
3375            }
3376        }
3377        return null;
3378    }
3379
3380    /**
3381     * @hide
3382     */
3383    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3384        synchronized (mPackages) {
3385            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3386            if (lib != null && lib.apk != null) {
3387                return mPackages.get(lib.apk);
3388            }
3389        }
3390        return null;
3391    }
3392
3393    @Override
3394    public FeatureInfo[] getSystemAvailableFeatures() {
3395        Collection<FeatureInfo> featSet;
3396        synchronized (mPackages) {
3397            featSet = mAvailableFeatures.values();
3398            int size = featSet.size();
3399            if (size > 0) {
3400                FeatureInfo[] features = new FeatureInfo[size+1];
3401                featSet.toArray(features);
3402                FeatureInfo fi = new FeatureInfo();
3403                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3404                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3405                features[size] = fi;
3406                return features;
3407            }
3408        }
3409        return null;
3410    }
3411
3412    @Override
3413    public boolean hasSystemFeature(String name) {
3414        synchronized (mPackages) {
3415            return mAvailableFeatures.containsKey(name);
3416        }
3417    }
3418
3419    @Override
3420    public int checkPermission(String permName, String pkgName, int userId) {
3421        if (!sUserManager.exists(userId)) {
3422            return PackageManager.PERMISSION_DENIED;
3423        }
3424
3425        synchronized (mPackages) {
3426            final PackageParser.Package p = mPackages.get(pkgName);
3427            if (p != null && p.mExtras != null) {
3428                final PackageSetting ps = (PackageSetting) p.mExtras;
3429                final PermissionsState permissionsState = ps.getPermissionsState();
3430                if (permissionsState.hasPermission(permName, userId)) {
3431                    return PackageManager.PERMISSION_GRANTED;
3432                }
3433                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3434                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3435                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3436                    return PackageManager.PERMISSION_GRANTED;
3437                }
3438            }
3439        }
3440
3441        return PackageManager.PERMISSION_DENIED;
3442    }
3443
3444    @Override
3445    public int checkUidPermission(String permName, int uid) {
3446        final int userId = UserHandle.getUserId(uid);
3447
3448        if (!sUserManager.exists(userId)) {
3449            return PackageManager.PERMISSION_DENIED;
3450        }
3451
3452        synchronized (mPackages) {
3453            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3454            if (obj != null) {
3455                final SettingBase ps = (SettingBase) obj;
3456                final PermissionsState permissionsState = ps.getPermissionsState();
3457                if (permissionsState.hasPermission(permName, userId)) {
3458                    return PackageManager.PERMISSION_GRANTED;
3459                }
3460                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3461                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3462                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3463                    return PackageManager.PERMISSION_GRANTED;
3464                }
3465            } else {
3466                ArraySet<String> perms = mSystemPermissions.get(uid);
3467                if (perms != null) {
3468                    if (perms.contains(permName)) {
3469                        return PackageManager.PERMISSION_GRANTED;
3470                    }
3471                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3472                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3473                        return PackageManager.PERMISSION_GRANTED;
3474                    }
3475                }
3476            }
3477        }
3478
3479        return PackageManager.PERMISSION_DENIED;
3480    }
3481
3482    @Override
3483    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3484        if (UserHandle.getCallingUserId() != userId) {
3485            mContext.enforceCallingPermission(
3486                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3487                    "isPermissionRevokedByPolicy for user " + userId);
3488        }
3489
3490        if (checkPermission(permission, packageName, userId)
3491                == PackageManager.PERMISSION_GRANTED) {
3492            return false;
3493        }
3494
3495        final long identity = Binder.clearCallingIdentity();
3496        try {
3497            final int flags = getPermissionFlags(permission, packageName, userId);
3498            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3499        } finally {
3500            Binder.restoreCallingIdentity(identity);
3501        }
3502    }
3503
3504    @Override
3505    public String getPermissionControllerPackageName() {
3506        synchronized (mPackages) {
3507            return mRequiredInstallerPackage;
3508        }
3509    }
3510
3511    /**
3512     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3513     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3514     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3515     * @param message the message to log on security exception
3516     */
3517    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3518            boolean checkShell, String message) {
3519        if (userId < 0) {
3520            throw new IllegalArgumentException("Invalid userId " + userId);
3521        }
3522        if (checkShell) {
3523            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3524        }
3525        if (userId == UserHandle.getUserId(callingUid)) return;
3526        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3527            if (requireFullPermission) {
3528                mContext.enforceCallingOrSelfPermission(
3529                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3530            } else {
3531                try {
3532                    mContext.enforceCallingOrSelfPermission(
3533                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3534                } catch (SecurityException se) {
3535                    mContext.enforceCallingOrSelfPermission(
3536                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3537                }
3538            }
3539        }
3540    }
3541
3542    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3543        if (callingUid == Process.SHELL_UID) {
3544            if (userHandle >= 0
3545                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3546                throw new SecurityException("Shell does not have permission to access user "
3547                        + userHandle);
3548            } else if (userHandle < 0) {
3549                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3550                        + Debug.getCallers(3));
3551            }
3552        }
3553    }
3554
3555    private BasePermission findPermissionTreeLP(String permName) {
3556        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3557            if (permName.startsWith(bp.name) &&
3558                    permName.length() > bp.name.length() &&
3559                    permName.charAt(bp.name.length()) == '.') {
3560                return bp;
3561            }
3562        }
3563        return null;
3564    }
3565
3566    private BasePermission checkPermissionTreeLP(String permName) {
3567        if (permName != null) {
3568            BasePermission bp = findPermissionTreeLP(permName);
3569            if (bp != null) {
3570                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3571                    return bp;
3572                }
3573                throw new SecurityException("Calling uid "
3574                        + Binder.getCallingUid()
3575                        + " is not allowed to add to permission tree "
3576                        + bp.name + " owned by uid " + bp.uid);
3577            }
3578        }
3579        throw new SecurityException("No permission tree found for " + permName);
3580    }
3581
3582    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3583        if (s1 == null) {
3584            return s2 == null;
3585        }
3586        if (s2 == null) {
3587            return false;
3588        }
3589        if (s1.getClass() != s2.getClass()) {
3590            return false;
3591        }
3592        return s1.equals(s2);
3593    }
3594
3595    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3596        if (pi1.icon != pi2.icon) return false;
3597        if (pi1.logo != pi2.logo) return false;
3598        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3599        if (!compareStrings(pi1.name, pi2.name)) return false;
3600        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3601        // We'll take care of setting this one.
3602        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3603        // These are not currently stored in settings.
3604        //if (!compareStrings(pi1.group, pi2.group)) return false;
3605        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3606        //if (pi1.labelRes != pi2.labelRes) return false;
3607        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3608        return true;
3609    }
3610
3611    int permissionInfoFootprint(PermissionInfo info) {
3612        int size = info.name.length();
3613        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3614        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3615        return size;
3616    }
3617
3618    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3619        int size = 0;
3620        for (BasePermission perm : mSettings.mPermissions.values()) {
3621            if (perm.uid == tree.uid) {
3622                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3623            }
3624        }
3625        return size;
3626    }
3627
3628    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3629        // We calculate the max size of permissions defined by this uid and throw
3630        // if that plus the size of 'info' would exceed our stated maximum.
3631        if (tree.uid != Process.SYSTEM_UID) {
3632            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3633            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3634                throw new SecurityException("Permission tree size cap exceeded");
3635            }
3636        }
3637    }
3638
3639    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3640        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3641            throw new SecurityException("Label must be specified in permission");
3642        }
3643        BasePermission tree = checkPermissionTreeLP(info.name);
3644        BasePermission bp = mSettings.mPermissions.get(info.name);
3645        boolean added = bp == null;
3646        boolean changed = true;
3647        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3648        if (added) {
3649            enforcePermissionCapLocked(info, tree);
3650            bp = new BasePermission(info.name, tree.sourcePackage,
3651                    BasePermission.TYPE_DYNAMIC);
3652        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3653            throw new SecurityException(
3654                    "Not allowed to modify non-dynamic permission "
3655                    + info.name);
3656        } else {
3657            if (bp.protectionLevel == fixedLevel
3658                    && bp.perm.owner.equals(tree.perm.owner)
3659                    && bp.uid == tree.uid
3660                    && comparePermissionInfos(bp.perm.info, info)) {
3661                changed = false;
3662            }
3663        }
3664        bp.protectionLevel = fixedLevel;
3665        info = new PermissionInfo(info);
3666        info.protectionLevel = fixedLevel;
3667        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3668        bp.perm.info.packageName = tree.perm.info.packageName;
3669        bp.uid = tree.uid;
3670        if (added) {
3671            mSettings.mPermissions.put(info.name, bp);
3672        }
3673        if (changed) {
3674            if (!async) {
3675                mSettings.writeLPr();
3676            } else {
3677                scheduleWriteSettingsLocked();
3678            }
3679        }
3680        return added;
3681    }
3682
3683    @Override
3684    public boolean addPermission(PermissionInfo info) {
3685        synchronized (mPackages) {
3686            return addPermissionLocked(info, false);
3687        }
3688    }
3689
3690    @Override
3691    public boolean addPermissionAsync(PermissionInfo info) {
3692        synchronized (mPackages) {
3693            return addPermissionLocked(info, true);
3694        }
3695    }
3696
3697    @Override
3698    public void removePermission(String name) {
3699        synchronized (mPackages) {
3700            checkPermissionTreeLP(name);
3701            BasePermission bp = mSettings.mPermissions.get(name);
3702            if (bp != null) {
3703                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3704                    throw new SecurityException(
3705                            "Not allowed to modify non-dynamic permission "
3706                            + name);
3707                }
3708                mSettings.mPermissions.remove(name);
3709                mSettings.writeLPr();
3710            }
3711        }
3712    }
3713
3714    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3715            BasePermission bp) {
3716        int index = pkg.requestedPermissions.indexOf(bp.name);
3717        if (index == -1) {
3718            throw new SecurityException("Package " + pkg.packageName
3719                    + " has not requested permission " + bp.name);
3720        }
3721        if (!bp.isRuntime() && !bp.isDevelopment()) {
3722            throw new SecurityException("Permission " + bp.name
3723                    + " is not a changeable permission type");
3724        }
3725    }
3726
3727    @Override
3728    public void grantRuntimePermission(String packageName, String name, final int userId) {
3729        if (!sUserManager.exists(userId)) {
3730            Log.e(TAG, "No such user:" + userId);
3731            return;
3732        }
3733
3734        mContext.enforceCallingOrSelfPermission(
3735                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3736                "grantRuntimePermission");
3737
3738        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3739                "grantRuntimePermission");
3740
3741        final int uid;
3742        final SettingBase sb;
3743
3744        synchronized (mPackages) {
3745            final PackageParser.Package pkg = mPackages.get(packageName);
3746            if (pkg == null) {
3747                throw new IllegalArgumentException("Unknown package: " + packageName);
3748            }
3749
3750            final BasePermission bp = mSettings.mPermissions.get(name);
3751            if (bp == null) {
3752                throw new IllegalArgumentException("Unknown permission: " + name);
3753            }
3754
3755            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3756
3757            // If a permission review is required for legacy apps we represent
3758            // their permissions as always granted runtime ones since we need
3759            // to keep the review required permission flag per user while an
3760            // install permission's state is shared across all users.
3761            if (Build.PERMISSIONS_REVIEW_REQUIRED
3762                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3763                    && bp.isRuntime()) {
3764                return;
3765            }
3766
3767            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3768            sb = (SettingBase) pkg.mExtras;
3769            if (sb == null) {
3770                throw new IllegalArgumentException("Unknown package: " + packageName);
3771            }
3772
3773            final PermissionsState permissionsState = sb.getPermissionsState();
3774
3775            final int flags = permissionsState.getPermissionFlags(name, userId);
3776            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3777                throw new SecurityException("Cannot grant system fixed permission "
3778                        + name + " for package " + packageName);
3779            }
3780
3781            if (bp.isDevelopment()) {
3782                // Development permissions must be handled specially, since they are not
3783                // normal runtime permissions.  For now they apply to all users.
3784                if (permissionsState.grantInstallPermission(bp) !=
3785                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3786                    scheduleWriteSettingsLocked();
3787                }
3788                return;
3789            }
3790
3791            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3792                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3793                return;
3794            }
3795
3796            final int result = permissionsState.grantRuntimePermission(bp, userId);
3797            switch (result) {
3798                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3799                    return;
3800                }
3801
3802                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3803                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3804                    mHandler.post(new Runnable() {
3805                        @Override
3806                        public void run() {
3807                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3808                        }
3809                    });
3810                }
3811                break;
3812            }
3813
3814            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3815
3816            // Not critical if that is lost - app has to request again.
3817            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3818        }
3819
3820        // Only need to do this if user is initialized. Otherwise it's a new user
3821        // and there are no processes running as the user yet and there's no need
3822        // to make an expensive call to remount processes for the changed permissions.
3823        if (READ_EXTERNAL_STORAGE.equals(name)
3824                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3825            final long token = Binder.clearCallingIdentity();
3826            try {
3827                if (sUserManager.isInitialized(userId)) {
3828                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3829                            MountServiceInternal.class);
3830                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3831                }
3832            } finally {
3833                Binder.restoreCallingIdentity(token);
3834            }
3835        }
3836    }
3837
3838    @Override
3839    public void revokeRuntimePermission(String packageName, String name, int userId) {
3840        if (!sUserManager.exists(userId)) {
3841            Log.e(TAG, "No such user:" + userId);
3842            return;
3843        }
3844
3845        mContext.enforceCallingOrSelfPermission(
3846                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3847                "revokeRuntimePermission");
3848
3849        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3850                "revokeRuntimePermission");
3851
3852        final int appId;
3853
3854        synchronized (mPackages) {
3855            final PackageParser.Package pkg = mPackages.get(packageName);
3856            if (pkg == null) {
3857                throw new IllegalArgumentException("Unknown package: " + packageName);
3858            }
3859
3860            final BasePermission bp = mSettings.mPermissions.get(name);
3861            if (bp == null) {
3862                throw new IllegalArgumentException("Unknown permission: " + name);
3863            }
3864
3865            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3866
3867            // If a permission review is required for legacy apps we represent
3868            // their permissions as always granted runtime ones since we need
3869            // to keep the review required permission flag per user while an
3870            // install permission's state is shared across all users.
3871            if (Build.PERMISSIONS_REVIEW_REQUIRED
3872                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3873                    && bp.isRuntime()) {
3874                return;
3875            }
3876
3877            SettingBase sb = (SettingBase) pkg.mExtras;
3878            if (sb == null) {
3879                throw new IllegalArgumentException("Unknown package: " + packageName);
3880            }
3881
3882            final PermissionsState permissionsState = sb.getPermissionsState();
3883
3884            final int flags = permissionsState.getPermissionFlags(name, userId);
3885            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3886                throw new SecurityException("Cannot revoke system fixed permission "
3887                        + name + " for package " + packageName);
3888            }
3889
3890            if (bp.isDevelopment()) {
3891                // Development permissions must be handled specially, since they are not
3892                // normal runtime permissions.  For now they apply to all users.
3893                if (permissionsState.revokeInstallPermission(bp) !=
3894                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3895                    scheduleWriteSettingsLocked();
3896                }
3897                return;
3898            }
3899
3900            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3901                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3902                return;
3903            }
3904
3905            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3906
3907            // Critical, after this call app should never have the permission.
3908            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3909
3910            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3911        }
3912
3913        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3914    }
3915
3916    @Override
3917    public void resetRuntimePermissions() {
3918        mContext.enforceCallingOrSelfPermission(
3919                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3920                "revokeRuntimePermission");
3921
3922        int callingUid = Binder.getCallingUid();
3923        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3924            mContext.enforceCallingOrSelfPermission(
3925                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3926                    "resetRuntimePermissions");
3927        }
3928
3929        synchronized (mPackages) {
3930            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3931            for (int userId : UserManagerService.getInstance().getUserIds()) {
3932                final int packageCount = mPackages.size();
3933                for (int i = 0; i < packageCount; i++) {
3934                    PackageParser.Package pkg = mPackages.valueAt(i);
3935                    if (!(pkg.mExtras instanceof PackageSetting)) {
3936                        continue;
3937                    }
3938                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3939                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3940                }
3941            }
3942        }
3943    }
3944
3945    @Override
3946    public int getPermissionFlags(String name, String packageName, int userId) {
3947        if (!sUserManager.exists(userId)) {
3948            return 0;
3949        }
3950
3951        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3952
3953        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3954                "getPermissionFlags");
3955
3956        synchronized (mPackages) {
3957            final PackageParser.Package pkg = mPackages.get(packageName);
3958            if (pkg == null) {
3959                throw new IllegalArgumentException("Unknown package: " + packageName);
3960            }
3961
3962            final BasePermission bp = mSettings.mPermissions.get(name);
3963            if (bp == null) {
3964                throw new IllegalArgumentException("Unknown permission: " + name);
3965            }
3966
3967            SettingBase sb = (SettingBase) pkg.mExtras;
3968            if (sb == null) {
3969                throw new IllegalArgumentException("Unknown package: " + packageName);
3970            }
3971
3972            PermissionsState permissionsState = sb.getPermissionsState();
3973            return permissionsState.getPermissionFlags(name, userId);
3974        }
3975    }
3976
3977    @Override
3978    public void updatePermissionFlags(String name, String packageName, int flagMask,
3979            int flagValues, int userId) {
3980        if (!sUserManager.exists(userId)) {
3981            return;
3982        }
3983
3984        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3985
3986        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3987                "updatePermissionFlags");
3988
3989        // Only the system can change these flags and nothing else.
3990        if (getCallingUid() != Process.SYSTEM_UID) {
3991            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3992            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3993            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3994            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3995            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3996        }
3997
3998        synchronized (mPackages) {
3999            final PackageParser.Package pkg = mPackages.get(packageName);
4000            if (pkg == null) {
4001                throw new IllegalArgumentException("Unknown package: " + packageName);
4002            }
4003
4004            final BasePermission bp = mSettings.mPermissions.get(name);
4005            if (bp == null) {
4006                throw new IllegalArgumentException("Unknown permission: " + name);
4007            }
4008
4009            SettingBase sb = (SettingBase) pkg.mExtras;
4010            if (sb == null) {
4011                throw new IllegalArgumentException("Unknown package: " + packageName);
4012            }
4013
4014            PermissionsState permissionsState = sb.getPermissionsState();
4015
4016            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4017
4018            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4019                // Install and runtime permissions are stored in different places,
4020                // so figure out what permission changed and persist the change.
4021                if (permissionsState.getInstallPermissionState(name) != null) {
4022                    scheduleWriteSettingsLocked();
4023                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4024                        || hadState) {
4025                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4026                }
4027            }
4028        }
4029    }
4030
4031    /**
4032     * Update the permission flags for all packages and runtime permissions of a user in order
4033     * to allow device or profile owner to remove POLICY_FIXED.
4034     */
4035    @Override
4036    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4037        if (!sUserManager.exists(userId)) {
4038            return;
4039        }
4040
4041        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4042
4043        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4044                "updatePermissionFlagsForAllApps");
4045
4046        // Only the system can change system fixed flags.
4047        if (getCallingUid() != Process.SYSTEM_UID) {
4048            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4049            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4050        }
4051
4052        synchronized (mPackages) {
4053            boolean changed = false;
4054            final int packageCount = mPackages.size();
4055            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4056                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4057                SettingBase sb = (SettingBase) pkg.mExtras;
4058                if (sb == null) {
4059                    continue;
4060                }
4061                PermissionsState permissionsState = sb.getPermissionsState();
4062                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4063                        userId, flagMask, flagValues);
4064            }
4065            if (changed) {
4066                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4067            }
4068        }
4069    }
4070
4071    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4072        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4073                != PackageManager.PERMISSION_GRANTED
4074            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4075                != PackageManager.PERMISSION_GRANTED) {
4076            throw new SecurityException(message + " requires "
4077                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4078                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4079        }
4080    }
4081
4082    @Override
4083    public boolean shouldShowRequestPermissionRationale(String permissionName,
4084            String packageName, int userId) {
4085        if (UserHandle.getCallingUserId() != userId) {
4086            mContext.enforceCallingPermission(
4087                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4088                    "canShowRequestPermissionRationale for user " + userId);
4089        }
4090
4091        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4092        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4093            return false;
4094        }
4095
4096        if (checkPermission(permissionName, packageName, userId)
4097                == PackageManager.PERMISSION_GRANTED) {
4098            return false;
4099        }
4100
4101        final int flags;
4102
4103        final long identity = Binder.clearCallingIdentity();
4104        try {
4105            flags = getPermissionFlags(permissionName,
4106                    packageName, userId);
4107        } finally {
4108            Binder.restoreCallingIdentity(identity);
4109        }
4110
4111        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4112                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4113                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4114
4115        if ((flags & fixedFlags) != 0) {
4116            return false;
4117        }
4118
4119        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4120    }
4121
4122    @Override
4123    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4124        mContext.enforceCallingOrSelfPermission(
4125                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4126                "addOnPermissionsChangeListener");
4127
4128        synchronized (mPackages) {
4129            mOnPermissionChangeListeners.addListenerLocked(listener);
4130        }
4131    }
4132
4133    @Override
4134    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4135        synchronized (mPackages) {
4136            mOnPermissionChangeListeners.removeListenerLocked(listener);
4137        }
4138    }
4139
4140    @Override
4141    public boolean isProtectedBroadcast(String actionName) {
4142        synchronized (mPackages) {
4143            if (mProtectedBroadcasts.contains(actionName)) {
4144                return true;
4145            } else if (actionName != null) {
4146                // TODO: remove these terrible hacks
4147                if (actionName.startsWith("android.net.netmon.lingerExpired")
4148                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4149                    return true;
4150                }
4151            }
4152        }
4153        return false;
4154    }
4155
4156    @Override
4157    public int checkSignatures(String pkg1, String pkg2) {
4158        synchronized (mPackages) {
4159            final PackageParser.Package p1 = mPackages.get(pkg1);
4160            final PackageParser.Package p2 = mPackages.get(pkg2);
4161            if (p1 == null || p1.mExtras == null
4162                    || p2 == null || p2.mExtras == null) {
4163                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4164            }
4165            return compareSignatures(p1.mSignatures, p2.mSignatures);
4166        }
4167    }
4168
4169    @Override
4170    public int checkUidSignatures(int uid1, int uid2) {
4171        // Map to base uids.
4172        uid1 = UserHandle.getAppId(uid1);
4173        uid2 = UserHandle.getAppId(uid2);
4174        // reader
4175        synchronized (mPackages) {
4176            Signature[] s1;
4177            Signature[] s2;
4178            Object obj = mSettings.getUserIdLPr(uid1);
4179            if (obj != null) {
4180                if (obj instanceof SharedUserSetting) {
4181                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4182                } else if (obj instanceof PackageSetting) {
4183                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4184                } else {
4185                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4186                }
4187            } else {
4188                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4189            }
4190            obj = mSettings.getUserIdLPr(uid2);
4191            if (obj != null) {
4192                if (obj instanceof SharedUserSetting) {
4193                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4194                } else if (obj instanceof PackageSetting) {
4195                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4196                } else {
4197                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4198                }
4199            } else {
4200                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4201            }
4202            return compareSignatures(s1, s2);
4203        }
4204    }
4205
4206    private void killUid(int appId, int userId, String reason) {
4207        final long identity = Binder.clearCallingIdentity();
4208        try {
4209            IActivityManager am = ActivityManagerNative.getDefault();
4210            if (am != null) {
4211                try {
4212                    am.killUid(appId, userId, reason);
4213                } catch (RemoteException e) {
4214                    /* ignore - same process */
4215                }
4216            }
4217        } finally {
4218            Binder.restoreCallingIdentity(identity);
4219        }
4220    }
4221
4222    /**
4223     * Compares two sets of signatures. Returns:
4224     * <br />
4225     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4226     * <br />
4227     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4228     * <br />
4229     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4230     * <br />
4231     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4232     * <br />
4233     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4234     */
4235    static int compareSignatures(Signature[] s1, Signature[] s2) {
4236        if (s1 == null) {
4237            return s2 == null
4238                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4239                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4240        }
4241
4242        if (s2 == null) {
4243            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4244        }
4245
4246        if (s1.length != s2.length) {
4247            return PackageManager.SIGNATURE_NO_MATCH;
4248        }
4249
4250        // Since both signature sets are of size 1, we can compare without HashSets.
4251        if (s1.length == 1) {
4252            return s1[0].equals(s2[0]) ?
4253                    PackageManager.SIGNATURE_MATCH :
4254                    PackageManager.SIGNATURE_NO_MATCH;
4255        }
4256
4257        ArraySet<Signature> set1 = new ArraySet<Signature>();
4258        for (Signature sig : s1) {
4259            set1.add(sig);
4260        }
4261        ArraySet<Signature> set2 = new ArraySet<Signature>();
4262        for (Signature sig : s2) {
4263            set2.add(sig);
4264        }
4265        // Make sure s2 contains all signatures in s1.
4266        if (set1.equals(set2)) {
4267            return PackageManager.SIGNATURE_MATCH;
4268        }
4269        return PackageManager.SIGNATURE_NO_MATCH;
4270    }
4271
4272    /**
4273     * If the database version for this type of package (internal storage or
4274     * external storage) is less than the version where package signatures
4275     * were updated, return true.
4276     */
4277    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4278        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4279        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4280    }
4281
4282    /**
4283     * Used for backward compatibility to make sure any packages with
4284     * certificate chains get upgraded to the new style. {@code existingSigs}
4285     * will be in the old format (since they were stored on disk from before the
4286     * system upgrade) and {@code scannedSigs} will be in the newer format.
4287     */
4288    private int compareSignaturesCompat(PackageSignatures existingSigs,
4289            PackageParser.Package scannedPkg) {
4290        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4291            return PackageManager.SIGNATURE_NO_MATCH;
4292        }
4293
4294        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4295        for (Signature sig : existingSigs.mSignatures) {
4296            existingSet.add(sig);
4297        }
4298        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4299        for (Signature sig : scannedPkg.mSignatures) {
4300            try {
4301                Signature[] chainSignatures = sig.getChainSignatures();
4302                for (Signature chainSig : chainSignatures) {
4303                    scannedCompatSet.add(chainSig);
4304                }
4305            } catch (CertificateEncodingException e) {
4306                scannedCompatSet.add(sig);
4307            }
4308        }
4309        /*
4310         * Make sure the expanded scanned set contains all signatures in the
4311         * existing one.
4312         */
4313        if (scannedCompatSet.equals(existingSet)) {
4314            // Migrate the old signatures to the new scheme.
4315            existingSigs.assignSignatures(scannedPkg.mSignatures);
4316            // The new KeySets will be re-added later in the scanning process.
4317            synchronized (mPackages) {
4318                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4319            }
4320            return PackageManager.SIGNATURE_MATCH;
4321        }
4322        return PackageManager.SIGNATURE_NO_MATCH;
4323    }
4324
4325    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4326        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4327        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4328    }
4329
4330    private int compareSignaturesRecover(PackageSignatures existingSigs,
4331            PackageParser.Package scannedPkg) {
4332        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4333            return PackageManager.SIGNATURE_NO_MATCH;
4334        }
4335
4336        String msg = null;
4337        try {
4338            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4339                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4340                        + scannedPkg.packageName);
4341                return PackageManager.SIGNATURE_MATCH;
4342            }
4343        } catch (CertificateException e) {
4344            msg = e.getMessage();
4345        }
4346
4347        logCriticalInfo(Log.INFO,
4348                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4349        return PackageManager.SIGNATURE_NO_MATCH;
4350    }
4351
4352    @Override
4353    public String[] getPackagesForUid(int uid) {
4354        uid = UserHandle.getAppId(uid);
4355        // reader
4356        synchronized (mPackages) {
4357            Object obj = mSettings.getUserIdLPr(uid);
4358            if (obj instanceof SharedUserSetting) {
4359                final SharedUserSetting sus = (SharedUserSetting) obj;
4360                final int N = sus.packages.size();
4361                final String[] res = new String[N];
4362                final Iterator<PackageSetting> it = sus.packages.iterator();
4363                int i = 0;
4364                while (it.hasNext()) {
4365                    res[i++] = it.next().name;
4366                }
4367                return res;
4368            } else if (obj instanceof PackageSetting) {
4369                final PackageSetting ps = (PackageSetting) obj;
4370                return new String[] { ps.name };
4371            }
4372        }
4373        return null;
4374    }
4375
4376    @Override
4377    public String getNameForUid(int uid) {
4378        // reader
4379        synchronized (mPackages) {
4380            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4381            if (obj instanceof SharedUserSetting) {
4382                final SharedUserSetting sus = (SharedUserSetting) obj;
4383                return sus.name + ":" + sus.userId;
4384            } else if (obj instanceof PackageSetting) {
4385                final PackageSetting ps = (PackageSetting) obj;
4386                return ps.name;
4387            }
4388        }
4389        return null;
4390    }
4391
4392    @Override
4393    public int getUidForSharedUser(String sharedUserName) {
4394        if(sharedUserName == null) {
4395            return -1;
4396        }
4397        // reader
4398        synchronized (mPackages) {
4399            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4400            if (suid == null) {
4401                return -1;
4402            }
4403            return suid.userId;
4404        }
4405    }
4406
4407    @Override
4408    public int getFlagsForUid(int uid) {
4409        synchronized (mPackages) {
4410            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4411            if (obj instanceof SharedUserSetting) {
4412                final SharedUserSetting sus = (SharedUserSetting) obj;
4413                return sus.pkgFlags;
4414            } else if (obj instanceof PackageSetting) {
4415                final PackageSetting ps = (PackageSetting) obj;
4416                return ps.pkgFlags;
4417            }
4418        }
4419        return 0;
4420    }
4421
4422    @Override
4423    public int getPrivateFlagsForUid(int uid) {
4424        synchronized (mPackages) {
4425            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4426            if (obj instanceof SharedUserSetting) {
4427                final SharedUserSetting sus = (SharedUserSetting) obj;
4428                return sus.pkgPrivateFlags;
4429            } else if (obj instanceof PackageSetting) {
4430                final PackageSetting ps = (PackageSetting) obj;
4431                return ps.pkgPrivateFlags;
4432            }
4433        }
4434        return 0;
4435    }
4436
4437    @Override
4438    public boolean isUidPrivileged(int uid) {
4439        uid = UserHandle.getAppId(uid);
4440        // reader
4441        synchronized (mPackages) {
4442            Object obj = mSettings.getUserIdLPr(uid);
4443            if (obj instanceof SharedUserSetting) {
4444                final SharedUserSetting sus = (SharedUserSetting) obj;
4445                final Iterator<PackageSetting> it = sus.packages.iterator();
4446                while (it.hasNext()) {
4447                    if (it.next().isPrivileged()) {
4448                        return true;
4449                    }
4450                }
4451            } else if (obj instanceof PackageSetting) {
4452                final PackageSetting ps = (PackageSetting) obj;
4453                return ps.isPrivileged();
4454            }
4455        }
4456        return false;
4457    }
4458
4459    @Override
4460    public String[] getAppOpPermissionPackages(String permissionName) {
4461        synchronized (mPackages) {
4462            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4463            if (pkgs == null) {
4464                return null;
4465            }
4466            return pkgs.toArray(new String[pkgs.size()]);
4467        }
4468    }
4469
4470    @Override
4471    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4472            int flags, int userId) {
4473        if (!sUserManager.exists(userId)) return null;
4474        flags = updateFlagsForResolve(flags, userId, intent);
4475        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4476        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4477        final ResolveInfo bestChoice =
4478                chooseBestActivity(intent, resolvedType, flags, query, userId);
4479
4480        if (isEphemeralAllowed(intent, query, userId)) {
4481            final EphemeralResolveInfo ai =
4482                    getEphemeralResolveInfo(intent, resolvedType, userId);
4483            if (ai != null) {
4484                if (DEBUG_EPHEMERAL) {
4485                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4486                }
4487                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4488                bestChoice.ephemeralResolveInfo = ai;
4489            }
4490        }
4491        return bestChoice;
4492    }
4493
4494    @Override
4495    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4496            IntentFilter filter, int match, ComponentName activity) {
4497        final int userId = UserHandle.getCallingUserId();
4498        if (DEBUG_PREFERRED) {
4499            Log.v(TAG, "setLastChosenActivity intent=" + intent
4500                + " resolvedType=" + resolvedType
4501                + " flags=" + flags
4502                + " filter=" + filter
4503                + " match=" + match
4504                + " activity=" + activity);
4505            filter.dump(new PrintStreamPrinter(System.out), "    ");
4506        }
4507        intent.setComponent(null);
4508        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4509        // Find any earlier preferred or last chosen entries and nuke them
4510        findPreferredActivity(intent, resolvedType,
4511                flags, query, 0, false, true, false, userId);
4512        // Add the new activity as the last chosen for this filter
4513        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4514                "Setting last chosen");
4515    }
4516
4517    @Override
4518    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4519        final int userId = UserHandle.getCallingUserId();
4520        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4521        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4522        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4523                false, false, false, userId);
4524    }
4525
4526
4527    private boolean isEphemeralAllowed(
4528            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4529        // Short circuit and return early if possible.
4530        if (DISABLE_EPHEMERAL_APPS) {
4531            return false;
4532        }
4533        final int callingUser = UserHandle.getCallingUserId();
4534        if (callingUser != UserHandle.USER_SYSTEM) {
4535            return false;
4536        }
4537        if (mEphemeralResolverConnection == null) {
4538            return false;
4539        }
4540        if (intent.getComponent() != null) {
4541            return false;
4542        }
4543        if (intent.getPackage() != null) {
4544            return false;
4545        }
4546        final boolean isWebUri = hasWebURI(intent);
4547        if (!isWebUri) {
4548            return false;
4549        }
4550        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4551        synchronized (mPackages) {
4552            final int count = resolvedActivites.size();
4553            for (int n = 0; n < count; n++) {
4554                ResolveInfo info = resolvedActivites.get(n);
4555                String packageName = info.activityInfo.packageName;
4556                PackageSetting ps = mSettings.mPackages.get(packageName);
4557                if (ps != null) {
4558                    // Try to get the status from User settings first
4559                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4560                    int status = (int) (packedStatus >> 32);
4561                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4562                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4563                        if (DEBUG_EPHEMERAL) {
4564                            Slog.v(TAG, "DENY ephemeral apps;"
4565                                + " pkg: " + packageName + ", status: " + status);
4566                        }
4567                        return false;
4568                    }
4569                }
4570            }
4571        }
4572        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4573        return true;
4574    }
4575
4576    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4577            int userId) {
4578        MessageDigest digest = null;
4579        try {
4580            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4581        } catch (NoSuchAlgorithmException e) {
4582            // If we can't create a digest, ignore ephemeral apps.
4583            return null;
4584        }
4585
4586        final byte[] hostBytes = intent.getData().getHost().getBytes();
4587        final byte[] digestBytes = digest.digest(hostBytes);
4588        int shaPrefix =
4589                digestBytes[0] << 24
4590                | digestBytes[1] << 16
4591                | digestBytes[2] << 8
4592                | digestBytes[3] << 0;
4593        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4594                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4595        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4596            // No hash prefix match; there are no ephemeral apps for this domain.
4597            return null;
4598        }
4599        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4600            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4601            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4602                continue;
4603            }
4604            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4605            // No filters; this should never happen.
4606            if (filters.isEmpty()) {
4607                continue;
4608            }
4609            // We have a domain match; resolve the filters to see if anything matches.
4610            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4611            for (int j = filters.size() - 1; j >= 0; --j) {
4612                final EphemeralResolveIntentInfo intentInfo =
4613                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4614                ephemeralResolver.addFilter(intentInfo);
4615            }
4616            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4617                    intent, resolvedType, false /*defaultOnly*/, userId);
4618            if (!matchedResolveInfoList.isEmpty()) {
4619                return matchedResolveInfoList.get(0);
4620            }
4621        }
4622        // Hash or filter mis-match; no ephemeral apps for this domain.
4623        return null;
4624    }
4625
4626    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4627            int flags, List<ResolveInfo> query, int userId) {
4628        if (query != null) {
4629            final int N = query.size();
4630            if (N == 1) {
4631                return query.get(0);
4632            } else if (N > 1) {
4633                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4634                // If there is more than one activity with the same priority,
4635                // then let the user decide between them.
4636                ResolveInfo r0 = query.get(0);
4637                ResolveInfo r1 = query.get(1);
4638                if (DEBUG_INTENT_MATCHING || debug) {
4639                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4640                            + r1.activityInfo.name + "=" + r1.priority);
4641                }
4642                // If the first activity has a higher priority, or a different
4643                // default, then it is always desirable to pick it.
4644                if (r0.priority != r1.priority
4645                        || r0.preferredOrder != r1.preferredOrder
4646                        || r0.isDefault != r1.isDefault) {
4647                    return query.get(0);
4648                }
4649                // If we have saved a preference for a preferred activity for
4650                // this Intent, use that.
4651                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4652                        flags, query, r0.priority, true, false, debug, userId);
4653                if (ri != null) {
4654                    return ri;
4655                }
4656                ri = new ResolveInfo(mResolveInfo);
4657                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4658                ri.activityInfo.applicationInfo = new ApplicationInfo(
4659                        ri.activityInfo.applicationInfo);
4660                if (userId != 0) {
4661                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4662                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4663                }
4664                // Make sure that the resolver is displayable in car mode
4665                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4666                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4667                return ri;
4668            }
4669        }
4670        return null;
4671    }
4672
4673    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4674            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4675        final int N = query.size();
4676        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4677                .get(userId);
4678        // Get the list of persistent preferred activities that handle the intent
4679        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4680        List<PersistentPreferredActivity> pprefs = ppir != null
4681                ? ppir.queryIntent(intent, resolvedType,
4682                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4683                : null;
4684        if (pprefs != null && pprefs.size() > 0) {
4685            final int M = pprefs.size();
4686            for (int i=0; i<M; i++) {
4687                final PersistentPreferredActivity ppa = pprefs.get(i);
4688                if (DEBUG_PREFERRED || debug) {
4689                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4690                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4691                            + "\n  component=" + ppa.mComponent);
4692                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4693                }
4694                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4695                        flags | MATCH_DISABLED_COMPONENTS, userId);
4696                if (DEBUG_PREFERRED || debug) {
4697                    Slog.v(TAG, "Found persistent preferred activity:");
4698                    if (ai != null) {
4699                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4700                    } else {
4701                        Slog.v(TAG, "  null");
4702                    }
4703                }
4704                if (ai == null) {
4705                    // This previously registered persistent preferred activity
4706                    // component is no longer known. Ignore it and do NOT remove it.
4707                    continue;
4708                }
4709                for (int j=0; j<N; j++) {
4710                    final ResolveInfo ri = query.get(j);
4711                    if (!ri.activityInfo.applicationInfo.packageName
4712                            .equals(ai.applicationInfo.packageName)) {
4713                        continue;
4714                    }
4715                    if (!ri.activityInfo.name.equals(ai.name)) {
4716                        continue;
4717                    }
4718                    //  Found a persistent preference that can handle the intent.
4719                    if (DEBUG_PREFERRED || debug) {
4720                        Slog.v(TAG, "Returning persistent preferred activity: " +
4721                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4722                    }
4723                    return ri;
4724                }
4725            }
4726        }
4727        return null;
4728    }
4729
4730    // TODO: handle preferred activities missing while user has amnesia
4731    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4732            List<ResolveInfo> query, int priority, boolean always,
4733            boolean removeMatches, boolean debug, int userId) {
4734        if (!sUserManager.exists(userId)) return null;
4735        flags = updateFlagsForResolve(flags, userId, intent);
4736        // writer
4737        synchronized (mPackages) {
4738            if (intent.getSelector() != null) {
4739                intent = intent.getSelector();
4740            }
4741            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4742
4743            // Try to find a matching persistent preferred activity.
4744            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4745                    debug, userId);
4746
4747            // If a persistent preferred activity matched, use it.
4748            if (pri != null) {
4749                return pri;
4750            }
4751
4752            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4753            // Get the list of preferred activities that handle the intent
4754            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4755            List<PreferredActivity> prefs = pir != null
4756                    ? pir.queryIntent(intent, resolvedType,
4757                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4758                    : null;
4759            if (prefs != null && prefs.size() > 0) {
4760                boolean changed = false;
4761                try {
4762                    // First figure out how good the original match set is.
4763                    // We will only allow preferred activities that came
4764                    // from the same match quality.
4765                    int match = 0;
4766
4767                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4768
4769                    final int N = query.size();
4770                    for (int j=0; j<N; j++) {
4771                        final ResolveInfo ri = query.get(j);
4772                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4773                                + ": 0x" + Integer.toHexString(match));
4774                        if (ri.match > match) {
4775                            match = ri.match;
4776                        }
4777                    }
4778
4779                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4780                            + Integer.toHexString(match));
4781
4782                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4783                    final int M = prefs.size();
4784                    for (int i=0; i<M; i++) {
4785                        final PreferredActivity pa = prefs.get(i);
4786                        if (DEBUG_PREFERRED || debug) {
4787                            Slog.v(TAG, "Checking PreferredActivity ds="
4788                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4789                                    + "\n  component=" + pa.mPref.mComponent);
4790                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4791                        }
4792                        if (pa.mPref.mMatch != match) {
4793                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4794                                    + Integer.toHexString(pa.mPref.mMatch));
4795                            continue;
4796                        }
4797                        // If it's not an "always" type preferred activity and that's what we're
4798                        // looking for, skip it.
4799                        if (always && !pa.mPref.mAlways) {
4800                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4801                            continue;
4802                        }
4803                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4804                                flags | MATCH_DISABLED_COMPONENTS, userId);
4805                        if (DEBUG_PREFERRED || debug) {
4806                            Slog.v(TAG, "Found preferred activity:");
4807                            if (ai != null) {
4808                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4809                            } else {
4810                                Slog.v(TAG, "  null");
4811                            }
4812                        }
4813                        if (ai == null) {
4814                            // This previously registered preferred activity
4815                            // component is no longer known.  Most likely an update
4816                            // to the app was installed and in the new version this
4817                            // component no longer exists.  Clean it up by removing
4818                            // it from the preferred activities list, and skip it.
4819                            Slog.w(TAG, "Removing dangling preferred activity: "
4820                                    + pa.mPref.mComponent);
4821                            pir.removeFilter(pa);
4822                            changed = true;
4823                            continue;
4824                        }
4825                        for (int j=0; j<N; j++) {
4826                            final ResolveInfo ri = query.get(j);
4827                            if (!ri.activityInfo.applicationInfo.packageName
4828                                    .equals(ai.applicationInfo.packageName)) {
4829                                continue;
4830                            }
4831                            if (!ri.activityInfo.name.equals(ai.name)) {
4832                                continue;
4833                            }
4834
4835                            if (removeMatches) {
4836                                pir.removeFilter(pa);
4837                                changed = true;
4838                                if (DEBUG_PREFERRED) {
4839                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4840                                }
4841                                break;
4842                            }
4843
4844                            // Okay we found a previously set preferred or last chosen app.
4845                            // If the result set is different from when this
4846                            // was created, we need to clear it and re-ask the
4847                            // user their preference, if we're looking for an "always" type entry.
4848                            if (always && !pa.mPref.sameSet(query)) {
4849                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4850                                        + intent + " type " + resolvedType);
4851                                if (DEBUG_PREFERRED) {
4852                                    Slog.v(TAG, "Removing preferred activity since set changed "
4853                                            + pa.mPref.mComponent);
4854                                }
4855                                pir.removeFilter(pa);
4856                                // Re-add the filter as a "last chosen" entry (!always)
4857                                PreferredActivity lastChosen = new PreferredActivity(
4858                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4859                                pir.addFilter(lastChosen);
4860                                changed = true;
4861                                return null;
4862                            }
4863
4864                            // Yay! Either the set matched or we're looking for the last chosen
4865                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4866                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4867                            return ri;
4868                        }
4869                    }
4870                } finally {
4871                    if (changed) {
4872                        if (DEBUG_PREFERRED) {
4873                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4874                        }
4875                        scheduleWritePackageRestrictionsLocked(userId);
4876                    }
4877                }
4878            }
4879        }
4880        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4881        return null;
4882    }
4883
4884    /*
4885     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4886     */
4887    @Override
4888    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4889            int targetUserId) {
4890        mContext.enforceCallingOrSelfPermission(
4891                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4892        List<CrossProfileIntentFilter> matches =
4893                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4894        if (matches != null) {
4895            int size = matches.size();
4896            for (int i = 0; i < size; i++) {
4897                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4898            }
4899        }
4900        if (hasWebURI(intent)) {
4901            // cross-profile app linking works only towards the parent.
4902            final UserInfo parent = getProfileParent(sourceUserId);
4903            synchronized(mPackages) {
4904                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4905                        intent, resolvedType, 0, sourceUserId, parent.id);
4906                return xpDomainInfo != null;
4907            }
4908        }
4909        return false;
4910    }
4911
4912    private UserInfo getProfileParent(int userId) {
4913        final long identity = Binder.clearCallingIdentity();
4914        try {
4915            return sUserManager.getProfileParent(userId);
4916        } finally {
4917            Binder.restoreCallingIdentity(identity);
4918        }
4919    }
4920
4921    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4922            String resolvedType, int userId) {
4923        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4924        if (resolver != null) {
4925            return resolver.queryIntent(intent, resolvedType, false, userId);
4926        }
4927        return null;
4928    }
4929
4930    @Override
4931    public List<ResolveInfo> queryIntentActivities(Intent intent,
4932            String resolvedType, int flags, int userId) {
4933        if (!sUserManager.exists(userId)) return Collections.emptyList();
4934        flags = updateFlagsForResolve(flags, userId, intent);
4935        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4936        ComponentName comp = intent.getComponent();
4937        if (comp == null) {
4938            if (intent.getSelector() != null) {
4939                intent = intent.getSelector();
4940                comp = intent.getComponent();
4941            }
4942        }
4943
4944        if (comp != null) {
4945            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4946            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4947            if (ai != null) {
4948                final ResolveInfo ri = new ResolveInfo();
4949                ri.activityInfo = ai;
4950                list.add(ri);
4951            }
4952            return list;
4953        }
4954
4955        // reader
4956        synchronized (mPackages) {
4957            final String pkgName = intent.getPackage();
4958            if (pkgName == null) {
4959                List<CrossProfileIntentFilter> matchingFilters =
4960                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4961                // Check for results that need to skip the current profile.
4962                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4963                        resolvedType, flags, userId);
4964                if (xpResolveInfo != null) {
4965                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4966                    result.add(xpResolveInfo);
4967                    return filterIfNotSystemUser(result, userId);
4968                }
4969
4970                // Check for results in the current profile.
4971                List<ResolveInfo> result = mActivities.queryIntent(
4972                        intent, resolvedType, flags, userId);
4973                result = filterIfNotSystemUser(result, userId);
4974
4975                // Check for cross profile results.
4976                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4977                xpResolveInfo = queryCrossProfileIntents(
4978                        matchingFilters, intent, resolvedType, flags, userId,
4979                        hasNonNegativePriorityResult);
4980                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4981                    boolean isVisibleToUser = filterIfNotSystemUser(
4982                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4983                    if (isVisibleToUser) {
4984                        result.add(xpResolveInfo);
4985                        Collections.sort(result, mResolvePrioritySorter);
4986                    }
4987                }
4988                if (hasWebURI(intent)) {
4989                    CrossProfileDomainInfo xpDomainInfo = null;
4990                    final UserInfo parent = getProfileParent(userId);
4991                    if (parent != null) {
4992                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4993                                flags, userId, parent.id);
4994                    }
4995                    if (xpDomainInfo != null) {
4996                        if (xpResolveInfo != null) {
4997                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4998                            // in the result.
4999                            result.remove(xpResolveInfo);
5000                        }
5001                        if (result.size() == 0) {
5002                            result.add(xpDomainInfo.resolveInfo);
5003                            return result;
5004                        }
5005                    } else if (result.size() <= 1) {
5006                        return result;
5007                    }
5008                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5009                            xpDomainInfo, userId);
5010                    Collections.sort(result, mResolvePrioritySorter);
5011                }
5012                return result;
5013            }
5014            final PackageParser.Package pkg = mPackages.get(pkgName);
5015            if (pkg != null) {
5016                return filterIfNotSystemUser(
5017                        mActivities.queryIntentForPackage(
5018                                intent, resolvedType, flags, pkg.activities, userId),
5019                        userId);
5020            }
5021            return new ArrayList<ResolveInfo>();
5022        }
5023    }
5024
5025    private static class CrossProfileDomainInfo {
5026        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5027        ResolveInfo resolveInfo;
5028        /* Best domain verification status of the activities found in the other profile */
5029        int bestDomainVerificationStatus;
5030    }
5031
5032    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5033            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5034        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5035                sourceUserId)) {
5036            return null;
5037        }
5038        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5039                resolvedType, flags, parentUserId);
5040
5041        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5042            return null;
5043        }
5044        CrossProfileDomainInfo result = null;
5045        int size = resultTargetUser.size();
5046        for (int i = 0; i < size; i++) {
5047            ResolveInfo riTargetUser = resultTargetUser.get(i);
5048            // Intent filter verification is only for filters that specify a host. So don't return
5049            // those that handle all web uris.
5050            if (riTargetUser.handleAllWebDataURI) {
5051                continue;
5052            }
5053            String packageName = riTargetUser.activityInfo.packageName;
5054            PackageSetting ps = mSettings.mPackages.get(packageName);
5055            if (ps == null) {
5056                continue;
5057            }
5058            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5059            int status = (int)(verificationState >> 32);
5060            if (result == null) {
5061                result = new CrossProfileDomainInfo();
5062                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5063                        sourceUserId, parentUserId);
5064                result.bestDomainVerificationStatus = status;
5065            } else {
5066                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5067                        result.bestDomainVerificationStatus);
5068            }
5069        }
5070        // Don't consider matches with status NEVER across profiles.
5071        if (result != null && result.bestDomainVerificationStatus
5072                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5073            return null;
5074        }
5075        return result;
5076    }
5077
5078    /**
5079     * Verification statuses are ordered from the worse to the best, except for
5080     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5081     */
5082    private int bestDomainVerificationStatus(int status1, int status2) {
5083        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5084            return status2;
5085        }
5086        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5087            return status1;
5088        }
5089        return (int) MathUtils.max(status1, status2);
5090    }
5091
5092    private boolean isUserEnabled(int userId) {
5093        long callingId = Binder.clearCallingIdentity();
5094        try {
5095            UserInfo userInfo = sUserManager.getUserInfo(userId);
5096            return userInfo != null && userInfo.isEnabled();
5097        } finally {
5098            Binder.restoreCallingIdentity(callingId);
5099        }
5100    }
5101
5102    /**
5103     * Filter out activities with systemUserOnly flag set, when current user is not System.
5104     *
5105     * @return filtered list
5106     */
5107    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5108        if (userId == UserHandle.USER_SYSTEM) {
5109            return resolveInfos;
5110        }
5111        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5112            ResolveInfo info = resolveInfos.get(i);
5113            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5114                resolveInfos.remove(i);
5115            }
5116        }
5117        return resolveInfos;
5118    }
5119
5120    /**
5121     * @param resolveInfos list of resolve infos in descending priority order
5122     * @return if the list contains a resolve info with non-negative priority
5123     */
5124    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5125        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5126    }
5127
5128    private static boolean hasWebURI(Intent intent) {
5129        if (intent.getData() == null) {
5130            return false;
5131        }
5132        final String scheme = intent.getScheme();
5133        if (TextUtils.isEmpty(scheme)) {
5134            return false;
5135        }
5136        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5137    }
5138
5139    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5140            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5141            int userId) {
5142        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5143
5144        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5145            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5146                    candidates.size());
5147        }
5148
5149        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5150        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5151        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5152        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5153        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5154        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5155
5156        synchronized (mPackages) {
5157            final int count = candidates.size();
5158            // First, try to use linked apps. Partition the candidates into four lists:
5159            // one for the final results, one for the "do not use ever", one for "undefined status"
5160            // and finally one for "browser app type".
5161            for (int n=0; n<count; n++) {
5162                ResolveInfo info = candidates.get(n);
5163                String packageName = info.activityInfo.packageName;
5164                PackageSetting ps = mSettings.mPackages.get(packageName);
5165                if (ps != null) {
5166                    // Add to the special match all list (Browser use case)
5167                    if (info.handleAllWebDataURI) {
5168                        matchAllList.add(info);
5169                        continue;
5170                    }
5171                    // Try to get the status from User settings first
5172                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5173                    int status = (int)(packedStatus >> 32);
5174                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5175                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5176                        if (DEBUG_DOMAIN_VERIFICATION) {
5177                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5178                                    + " : linkgen=" + linkGeneration);
5179                        }
5180                        // Use link-enabled generation as preferredOrder, i.e.
5181                        // prefer newly-enabled over earlier-enabled.
5182                        info.preferredOrder = linkGeneration;
5183                        alwaysList.add(info);
5184                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5185                        if (DEBUG_DOMAIN_VERIFICATION) {
5186                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5187                        }
5188                        neverList.add(info);
5189                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5190                        if (DEBUG_DOMAIN_VERIFICATION) {
5191                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5192                        }
5193                        alwaysAskList.add(info);
5194                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5195                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5196                        if (DEBUG_DOMAIN_VERIFICATION) {
5197                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5198                        }
5199                        undefinedList.add(info);
5200                    }
5201                }
5202            }
5203
5204            // We'll want to include browser possibilities in a few cases
5205            boolean includeBrowser = false;
5206
5207            // First try to add the "always" resolution(s) for the current user, if any
5208            if (alwaysList.size() > 0) {
5209                result.addAll(alwaysList);
5210            } else {
5211                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5212                result.addAll(undefinedList);
5213                // Maybe add one for the other profile.
5214                if (xpDomainInfo != null && (
5215                        xpDomainInfo.bestDomainVerificationStatus
5216                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5217                    result.add(xpDomainInfo.resolveInfo);
5218                }
5219                includeBrowser = true;
5220            }
5221
5222            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5223            // If there were 'always' entries their preferred order has been set, so we also
5224            // back that off to make the alternatives equivalent
5225            if (alwaysAskList.size() > 0) {
5226                for (ResolveInfo i : result) {
5227                    i.preferredOrder = 0;
5228                }
5229                result.addAll(alwaysAskList);
5230                includeBrowser = true;
5231            }
5232
5233            if (includeBrowser) {
5234                // Also add browsers (all of them or only the default one)
5235                if (DEBUG_DOMAIN_VERIFICATION) {
5236                    Slog.v(TAG, "   ...including browsers in candidate set");
5237                }
5238                if ((matchFlags & MATCH_ALL) != 0) {
5239                    result.addAll(matchAllList);
5240                } else {
5241                    // Browser/generic handling case.  If there's a default browser, go straight
5242                    // to that (but only if there is no other higher-priority match).
5243                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5244                    int maxMatchPrio = 0;
5245                    ResolveInfo defaultBrowserMatch = null;
5246                    final int numCandidates = matchAllList.size();
5247                    for (int n = 0; n < numCandidates; n++) {
5248                        ResolveInfo info = matchAllList.get(n);
5249                        // track the highest overall match priority...
5250                        if (info.priority > maxMatchPrio) {
5251                            maxMatchPrio = info.priority;
5252                        }
5253                        // ...and the highest-priority default browser match
5254                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5255                            if (defaultBrowserMatch == null
5256                                    || (defaultBrowserMatch.priority < info.priority)) {
5257                                if (debug) {
5258                                    Slog.v(TAG, "Considering default browser match " + info);
5259                                }
5260                                defaultBrowserMatch = info;
5261                            }
5262                        }
5263                    }
5264                    if (defaultBrowserMatch != null
5265                            && defaultBrowserMatch.priority >= maxMatchPrio
5266                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5267                    {
5268                        if (debug) {
5269                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5270                        }
5271                        result.add(defaultBrowserMatch);
5272                    } else {
5273                        result.addAll(matchAllList);
5274                    }
5275                }
5276
5277                // If there is nothing selected, add all candidates and remove the ones that the user
5278                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5279                if (result.size() == 0) {
5280                    result.addAll(candidates);
5281                    result.removeAll(neverList);
5282                }
5283            }
5284        }
5285        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5286            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5287                    result.size());
5288            for (ResolveInfo info : result) {
5289                Slog.v(TAG, "  + " + info.activityInfo);
5290            }
5291        }
5292        return result;
5293    }
5294
5295    // Returns a packed value as a long:
5296    //
5297    // high 'int'-sized word: link status: undefined/ask/never/always.
5298    // low 'int'-sized word: relative priority among 'always' results.
5299    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5300        long result = ps.getDomainVerificationStatusForUser(userId);
5301        // if none available, get the master status
5302        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5303            if (ps.getIntentFilterVerificationInfo() != null) {
5304                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5305            }
5306        }
5307        return result;
5308    }
5309
5310    private ResolveInfo querySkipCurrentProfileIntents(
5311            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5312            int flags, int sourceUserId) {
5313        if (matchingFilters != null) {
5314            int size = matchingFilters.size();
5315            for (int i = 0; i < size; i ++) {
5316                CrossProfileIntentFilter filter = matchingFilters.get(i);
5317                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5318                    // Checking if there are activities in the target user that can handle the
5319                    // intent.
5320                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5321                            resolvedType, flags, sourceUserId);
5322                    if (resolveInfo != null) {
5323                        return resolveInfo;
5324                    }
5325                }
5326            }
5327        }
5328        return null;
5329    }
5330
5331    // Return matching ResolveInfo in target user if any.
5332    private ResolveInfo queryCrossProfileIntents(
5333            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5334            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5335        if (matchingFilters != null) {
5336            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5337            // match the same intent. For performance reasons, it is better not to
5338            // run queryIntent twice for the same userId
5339            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5340            int size = matchingFilters.size();
5341            for (int i = 0; i < size; i++) {
5342                CrossProfileIntentFilter filter = matchingFilters.get(i);
5343                int targetUserId = filter.getTargetUserId();
5344                boolean skipCurrentProfile =
5345                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5346                boolean skipCurrentProfileIfNoMatchFound =
5347                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5348                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5349                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5350                    // Checking if there are activities in the target user that can handle the
5351                    // intent.
5352                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5353                            resolvedType, flags, sourceUserId);
5354                    if (resolveInfo != null) return resolveInfo;
5355                    alreadyTriedUserIds.put(targetUserId, true);
5356                }
5357            }
5358        }
5359        return null;
5360    }
5361
5362    /**
5363     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5364     * will forward the intent to the filter's target user.
5365     * Otherwise, returns null.
5366     */
5367    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5368            String resolvedType, int flags, int sourceUserId) {
5369        int targetUserId = filter.getTargetUserId();
5370        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5371                resolvedType, flags, targetUserId);
5372        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5373                && isUserEnabled(targetUserId)) {
5374            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5375        }
5376        return null;
5377    }
5378
5379    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5380            int sourceUserId, int targetUserId) {
5381        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5382        long ident = Binder.clearCallingIdentity();
5383        boolean targetIsProfile;
5384        try {
5385            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5386        } finally {
5387            Binder.restoreCallingIdentity(ident);
5388        }
5389        String className;
5390        if (targetIsProfile) {
5391            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5392        } else {
5393            className = FORWARD_INTENT_TO_PARENT;
5394        }
5395        ComponentName forwardingActivityComponentName = new ComponentName(
5396                mAndroidApplication.packageName, className);
5397        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5398                sourceUserId);
5399        if (!targetIsProfile) {
5400            forwardingActivityInfo.showUserIcon = targetUserId;
5401            forwardingResolveInfo.noResourceId = true;
5402        }
5403        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5404        forwardingResolveInfo.priority = 0;
5405        forwardingResolveInfo.preferredOrder = 0;
5406        forwardingResolveInfo.match = 0;
5407        forwardingResolveInfo.isDefault = true;
5408        forwardingResolveInfo.filter = filter;
5409        forwardingResolveInfo.targetUserId = targetUserId;
5410        return forwardingResolveInfo;
5411    }
5412
5413    @Override
5414    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5415            Intent[] specifics, String[] specificTypes, Intent intent,
5416            String resolvedType, int flags, int userId) {
5417        if (!sUserManager.exists(userId)) return Collections.emptyList();
5418        flags = updateFlagsForResolve(flags, userId, intent);
5419        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5420                false, "query intent activity options");
5421        final String resultsAction = intent.getAction();
5422
5423        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5424                | PackageManager.GET_RESOLVED_FILTER, userId);
5425
5426        if (DEBUG_INTENT_MATCHING) {
5427            Log.v(TAG, "Query " + intent + ": " + results);
5428        }
5429
5430        int specificsPos = 0;
5431        int N;
5432
5433        // todo: note that the algorithm used here is O(N^2).  This
5434        // isn't a problem in our current environment, but if we start running
5435        // into situations where we have more than 5 or 10 matches then this
5436        // should probably be changed to something smarter...
5437
5438        // First we go through and resolve each of the specific items
5439        // that were supplied, taking care of removing any corresponding
5440        // duplicate items in the generic resolve list.
5441        if (specifics != null) {
5442            for (int i=0; i<specifics.length; i++) {
5443                final Intent sintent = specifics[i];
5444                if (sintent == null) {
5445                    continue;
5446                }
5447
5448                if (DEBUG_INTENT_MATCHING) {
5449                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5450                }
5451
5452                String action = sintent.getAction();
5453                if (resultsAction != null && resultsAction.equals(action)) {
5454                    // If this action was explicitly requested, then don't
5455                    // remove things that have it.
5456                    action = null;
5457                }
5458
5459                ResolveInfo ri = null;
5460                ActivityInfo ai = null;
5461
5462                ComponentName comp = sintent.getComponent();
5463                if (comp == null) {
5464                    ri = resolveIntent(
5465                        sintent,
5466                        specificTypes != null ? specificTypes[i] : null,
5467                            flags, userId);
5468                    if (ri == null) {
5469                        continue;
5470                    }
5471                    if (ri == mResolveInfo) {
5472                        // ACK!  Must do something better with this.
5473                    }
5474                    ai = ri.activityInfo;
5475                    comp = new ComponentName(ai.applicationInfo.packageName,
5476                            ai.name);
5477                } else {
5478                    ai = getActivityInfo(comp, flags, userId);
5479                    if (ai == null) {
5480                        continue;
5481                    }
5482                }
5483
5484                // Look for any generic query activities that are duplicates
5485                // of this specific one, and remove them from the results.
5486                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5487                N = results.size();
5488                int j;
5489                for (j=specificsPos; j<N; j++) {
5490                    ResolveInfo sri = results.get(j);
5491                    if ((sri.activityInfo.name.equals(comp.getClassName())
5492                            && sri.activityInfo.applicationInfo.packageName.equals(
5493                                    comp.getPackageName()))
5494                        || (action != null && sri.filter.matchAction(action))) {
5495                        results.remove(j);
5496                        if (DEBUG_INTENT_MATCHING) Log.v(
5497                            TAG, "Removing duplicate item from " + j
5498                            + " due to specific " + specificsPos);
5499                        if (ri == null) {
5500                            ri = sri;
5501                        }
5502                        j--;
5503                        N--;
5504                    }
5505                }
5506
5507                // Add this specific item to its proper place.
5508                if (ri == null) {
5509                    ri = new ResolveInfo();
5510                    ri.activityInfo = ai;
5511                }
5512                results.add(specificsPos, ri);
5513                ri.specificIndex = i;
5514                specificsPos++;
5515            }
5516        }
5517
5518        // Now we go through the remaining generic results and remove any
5519        // duplicate actions that are found here.
5520        N = results.size();
5521        for (int i=specificsPos; i<N-1; i++) {
5522            final ResolveInfo rii = results.get(i);
5523            if (rii.filter == null) {
5524                continue;
5525            }
5526
5527            // Iterate over all of the actions of this result's intent
5528            // filter...  typically this should be just one.
5529            final Iterator<String> it = rii.filter.actionsIterator();
5530            if (it == null) {
5531                continue;
5532            }
5533            while (it.hasNext()) {
5534                final String action = it.next();
5535                if (resultsAction != null && resultsAction.equals(action)) {
5536                    // If this action was explicitly requested, then don't
5537                    // remove things that have it.
5538                    continue;
5539                }
5540                for (int j=i+1; j<N; j++) {
5541                    final ResolveInfo rij = results.get(j);
5542                    if (rij.filter != null && rij.filter.hasAction(action)) {
5543                        results.remove(j);
5544                        if (DEBUG_INTENT_MATCHING) Log.v(
5545                            TAG, "Removing duplicate item from " + j
5546                            + " due to action " + action + " at " + i);
5547                        j--;
5548                        N--;
5549                    }
5550                }
5551            }
5552
5553            // If the caller didn't request filter information, drop it now
5554            // so we don't have to marshall/unmarshall it.
5555            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5556                rii.filter = null;
5557            }
5558        }
5559
5560        // Filter out the caller activity if so requested.
5561        if (caller != null) {
5562            N = results.size();
5563            for (int i=0; i<N; i++) {
5564                ActivityInfo ainfo = results.get(i).activityInfo;
5565                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5566                        && caller.getClassName().equals(ainfo.name)) {
5567                    results.remove(i);
5568                    break;
5569                }
5570            }
5571        }
5572
5573        // If the caller didn't request filter information,
5574        // drop them now so we don't have to
5575        // marshall/unmarshall it.
5576        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5577            N = results.size();
5578            for (int i=0; i<N; i++) {
5579                results.get(i).filter = null;
5580            }
5581        }
5582
5583        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5584        return results;
5585    }
5586
5587    @Override
5588    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5589            int userId) {
5590        if (!sUserManager.exists(userId)) return Collections.emptyList();
5591        flags = updateFlagsForResolve(flags, userId, intent);
5592        ComponentName comp = intent.getComponent();
5593        if (comp == null) {
5594            if (intent.getSelector() != null) {
5595                intent = intent.getSelector();
5596                comp = intent.getComponent();
5597            }
5598        }
5599        if (comp != null) {
5600            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5601            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5602            if (ai != null) {
5603                ResolveInfo ri = new ResolveInfo();
5604                ri.activityInfo = ai;
5605                list.add(ri);
5606            }
5607            return list;
5608        }
5609
5610        // reader
5611        synchronized (mPackages) {
5612            String pkgName = intent.getPackage();
5613            if (pkgName == null) {
5614                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5615            }
5616            final PackageParser.Package pkg = mPackages.get(pkgName);
5617            if (pkg != null) {
5618                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5619                        userId);
5620            }
5621            return null;
5622        }
5623    }
5624
5625    @Override
5626    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5627        if (!sUserManager.exists(userId)) return null;
5628        flags = updateFlagsForResolve(flags, userId, intent);
5629        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5630        if (query != null) {
5631            if (query.size() >= 1) {
5632                // If there is more than one service with the same priority,
5633                // just arbitrarily pick the first one.
5634                return query.get(0);
5635            }
5636        }
5637        return null;
5638    }
5639
5640    @Override
5641    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5642            int userId) {
5643        if (!sUserManager.exists(userId)) return Collections.emptyList();
5644        flags = updateFlagsForResolve(flags, userId, intent);
5645        ComponentName comp = intent.getComponent();
5646        if (comp == null) {
5647            if (intent.getSelector() != null) {
5648                intent = intent.getSelector();
5649                comp = intent.getComponent();
5650            }
5651        }
5652        if (comp != null) {
5653            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5654            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5655            if (si != null) {
5656                final ResolveInfo ri = new ResolveInfo();
5657                ri.serviceInfo = si;
5658                list.add(ri);
5659            }
5660            return list;
5661        }
5662
5663        // reader
5664        synchronized (mPackages) {
5665            String pkgName = intent.getPackage();
5666            if (pkgName == null) {
5667                return mServices.queryIntent(intent, resolvedType, flags, userId);
5668            }
5669            final PackageParser.Package pkg = mPackages.get(pkgName);
5670            if (pkg != null) {
5671                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5672                        userId);
5673            }
5674            return null;
5675        }
5676    }
5677
5678    @Override
5679    public List<ResolveInfo> queryIntentContentProviders(
5680            Intent intent, String resolvedType, int flags, int userId) {
5681        if (!sUserManager.exists(userId)) return Collections.emptyList();
5682        flags = updateFlagsForResolve(flags, userId, intent);
5683        ComponentName comp = intent.getComponent();
5684        if (comp == null) {
5685            if (intent.getSelector() != null) {
5686                intent = intent.getSelector();
5687                comp = intent.getComponent();
5688            }
5689        }
5690        if (comp != null) {
5691            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5692            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5693            if (pi != null) {
5694                final ResolveInfo ri = new ResolveInfo();
5695                ri.providerInfo = pi;
5696                list.add(ri);
5697            }
5698            return list;
5699        }
5700
5701        // reader
5702        synchronized (mPackages) {
5703            String pkgName = intent.getPackage();
5704            if (pkgName == null) {
5705                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5706            }
5707            final PackageParser.Package pkg = mPackages.get(pkgName);
5708            if (pkg != null) {
5709                return mProviders.queryIntentForPackage(
5710                        intent, resolvedType, flags, pkg.providers, userId);
5711            }
5712            return null;
5713        }
5714    }
5715
5716    @Override
5717    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5718        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5719        flags = updateFlagsForPackage(flags, userId, null);
5720        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5721        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5722
5723        // writer
5724        synchronized (mPackages) {
5725            ArrayList<PackageInfo> list;
5726            if (listUninstalled) {
5727                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5728                for (PackageSetting ps : mSettings.mPackages.values()) {
5729                    PackageInfo pi;
5730                    if (ps.pkg != null) {
5731                        pi = generatePackageInfo(ps.pkg, flags, userId);
5732                    } else {
5733                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5734                    }
5735                    if (pi != null) {
5736                        list.add(pi);
5737                    }
5738                }
5739            } else {
5740                list = new ArrayList<PackageInfo>(mPackages.size());
5741                for (PackageParser.Package p : mPackages.values()) {
5742                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5743                    if (pi != null) {
5744                        list.add(pi);
5745                    }
5746                }
5747            }
5748
5749            return new ParceledListSlice<PackageInfo>(list);
5750        }
5751    }
5752
5753    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5754            String[] permissions, boolean[] tmp, int flags, int userId) {
5755        int numMatch = 0;
5756        final PermissionsState permissionsState = ps.getPermissionsState();
5757        for (int i=0; i<permissions.length; i++) {
5758            final String permission = permissions[i];
5759            if (permissionsState.hasPermission(permission, userId)) {
5760                tmp[i] = true;
5761                numMatch++;
5762            } else {
5763                tmp[i] = false;
5764            }
5765        }
5766        if (numMatch == 0) {
5767            return;
5768        }
5769        PackageInfo pi;
5770        if (ps.pkg != null) {
5771            pi = generatePackageInfo(ps.pkg, flags, userId);
5772        } else {
5773            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5774        }
5775        // The above might return null in cases of uninstalled apps or install-state
5776        // skew across users/profiles.
5777        if (pi != null) {
5778            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5779                if (numMatch == permissions.length) {
5780                    pi.requestedPermissions = permissions;
5781                } else {
5782                    pi.requestedPermissions = new String[numMatch];
5783                    numMatch = 0;
5784                    for (int i=0; i<permissions.length; i++) {
5785                        if (tmp[i]) {
5786                            pi.requestedPermissions[numMatch] = permissions[i];
5787                            numMatch++;
5788                        }
5789                    }
5790                }
5791            }
5792            list.add(pi);
5793        }
5794    }
5795
5796    @Override
5797    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5798            String[] permissions, int flags, int userId) {
5799        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5800        flags = updateFlagsForPackage(flags, userId, permissions);
5801        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5802
5803        // writer
5804        synchronized (mPackages) {
5805            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5806            boolean[] tmpBools = new boolean[permissions.length];
5807            if (listUninstalled) {
5808                for (PackageSetting ps : mSettings.mPackages.values()) {
5809                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5810                }
5811            } else {
5812                for (PackageParser.Package pkg : mPackages.values()) {
5813                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5814                    if (ps != null) {
5815                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5816                                userId);
5817                    }
5818                }
5819            }
5820
5821            return new ParceledListSlice<PackageInfo>(list);
5822        }
5823    }
5824
5825    @Override
5826    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5827        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5828        flags = updateFlagsForApplication(flags, userId, null);
5829        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5830
5831        // writer
5832        synchronized (mPackages) {
5833            ArrayList<ApplicationInfo> list;
5834            if (listUninstalled) {
5835                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5836                for (PackageSetting ps : mSettings.mPackages.values()) {
5837                    ApplicationInfo ai;
5838                    if (ps.pkg != null) {
5839                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5840                                ps.readUserState(userId), userId);
5841                    } else {
5842                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5843                    }
5844                    if (ai != null) {
5845                        list.add(ai);
5846                    }
5847                }
5848            } else {
5849                list = new ArrayList<ApplicationInfo>(mPackages.size());
5850                for (PackageParser.Package p : mPackages.values()) {
5851                    if (p.mExtras != null) {
5852                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5853                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5854                        if (ai != null) {
5855                            list.add(ai);
5856                        }
5857                    }
5858                }
5859            }
5860
5861            return new ParceledListSlice<ApplicationInfo>(list);
5862        }
5863    }
5864
5865    @Override
5866    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5867        if (DISABLE_EPHEMERAL_APPS) {
5868            return null;
5869        }
5870
5871        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5872                "getEphemeralApplications");
5873        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5874                "getEphemeralApplications");
5875        synchronized (mPackages) {
5876            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5877                    .getEphemeralApplicationsLPw(userId);
5878            if (ephemeralApps != null) {
5879                return new ParceledListSlice<>(ephemeralApps);
5880            }
5881        }
5882        return null;
5883    }
5884
5885    @Override
5886    public boolean isEphemeralApplication(String packageName, int userId) {
5887        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5888                "isEphemeral");
5889        if (DISABLE_EPHEMERAL_APPS) {
5890            return false;
5891        }
5892
5893        if (!isCallerSameApp(packageName)) {
5894            return false;
5895        }
5896        synchronized (mPackages) {
5897            PackageParser.Package pkg = mPackages.get(packageName);
5898            if (pkg != null) {
5899                return pkg.applicationInfo.isEphemeralApp();
5900            }
5901        }
5902        return false;
5903    }
5904
5905    @Override
5906    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5907        if (DISABLE_EPHEMERAL_APPS) {
5908            return null;
5909        }
5910
5911        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5912                "getCookie");
5913        if (!isCallerSameApp(packageName)) {
5914            return null;
5915        }
5916        synchronized (mPackages) {
5917            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5918                    packageName, userId);
5919        }
5920    }
5921
5922    @Override
5923    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5924        if (DISABLE_EPHEMERAL_APPS) {
5925            return true;
5926        }
5927
5928        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5929                "setCookie");
5930        if (!isCallerSameApp(packageName)) {
5931            return false;
5932        }
5933        synchronized (mPackages) {
5934            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5935                    packageName, cookie, userId);
5936        }
5937    }
5938
5939    @Override
5940    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5941        if (DISABLE_EPHEMERAL_APPS) {
5942            return null;
5943        }
5944
5945        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5946                "getEphemeralApplicationIcon");
5947        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5948                "getEphemeralApplicationIcon");
5949        synchronized (mPackages) {
5950            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5951                    packageName, userId);
5952        }
5953    }
5954
5955    private boolean isCallerSameApp(String packageName) {
5956        PackageParser.Package pkg = mPackages.get(packageName);
5957        return pkg != null
5958                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5959    }
5960
5961    public List<ApplicationInfo> getPersistentApplications(int flags) {
5962        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5963
5964        // reader
5965        synchronized (mPackages) {
5966            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5967            final int userId = UserHandle.getCallingUserId();
5968            while (i.hasNext()) {
5969                final PackageParser.Package p = i.next();
5970                if (p.applicationInfo != null
5971                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5972                        && (!mSafeMode || isSystemApp(p))) {
5973                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5974                    if (ps != null) {
5975                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5976                                ps.readUserState(userId), userId);
5977                        if (ai != null) {
5978                            finalList.add(ai);
5979                        }
5980                    }
5981                }
5982            }
5983        }
5984
5985        return finalList;
5986    }
5987
5988    @Override
5989    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5990        if (!sUserManager.exists(userId)) return null;
5991        flags = updateFlagsForComponent(flags, userId, name);
5992        // reader
5993        synchronized (mPackages) {
5994            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5995            PackageSetting ps = provider != null
5996                    ? mSettings.mPackages.get(provider.owner.packageName)
5997                    : null;
5998            return ps != null
5999                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6000                    ? PackageParser.generateProviderInfo(provider, flags,
6001                            ps.readUserState(userId), userId)
6002                    : null;
6003        }
6004    }
6005
6006    /**
6007     * @deprecated
6008     */
6009    @Deprecated
6010    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6011        // reader
6012        synchronized (mPackages) {
6013            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6014                    .entrySet().iterator();
6015            final int userId = UserHandle.getCallingUserId();
6016            while (i.hasNext()) {
6017                Map.Entry<String, PackageParser.Provider> entry = i.next();
6018                PackageParser.Provider p = entry.getValue();
6019                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6020
6021                if (ps != null && p.syncable
6022                        && (!mSafeMode || (p.info.applicationInfo.flags
6023                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6024                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6025                            ps.readUserState(userId), userId);
6026                    if (info != null) {
6027                        outNames.add(entry.getKey());
6028                        outInfo.add(info);
6029                    }
6030                }
6031            }
6032        }
6033    }
6034
6035    @Override
6036    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6037            int uid, int flags) {
6038        final int userId = processName != null ? UserHandle.getUserId(uid)
6039                : UserHandle.getCallingUserId();
6040        if (!sUserManager.exists(userId)) return null;
6041        flags = updateFlagsForComponent(flags, userId, processName);
6042
6043        ArrayList<ProviderInfo> finalList = null;
6044        // reader
6045        synchronized (mPackages) {
6046            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6047            while (i.hasNext()) {
6048                final PackageParser.Provider p = i.next();
6049                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6050                if (ps != null && p.info.authority != null
6051                        && (processName == null
6052                                || (p.info.processName.equals(processName)
6053                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6054                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6055                    if (finalList == null) {
6056                        finalList = new ArrayList<ProviderInfo>(3);
6057                    }
6058                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6059                            ps.readUserState(userId), userId);
6060                    if (info != null) {
6061                        finalList.add(info);
6062                    }
6063                }
6064            }
6065        }
6066
6067        if (finalList != null) {
6068            Collections.sort(finalList, mProviderInitOrderSorter);
6069            return new ParceledListSlice<ProviderInfo>(finalList);
6070        }
6071
6072        return null;
6073    }
6074
6075    @Override
6076    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6077        // reader
6078        synchronized (mPackages) {
6079            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6080            return PackageParser.generateInstrumentationInfo(i, flags);
6081        }
6082    }
6083
6084    @Override
6085    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6086            int flags) {
6087        ArrayList<InstrumentationInfo> finalList =
6088            new ArrayList<InstrumentationInfo>();
6089
6090        // reader
6091        synchronized (mPackages) {
6092            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6093            while (i.hasNext()) {
6094                final PackageParser.Instrumentation p = i.next();
6095                if (targetPackage == null
6096                        || targetPackage.equals(p.info.targetPackage)) {
6097                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6098                            flags);
6099                    if (ii != null) {
6100                        finalList.add(ii);
6101                    }
6102                }
6103            }
6104        }
6105
6106        return finalList;
6107    }
6108
6109    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6110        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6111        if (overlays == null) {
6112            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6113            return;
6114        }
6115        for (PackageParser.Package opkg : overlays.values()) {
6116            // Not much to do if idmap fails: we already logged the error
6117            // and we certainly don't want to abort installation of pkg simply
6118            // because an overlay didn't fit properly. For these reasons,
6119            // ignore the return value of createIdmapForPackagePairLI.
6120            createIdmapForPackagePairLI(pkg, opkg);
6121        }
6122    }
6123
6124    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6125            PackageParser.Package opkg) {
6126        if (!opkg.mTrustedOverlay) {
6127            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6128                    opkg.baseCodePath + ": overlay not trusted");
6129            return false;
6130        }
6131        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6132        if (overlaySet == null) {
6133            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6134                    opkg.baseCodePath + " but target package has no known overlays");
6135            return false;
6136        }
6137        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6138        // TODO: generate idmap for split APKs
6139        try {
6140            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6141        } catch (InstallerException e) {
6142            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6143                    + opkg.baseCodePath);
6144            return false;
6145        }
6146        PackageParser.Package[] overlayArray =
6147            overlaySet.values().toArray(new PackageParser.Package[0]);
6148        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6149            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6150                return p1.mOverlayPriority - p2.mOverlayPriority;
6151            }
6152        };
6153        Arrays.sort(overlayArray, cmp);
6154
6155        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6156        int i = 0;
6157        for (PackageParser.Package p : overlayArray) {
6158            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6159        }
6160        return true;
6161    }
6162
6163    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6164        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6165        try {
6166            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6167        } finally {
6168            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6169        }
6170    }
6171
6172    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6173        final File[] files = dir.listFiles();
6174        if (ArrayUtils.isEmpty(files)) {
6175            Log.d(TAG, "No files in app dir " + dir);
6176            return;
6177        }
6178
6179        if (DEBUG_PACKAGE_SCANNING) {
6180            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6181                    + " flags=0x" + Integer.toHexString(parseFlags));
6182        }
6183
6184        for (File file : files) {
6185            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6186                    && !PackageInstallerService.isStageName(file.getName());
6187            if (!isPackage) {
6188                // Ignore entries which are not packages
6189                continue;
6190            }
6191            try {
6192                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6193                        scanFlags, currentTime, null);
6194            } catch (PackageManagerException e) {
6195                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6196
6197                // Delete invalid userdata apps
6198                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6199                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6200                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6201                    removeCodePathLI(file);
6202                }
6203            }
6204        }
6205    }
6206
6207    private static File getSettingsProblemFile() {
6208        File dataDir = Environment.getDataDirectory();
6209        File systemDir = new File(dataDir, "system");
6210        File fname = new File(systemDir, "uiderrors.txt");
6211        return fname;
6212    }
6213
6214    static void reportSettingsProblem(int priority, String msg) {
6215        logCriticalInfo(priority, msg);
6216    }
6217
6218    static void logCriticalInfo(int priority, String msg) {
6219        Slog.println(priority, TAG, msg);
6220        EventLogTags.writePmCriticalInfo(msg);
6221        try {
6222            File fname = getSettingsProblemFile();
6223            FileOutputStream out = new FileOutputStream(fname, true);
6224            PrintWriter pw = new FastPrintWriter(out);
6225            SimpleDateFormat formatter = new SimpleDateFormat();
6226            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6227            pw.println(dateString + ": " + msg);
6228            pw.close();
6229            FileUtils.setPermissions(
6230                    fname.toString(),
6231                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6232                    -1, -1);
6233        } catch (java.io.IOException e) {
6234        }
6235    }
6236
6237    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6238            PackageParser.Package pkg, File srcFile, int parseFlags)
6239            throws PackageManagerException {
6240        if (ps != null
6241                && ps.codePath.equals(srcFile)
6242                && ps.timeStamp == srcFile.lastModified()
6243                && !isCompatSignatureUpdateNeeded(pkg)
6244                && !isRecoverSignatureUpdateNeeded(pkg)) {
6245            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6246            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6247            ArraySet<PublicKey> signingKs;
6248            synchronized (mPackages) {
6249                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6250            }
6251            if (ps.signatures.mSignatures != null
6252                    && ps.signatures.mSignatures.length != 0
6253                    && signingKs != null) {
6254                // Optimization: reuse the existing cached certificates
6255                // if the package appears to be unchanged.
6256                pkg.mSignatures = ps.signatures.mSignatures;
6257                pkg.mSigningKeys = signingKs;
6258                return;
6259            }
6260
6261            Slog.w(TAG, "PackageSetting for " + ps.name
6262                    + " is missing signatures.  Collecting certs again to recover them.");
6263        } else {
6264            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6265        }
6266
6267        try {
6268            pp.collectCertificates(pkg, parseFlags);
6269        } catch (PackageParserException e) {
6270            throw PackageManagerException.from(e);
6271        }
6272    }
6273
6274    /**
6275     *  Traces a package scan.
6276     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6277     */
6278    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6279            long currentTime, UserHandle user) throws PackageManagerException {
6280        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6281        try {
6282            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6283        } finally {
6284            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6285        }
6286    }
6287
6288    /**
6289     *  Scans a package and returns the newly parsed package.
6290     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6291     */
6292    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6293            long currentTime, UserHandle user) throws PackageManagerException {
6294        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6295        parseFlags |= mDefParseFlags;
6296        PackageParser pp = new PackageParser();
6297        pp.setSeparateProcesses(mSeparateProcesses);
6298        pp.setOnlyCoreApps(mOnlyCore);
6299        pp.setDisplayMetrics(mMetrics);
6300
6301        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6302            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6303        }
6304
6305        final PackageParser.Package pkg;
6306        try {
6307            pkg = pp.parsePackage(scanFile, parseFlags);
6308        } catch (PackageParserException e) {
6309            throw PackageManagerException.from(e);
6310        }
6311
6312        PackageSetting ps = null;
6313        PackageSetting updatedPkg;
6314        // reader
6315        synchronized (mPackages) {
6316            // Look to see if we already know about this package.
6317            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6318            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6319                // This package has been renamed to its original name.  Let's
6320                // use that.
6321                ps = mSettings.peekPackageLPr(oldName);
6322            }
6323            // If there was no original package, see one for the real package name.
6324            if (ps == null) {
6325                ps = mSettings.peekPackageLPr(pkg.packageName);
6326            }
6327            // Check to see if this package could be hiding/updating a system
6328            // package.  Must look for it either under the original or real
6329            // package name depending on our state.
6330            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6331            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6332        }
6333        boolean updatedPkgBetter = false;
6334        // First check if this is a system package that may involve an update
6335        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6336            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6337            // it needs to drop FLAG_PRIVILEGED.
6338            if (locationIsPrivileged(scanFile)) {
6339                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6340            } else {
6341                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6342            }
6343
6344            if (ps != null && !ps.codePath.equals(scanFile)) {
6345                // The path has changed from what was last scanned...  check the
6346                // version of the new path against what we have stored to determine
6347                // what to do.
6348                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6349                if (pkg.mVersionCode <= ps.versionCode) {
6350                    // The system package has been updated and the code path does not match
6351                    // Ignore entry. Skip it.
6352                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6353                            + " ignored: updated version " + ps.versionCode
6354                            + " better than this " + pkg.mVersionCode);
6355                    if (!updatedPkg.codePath.equals(scanFile)) {
6356                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6357                                + ps.name + " changing from " + updatedPkg.codePathString
6358                                + " to " + scanFile);
6359                        updatedPkg.codePath = scanFile;
6360                        updatedPkg.codePathString = scanFile.toString();
6361                        updatedPkg.resourcePath = scanFile;
6362                        updatedPkg.resourcePathString = scanFile.toString();
6363                    }
6364                    updatedPkg.pkg = pkg;
6365                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6366                            "Package " + ps.name + " at " + scanFile
6367                                    + " ignored: updated version " + ps.versionCode
6368                                    + " better than this " + pkg.mVersionCode);
6369                } else {
6370                    // The current app on the system partition is better than
6371                    // what we have updated to on the data partition; switch
6372                    // back to the system partition version.
6373                    // At this point, its safely assumed that package installation for
6374                    // apps in system partition will go through. If not there won't be a working
6375                    // version of the app
6376                    // writer
6377                    synchronized (mPackages) {
6378                        // Just remove the loaded entries from package lists.
6379                        mPackages.remove(ps.name);
6380                    }
6381
6382                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6383                            + " reverting from " + ps.codePathString
6384                            + ": new version " + pkg.mVersionCode
6385                            + " better than installed " + ps.versionCode);
6386
6387                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6388                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6389                    synchronized (mInstallLock) {
6390                        args.cleanUpResourcesLI();
6391                    }
6392                    synchronized (mPackages) {
6393                        mSettings.enableSystemPackageLPw(ps.name);
6394                    }
6395                    updatedPkgBetter = true;
6396                }
6397            }
6398        }
6399
6400        if (updatedPkg != null) {
6401            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6402            // initially
6403            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6404
6405            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6406            // flag set initially
6407            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6408                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6409            }
6410        }
6411
6412        // Verify certificates against what was last scanned
6413        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6414
6415        /*
6416         * A new system app appeared, but we already had a non-system one of the
6417         * same name installed earlier.
6418         */
6419        boolean shouldHideSystemApp = false;
6420        if (updatedPkg == null && ps != null
6421                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6422            /*
6423             * Check to make sure the signatures match first. If they don't,
6424             * wipe the installed application and its data.
6425             */
6426            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6427                    != PackageManager.SIGNATURE_MATCH) {
6428                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6429                        + " signatures don't match existing userdata copy; removing");
6430                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6431                ps = null;
6432            } else {
6433                /*
6434                 * If the newly-added system app is an older version than the
6435                 * already installed version, hide it. It will be scanned later
6436                 * and re-added like an update.
6437                 */
6438                if (pkg.mVersionCode <= ps.versionCode) {
6439                    shouldHideSystemApp = true;
6440                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6441                            + " but new version " + pkg.mVersionCode + " better than installed "
6442                            + ps.versionCode + "; hiding system");
6443                } else {
6444                    /*
6445                     * The newly found system app is a newer version that the
6446                     * one previously installed. Simply remove the
6447                     * already-installed application and replace it with our own
6448                     * while keeping the application data.
6449                     */
6450                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6451                            + " reverting from " + ps.codePathString + ": new version "
6452                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6453                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6454                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6455                    synchronized (mInstallLock) {
6456                        args.cleanUpResourcesLI();
6457                    }
6458                }
6459            }
6460        }
6461
6462        // The apk is forward locked (not public) if its code and resources
6463        // are kept in different files. (except for app in either system or
6464        // vendor path).
6465        // TODO grab this value from PackageSettings
6466        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6467            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6468                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6469            }
6470        }
6471
6472        // TODO: extend to support forward-locked splits
6473        String resourcePath = null;
6474        String baseResourcePath = null;
6475        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6476            if (ps != null && ps.resourcePathString != null) {
6477                resourcePath = ps.resourcePathString;
6478                baseResourcePath = ps.resourcePathString;
6479            } else {
6480                // Should not happen at all. Just log an error.
6481                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6482            }
6483        } else {
6484            resourcePath = pkg.codePath;
6485            baseResourcePath = pkg.baseCodePath;
6486        }
6487
6488        // Set application objects path explicitly.
6489        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6490        pkg.applicationInfo.setCodePath(pkg.codePath);
6491        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6492        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6493        pkg.applicationInfo.setResourcePath(resourcePath);
6494        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6495        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6496
6497        // Note that we invoke the following method only if we are about to unpack an application
6498        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6499                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6500
6501        /*
6502         * If the system app should be overridden by a previously installed
6503         * data, hide the system app now and let the /data/app scan pick it up
6504         * again.
6505         */
6506        if (shouldHideSystemApp) {
6507            synchronized (mPackages) {
6508                mSettings.disableSystemPackageLPw(pkg.packageName);
6509            }
6510        }
6511
6512        return scannedPkg;
6513    }
6514
6515    private static String fixProcessName(String defProcessName,
6516            String processName, int uid) {
6517        if (processName == null) {
6518            return defProcessName;
6519        }
6520        return processName;
6521    }
6522
6523    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6524            throws PackageManagerException {
6525        if (pkgSetting.signatures.mSignatures != null) {
6526            // Already existing package. Make sure signatures match
6527            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6528                    == PackageManager.SIGNATURE_MATCH;
6529            if (!match) {
6530                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6531                        == PackageManager.SIGNATURE_MATCH;
6532            }
6533            if (!match) {
6534                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6535                        == PackageManager.SIGNATURE_MATCH;
6536            }
6537            if (!match) {
6538                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6539                        + pkg.packageName + " signatures do not match the "
6540                        + "previously installed version; ignoring!");
6541            }
6542        }
6543
6544        // Check for shared user signatures
6545        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6546            // Already existing package. Make sure signatures match
6547            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6548                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6549            if (!match) {
6550                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6551                        == PackageManager.SIGNATURE_MATCH;
6552            }
6553            if (!match) {
6554                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6555                        == PackageManager.SIGNATURE_MATCH;
6556            }
6557            if (!match) {
6558                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6559                        "Package " + pkg.packageName
6560                        + " has no signatures that match those in shared user "
6561                        + pkgSetting.sharedUser.name + "; ignoring!");
6562            }
6563        }
6564    }
6565
6566    /**
6567     * Enforces that only the system UID or root's UID can call a method exposed
6568     * via Binder.
6569     *
6570     * @param message used as message if SecurityException is thrown
6571     * @throws SecurityException if the caller is not system or root
6572     */
6573    private static final void enforceSystemOrRoot(String message) {
6574        final int uid = Binder.getCallingUid();
6575        if (uid != Process.SYSTEM_UID && uid != 0) {
6576            throw new SecurityException(message);
6577        }
6578    }
6579
6580    @Override
6581    public void performFstrimIfNeeded() {
6582        enforceSystemOrRoot("Only the system can request fstrim");
6583
6584        // Before everything else, see whether we need to fstrim.
6585        try {
6586            IMountService ms = PackageHelper.getMountService();
6587            if (ms != null) {
6588                final boolean isUpgrade = isUpgrade();
6589                boolean doTrim = isUpgrade;
6590                if (doTrim) {
6591                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6592                } else {
6593                    final long interval = android.provider.Settings.Global.getLong(
6594                            mContext.getContentResolver(),
6595                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6596                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6597                    if (interval > 0) {
6598                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6599                        if (timeSinceLast > interval) {
6600                            doTrim = true;
6601                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6602                                    + "; running immediately");
6603                        }
6604                    }
6605                }
6606                if (doTrim) {
6607                    if (!isFirstBoot()) {
6608                        try {
6609                            ActivityManagerNative.getDefault().showBootMessage(
6610                                    mContext.getResources().getString(
6611                                            R.string.android_upgrading_fstrim), true);
6612                        } catch (RemoteException e) {
6613                        }
6614                    }
6615                    ms.runMaintenance();
6616                }
6617            } else {
6618                Slog.e(TAG, "Mount service unavailable!");
6619            }
6620        } catch (RemoteException e) {
6621            // Can't happen; MountService is local
6622        }
6623    }
6624
6625    @Override
6626    public void extractPackagesIfNeeded() {
6627        enforceSystemOrRoot("Only the system can request package extraction");
6628
6629        // Extract pacakges only if profile-guided compilation is enabled because
6630        // otherwise BackgroundDexOptService will not dexopt them later.
6631        if (mUseJitProfiles) {
6632            ArraySet<String> pkgs = getOptimizablePackages();
6633            if (pkgs != null) {
6634                for (String pkg : pkgs) {
6635                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6636                            true /* extractOnly */);
6637                }
6638            }
6639        }
6640    }
6641
6642    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6643        List<ResolveInfo> ris = null;
6644        try {
6645            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6646                    intent, null, 0, userId);
6647        } catch (RemoteException e) {
6648        }
6649        ArraySet<String> pkgNames = new ArraySet<String>();
6650        if (ris != null) {
6651            for (ResolveInfo ri : ris) {
6652                pkgNames.add(ri.activityInfo.packageName);
6653            }
6654        }
6655        return pkgNames;
6656    }
6657
6658    @Override
6659    public void notifyPackageUse(String packageName) {
6660        synchronized (mPackages) {
6661            PackageParser.Package p = mPackages.get(packageName);
6662            if (p == null) {
6663                return;
6664            }
6665            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6666        }
6667    }
6668
6669    // TODO: this is not used nor needed. Delete it.
6670    @Override
6671    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6672        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6673                false /* extractOnly */);
6674    }
6675
6676    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6677            boolean extractOnly) {
6678        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly);
6679    }
6680
6681    private boolean performDexOptTraced(String packageName, String instructionSet,
6682                boolean useProfiles, boolean extractOnly) {
6683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6684        try {
6685            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689    }
6690
6691    private boolean performDexOptInternal(String packageName, String instructionSet,
6692                boolean useProfiles, boolean extractOnly) {
6693        PackageParser.Package p;
6694        final String targetInstructionSet;
6695        synchronized (mPackages) {
6696            p = mPackages.get(packageName);
6697            if (p == null) {
6698                return false;
6699            }
6700            mPackageUsage.write(false);
6701
6702            targetInstructionSet = instructionSet != null ? instructionSet :
6703                    getPrimaryInstructionSet(p.applicationInfo);
6704            if (!useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6705                // Skip only if we do not use profiles since they might trigger a recompilation.
6706                return false;
6707            }
6708        }
6709        long callingId = Binder.clearCallingIdentity();
6710        try {
6711            synchronized (mInstallLock) {
6712                final String[] instructionSets = new String[] { targetInstructionSet };
6713                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6714                        true /* inclDependencies */, useProfiles, extractOnly);
6715                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6716            }
6717        } finally {
6718            Binder.restoreCallingIdentity(callingId);
6719        }
6720    }
6721
6722    public ArraySet<String> getOptimizablePackages() {
6723        ArraySet<String> pkgs = new ArraySet<String>();
6724        synchronized (mPackages) {
6725            for (PackageParser.Package p : mPackages.values()) {
6726                if (PackageDexOptimizer.canOptimizePackage(p)) {
6727                    pkgs.add(p.packageName);
6728                }
6729            }
6730        }
6731        return pkgs;
6732    }
6733
6734    public void shutdown() {
6735        mPackageUsage.write(true);
6736    }
6737
6738    @Override
6739    public void forceDexOpt(String packageName) {
6740        enforceSystemOrRoot("forceDexOpt");
6741
6742        PackageParser.Package pkg;
6743        synchronized (mPackages) {
6744            pkg = mPackages.get(packageName);
6745            if (pkg == null) {
6746                throw new IllegalArgumentException("Unknown package: " + packageName);
6747            }
6748        }
6749
6750        synchronized (mInstallLock) {
6751            final String[] instructionSets = new String[] {
6752                    getPrimaryInstructionSet(pkg.applicationInfo) };
6753
6754            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6755
6756            // Whoever is calling forceDexOpt wants a fully compiled package.
6757            // Don't use profiles since that may cause compilation to be skipped.
6758            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6759                    true /* inclDependencies */, false /* useProfiles */,
6760                    false /* extractOnly */);
6761
6762            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6763            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6764                throw new IllegalStateException("Failed to dexopt: " + res);
6765            }
6766        }
6767    }
6768
6769    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6770        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6771            Slog.w(TAG, "Unable to update from " + oldPkg.name
6772                    + " to " + newPkg.packageName
6773                    + ": old package not in system partition");
6774            return false;
6775        } else if (mPackages.get(oldPkg.name) != null) {
6776            Slog.w(TAG, "Unable to update from " + oldPkg.name
6777                    + " to " + newPkg.packageName
6778                    + ": old package still exists");
6779            return false;
6780        }
6781        return true;
6782    }
6783
6784    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6785        // TODO: triage flags as part of 26466827
6786        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6787
6788        boolean res = true;
6789        final int[] users = sUserManager.getUserIds();
6790        for (int user : users) {
6791            try {
6792                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6793            } catch (InstallerException e) {
6794                Slog.w(TAG, "Failed to delete data directory", e);
6795                res = false;
6796            }
6797        }
6798        return res;
6799    }
6800
6801    void removeCodePathLI(File codePath) {
6802        if (codePath.isDirectory()) {
6803            try {
6804                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6805            } catch (InstallerException e) {
6806                Slog.w(TAG, "Failed to remove code path", e);
6807            }
6808        } else {
6809            codePath.delete();
6810        }
6811    }
6812
6813    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6814        try {
6815            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6816        } catch (InstallerException e) {
6817            Slog.w(TAG, "Failed to destroy app data", e);
6818        }
6819    }
6820
6821    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6822            int appId, String seinfo) {
6823        try {
6824            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6825        } catch (InstallerException e) {
6826            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6827        }
6828    }
6829
6830    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6831        // TODO: triage flags as part of 26466827
6832        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6833
6834        final int[] users = sUserManager.getUserIds();
6835        for (int user : users) {
6836            try {
6837                mInstaller.clearAppData(volumeUuid, packageName, user,
6838                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6839            } catch (InstallerException e) {
6840                Slog.w(TAG, "Failed to delete code cache directory", e);
6841            }
6842        }
6843    }
6844
6845    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6846            PackageParser.Package changingLib) {
6847        if (file.path != null) {
6848            usesLibraryFiles.add(file.path);
6849            return;
6850        }
6851        PackageParser.Package p = mPackages.get(file.apk);
6852        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6853            // If we are doing this while in the middle of updating a library apk,
6854            // then we need to make sure to use that new apk for determining the
6855            // dependencies here.  (We haven't yet finished committing the new apk
6856            // to the package manager state.)
6857            if (p == null || p.packageName.equals(changingLib.packageName)) {
6858                p = changingLib;
6859            }
6860        }
6861        if (p != null) {
6862            usesLibraryFiles.addAll(p.getAllCodePaths());
6863        }
6864    }
6865
6866    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6867            PackageParser.Package changingLib) throws PackageManagerException {
6868        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6869            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6870            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6871            for (int i=0; i<N; i++) {
6872                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6873                if (file == null) {
6874                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6875                            "Package " + pkg.packageName + " requires unavailable shared library "
6876                            + pkg.usesLibraries.get(i) + "; failing!");
6877                }
6878                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6879            }
6880            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6881            for (int i=0; i<N; i++) {
6882                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6883                if (file == null) {
6884                    Slog.w(TAG, "Package " + pkg.packageName
6885                            + " desires unavailable shared library "
6886                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6887                } else {
6888                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6889                }
6890            }
6891            N = usesLibraryFiles.size();
6892            if (N > 0) {
6893                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6894            } else {
6895                pkg.usesLibraryFiles = null;
6896            }
6897        }
6898    }
6899
6900    private static boolean hasString(List<String> list, List<String> which) {
6901        if (list == null) {
6902            return false;
6903        }
6904        for (int i=list.size()-1; i>=0; i--) {
6905            for (int j=which.size()-1; j>=0; j--) {
6906                if (which.get(j).equals(list.get(i))) {
6907                    return true;
6908                }
6909            }
6910        }
6911        return false;
6912    }
6913
6914    private void updateAllSharedLibrariesLPw() {
6915        for (PackageParser.Package pkg : mPackages.values()) {
6916            try {
6917                updateSharedLibrariesLPw(pkg, null);
6918            } catch (PackageManagerException e) {
6919                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6920            }
6921        }
6922    }
6923
6924    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6925            PackageParser.Package changingPkg) {
6926        ArrayList<PackageParser.Package> res = null;
6927        for (PackageParser.Package pkg : mPackages.values()) {
6928            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6929                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6930                if (res == null) {
6931                    res = new ArrayList<PackageParser.Package>();
6932                }
6933                res.add(pkg);
6934                try {
6935                    updateSharedLibrariesLPw(pkg, changingPkg);
6936                } catch (PackageManagerException e) {
6937                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6938                }
6939            }
6940        }
6941        return res;
6942    }
6943
6944    /**
6945     * Derive the value of the {@code cpuAbiOverride} based on the provided
6946     * value and an optional stored value from the package settings.
6947     */
6948    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6949        String cpuAbiOverride = null;
6950
6951        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6952            cpuAbiOverride = null;
6953        } else if (abiOverride != null) {
6954            cpuAbiOverride = abiOverride;
6955        } else if (settings != null) {
6956            cpuAbiOverride = settings.cpuAbiOverrideString;
6957        }
6958
6959        return cpuAbiOverride;
6960    }
6961
6962    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6963            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6964        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6965        try {
6966            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6967        } finally {
6968            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6969        }
6970    }
6971
6972    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6973            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6974        boolean success = false;
6975        try {
6976            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6977                    currentTime, user);
6978            success = true;
6979            return res;
6980        } finally {
6981            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6982                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6983            }
6984        }
6985    }
6986
6987    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6988            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6989        final File scanFile = new File(pkg.codePath);
6990        if (pkg.applicationInfo.getCodePath() == null ||
6991                pkg.applicationInfo.getResourcePath() == null) {
6992            // Bail out. The resource and code paths haven't been set.
6993            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6994                    "Code and resource paths haven't been set correctly");
6995        }
6996
6997        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6998            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6999        } else {
7000            // Only allow system apps to be flagged as core apps.
7001            pkg.coreApp = false;
7002        }
7003
7004        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7005            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7006        }
7007
7008        if (mCustomResolverComponentName != null &&
7009                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7010            setUpCustomResolverActivity(pkg);
7011        }
7012
7013        if (pkg.packageName.equals("android")) {
7014            synchronized (mPackages) {
7015                if (mAndroidApplication != null) {
7016                    Slog.w(TAG, "*************************************************");
7017                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7018                    Slog.w(TAG, " file=" + scanFile);
7019                    Slog.w(TAG, "*************************************************");
7020                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7021                            "Core android package being redefined.  Skipping.");
7022                }
7023
7024                // Set up information for our fall-back user intent resolution activity.
7025                mPlatformPackage = pkg;
7026                pkg.mVersionCode = mSdkVersion;
7027                mAndroidApplication = pkg.applicationInfo;
7028
7029                if (!mResolverReplaced) {
7030                    mResolveActivity.applicationInfo = mAndroidApplication;
7031                    mResolveActivity.name = ResolverActivity.class.getName();
7032                    mResolveActivity.packageName = mAndroidApplication.packageName;
7033                    mResolveActivity.processName = "system:ui";
7034                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7035                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7036                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7037                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7038                    mResolveActivity.exported = true;
7039                    mResolveActivity.enabled = true;
7040                    mResolveInfo.activityInfo = mResolveActivity;
7041                    mResolveInfo.priority = 0;
7042                    mResolveInfo.preferredOrder = 0;
7043                    mResolveInfo.match = 0;
7044                    mResolveComponentName = new ComponentName(
7045                            mAndroidApplication.packageName, mResolveActivity.name);
7046                }
7047            }
7048        }
7049
7050        if (DEBUG_PACKAGE_SCANNING) {
7051            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7052                Log.d(TAG, "Scanning package " + pkg.packageName);
7053        }
7054
7055        if (mPackages.containsKey(pkg.packageName)
7056                || mSharedLibraries.containsKey(pkg.packageName)) {
7057            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7058                    "Application package " + pkg.packageName
7059                    + " already installed.  Skipping duplicate.");
7060        }
7061
7062        // If we're only installing presumed-existing packages, require that the
7063        // scanned APK is both already known and at the path previously established
7064        // for it.  Previously unknown packages we pick up normally, but if we have an
7065        // a priori expectation about this package's install presence, enforce it.
7066        // With a singular exception for new system packages. When an OTA contains
7067        // a new system package, we allow the codepath to change from a system location
7068        // to the user-installed location. If we don't allow this change, any newer,
7069        // user-installed version of the application will be ignored.
7070        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7071            if (mExpectingBetter.containsKey(pkg.packageName)) {
7072                logCriticalInfo(Log.WARN,
7073                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7074            } else {
7075                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7076                if (known != null) {
7077                    if (DEBUG_PACKAGE_SCANNING) {
7078                        Log.d(TAG, "Examining " + pkg.codePath
7079                                + " and requiring known paths " + known.codePathString
7080                                + " & " + known.resourcePathString);
7081                    }
7082                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7083                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7084                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7085                                "Application package " + pkg.packageName
7086                                + " found at " + pkg.applicationInfo.getCodePath()
7087                                + " but expected at " + known.codePathString + "; ignoring.");
7088                    }
7089                }
7090            }
7091        }
7092
7093        // Initialize package source and resource directories
7094        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7095        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7096
7097        SharedUserSetting suid = null;
7098        PackageSetting pkgSetting = null;
7099
7100        if (!isSystemApp(pkg)) {
7101            // Only system apps can use these features.
7102            pkg.mOriginalPackages = null;
7103            pkg.mRealPackage = null;
7104            pkg.mAdoptPermissions = null;
7105        }
7106
7107        // writer
7108        synchronized (mPackages) {
7109            if (pkg.mSharedUserId != null) {
7110                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7111                if (suid == null) {
7112                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7113                            "Creating application package " + pkg.packageName
7114                            + " for shared user failed");
7115                }
7116                if (DEBUG_PACKAGE_SCANNING) {
7117                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7118                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7119                                + "): packages=" + suid.packages);
7120                }
7121            }
7122
7123            // Check if we are renaming from an original package name.
7124            PackageSetting origPackage = null;
7125            String realName = null;
7126            if (pkg.mOriginalPackages != null) {
7127                // This package may need to be renamed to a previously
7128                // installed name.  Let's check on that...
7129                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7130                if (pkg.mOriginalPackages.contains(renamed)) {
7131                    // This package had originally been installed as the
7132                    // original name, and we have already taken care of
7133                    // transitioning to the new one.  Just update the new
7134                    // one to continue using the old name.
7135                    realName = pkg.mRealPackage;
7136                    if (!pkg.packageName.equals(renamed)) {
7137                        // Callers into this function may have already taken
7138                        // care of renaming the package; only do it here if
7139                        // it is not already done.
7140                        pkg.setPackageName(renamed);
7141                    }
7142
7143                } else {
7144                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7145                        if ((origPackage = mSettings.peekPackageLPr(
7146                                pkg.mOriginalPackages.get(i))) != null) {
7147                            // We do have the package already installed under its
7148                            // original name...  should we use it?
7149                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7150                                // New package is not compatible with original.
7151                                origPackage = null;
7152                                continue;
7153                            } else if (origPackage.sharedUser != null) {
7154                                // Make sure uid is compatible between packages.
7155                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7156                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7157                                            + " to " + pkg.packageName + ": old uid "
7158                                            + origPackage.sharedUser.name
7159                                            + " differs from " + pkg.mSharedUserId);
7160                                    origPackage = null;
7161                                    continue;
7162                                }
7163                            } else {
7164                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7165                                        + pkg.packageName + " to old name " + origPackage.name);
7166                            }
7167                            break;
7168                        }
7169                    }
7170                }
7171            }
7172
7173            if (mTransferedPackages.contains(pkg.packageName)) {
7174                Slog.w(TAG, "Package " + pkg.packageName
7175                        + " was transferred to another, but its .apk remains");
7176            }
7177
7178            // Just create the setting, don't add it yet. For already existing packages
7179            // the PkgSetting exists already and doesn't have to be created.
7180            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7181                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7182                    pkg.applicationInfo.primaryCpuAbi,
7183                    pkg.applicationInfo.secondaryCpuAbi,
7184                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7185                    user, false);
7186            if (pkgSetting == null) {
7187                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7188                        "Creating application package " + pkg.packageName + " failed");
7189            }
7190
7191            if (pkgSetting.origPackage != null) {
7192                // If we are first transitioning from an original package,
7193                // fix up the new package's name now.  We need to do this after
7194                // looking up the package under its new name, so getPackageLP
7195                // can take care of fiddling things correctly.
7196                pkg.setPackageName(origPackage.name);
7197
7198                // File a report about this.
7199                String msg = "New package " + pkgSetting.realName
7200                        + " renamed to replace old package " + pkgSetting.name;
7201                reportSettingsProblem(Log.WARN, msg);
7202
7203                // Make a note of it.
7204                mTransferedPackages.add(origPackage.name);
7205
7206                // No longer need to retain this.
7207                pkgSetting.origPackage = null;
7208            }
7209
7210            if (realName != null) {
7211                // Make a note of it.
7212                mTransferedPackages.add(pkg.packageName);
7213            }
7214
7215            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7216                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7217            }
7218
7219            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7220                // Check all shared libraries and map to their actual file path.
7221                // We only do this here for apps not on a system dir, because those
7222                // are the only ones that can fail an install due to this.  We
7223                // will take care of the system apps by updating all of their
7224                // library paths after the scan is done.
7225                updateSharedLibrariesLPw(pkg, null);
7226            }
7227
7228            if (mFoundPolicyFile) {
7229                SELinuxMMAC.assignSeinfoValue(pkg);
7230            }
7231
7232            pkg.applicationInfo.uid = pkgSetting.appId;
7233            pkg.mExtras = pkgSetting;
7234            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7235                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7236                    // We just determined the app is signed correctly, so bring
7237                    // over the latest parsed certs.
7238                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7239                } else {
7240                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7241                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7242                                "Package " + pkg.packageName + " upgrade keys do not match the "
7243                                + "previously installed version");
7244                    } else {
7245                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7246                        String msg = "System package " + pkg.packageName
7247                            + " signature changed; retaining data.";
7248                        reportSettingsProblem(Log.WARN, msg);
7249                    }
7250                }
7251            } else {
7252                try {
7253                    verifySignaturesLP(pkgSetting, pkg);
7254                    // We just determined the app is signed correctly, so bring
7255                    // over the latest parsed certs.
7256                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7257                } catch (PackageManagerException e) {
7258                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7259                        throw e;
7260                    }
7261                    // The signature has changed, but this package is in the system
7262                    // image...  let's recover!
7263                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7264                    // However...  if this package is part of a shared user, but it
7265                    // doesn't match the signature of the shared user, let's fail.
7266                    // What this means is that you can't change the signatures
7267                    // associated with an overall shared user, which doesn't seem all
7268                    // that unreasonable.
7269                    if (pkgSetting.sharedUser != null) {
7270                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7271                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7272                            throw new PackageManagerException(
7273                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7274                                            "Signature mismatch for shared user: "
7275                                            + pkgSetting.sharedUser);
7276                        }
7277                    }
7278                    // File a report about this.
7279                    String msg = "System package " + pkg.packageName
7280                        + " signature changed; retaining data.";
7281                    reportSettingsProblem(Log.WARN, msg);
7282                }
7283            }
7284            // Verify that this new package doesn't have any content providers
7285            // that conflict with existing packages.  Only do this if the
7286            // package isn't already installed, since we don't want to break
7287            // things that are installed.
7288            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7289                final int N = pkg.providers.size();
7290                int i;
7291                for (i=0; i<N; i++) {
7292                    PackageParser.Provider p = pkg.providers.get(i);
7293                    if (p.info.authority != null) {
7294                        String names[] = p.info.authority.split(";");
7295                        for (int j = 0; j < names.length; j++) {
7296                            if (mProvidersByAuthority.containsKey(names[j])) {
7297                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7298                                final String otherPackageName =
7299                                        ((other != null && other.getComponentName() != null) ?
7300                                                other.getComponentName().getPackageName() : "?");
7301                                throw new PackageManagerException(
7302                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7303                                                "Can't install because provider name " + names[j]
7304                                                + " (in package " + pkg.applicationInfo.packageName
7305                                                + ") is already used by " + otherPackageName);
7306                            }
7307                        }
7308                    }
7309                }
7310            }
7311
7312            if (pkg.mAdoptPermissions != null) {
7313                // This package wants to adopt ownership of permissions from
7314                // another package.
7315                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7316                    final String origName = pkg.mAdoptPermissions.get(i);
7317                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7318                    if (orig != null) {
7319                        if (verifyPackageUpdateLPr(orig, pkg)) {
7320                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7321                                    + pkg.packageName);
7322                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7323                        }
7324                    }
7325                }
7326            }
7327        }
7328
7329        final String pkgName = pkg.packageName;
7330
7331        final long scanFileTime = scanFile.lastModified();
7332        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7333        pkg.applicationInfo.processName = fixProcessName(
7334                pkg.applicationInfo.packageName,
7335                pkg.applicationInfo.processName,
7336                pkg.applicationInfo.uid);
7337
7338        if (pkg != mPlatformPackage) {
7339            // Get all of our default paths setup
7340            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7341        }
7342
7343        final String path = scanFile.getPath();
7344        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7345
7346        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7347            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7348
7349            // Some system apps still use directory structure for native libraries
7350            // in which case we might end up not detecting abi solely based on apk
7351            // structure. Try to detect abi based on directory structure.
7352            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7353                    pkg.applicationInfo.primaryCpuAbi == null) {
7354                setBundledAppAbisAndRoots(pkg, pkgSetting);
7355                setNativeLibraryPaths(pkg);
7356            }
7357
7358        } else {
7359            if ((scanFlags & SCAN_MOVE) != 0) {
7360                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7361                // but we already have this packages package info in the PackageSetting. We just
7362                // use that and derive the native library path based on the new codepath.
7363                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7364                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7365            }
7366
7367            // Set native library paths again. For moves, the path will be updated based on the
7368            // ABIs we've determined above. For non-moves, the path will be updated based on the
7369            // ABIs we determined during compilation, but the path will depend on the final
7370            // package path (after the rename away from the stage path).
7371            setNativeLibraryPaths(pkg);
7372        }
7373
7374        // This is a special case for the "system" package, where the ABI is
7375        // dictated by the zygote configuration (and init.rc). We should keep track
7376        // of this ABI so that we can deal with "normal" applications that run under
7377        // the same UID correctly.
7378        if (mPlatformPackage == pkg) {
7379            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7380                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7381        }
7382
7383        // If there's a mismatch between the abi-override in the package setting
7384        // and the abiOverride specified for the install. Warn about this because we
7385        // would've already compiled the app without taking the package setting into
7386        // account.
7387        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7388            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7389                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7390                        " for package " + pkg.packageName);
7391            }
7392        }
7393
7394        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7395        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7396        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7397
7398        // Copy the derived override back to the parsed package, so that we can
7399        // update the package settings accordingly.
7400        pkg.cpuAbiOverride = cpuAbiOverride;
7401
7402        if (DEBUG_ABI_SELECTION) {
7403            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7404                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7405                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7406        }
7407
7408        // Push the derived path down into PackageSettings so we know what to
7409        // clean up at uninstall time.
7410        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7411
7412        if (DEBUG_ABI_SELECTION) {
7413            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7414                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7415                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7416        }
7417
7418        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7419            // We don't do this here during boot because we can do it all
7420            // at once after scanning all existing packages.
7421            //
7422            // We also do this *before* we perform dexopt on this package, so that
7423            // we can avoid redundant dexopts, and also to make sure we've got the
7424            // code and package path correct.
7425            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7426                    pkg, true /* boot complete */);
7427        }
7428
7429        if (mFactoryTest && pkg.requestedPermissions.contains(
7430                android.Manifest.permission.FACTORY_TEST)) {
7431            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7432        }
7433
7434        ArrayList<PackageParser.Package> clientLibPkgs = null;
7435
7436        // writer
7437        synchronized (mPackages) {
7438            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7439                // Only system apps can add new shared libraries.
7440                if (pkg.libraryNames != null) {
7441                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7442                        String name = pkg.libraryNames.get(i);
7443                        boolean allowed = false;
7444                        if (pkg.isUpdatedSystemApp()) {
7445                            // New library entries can only be added through the
7446                            // system image.  This is important to get rid of a lot
7447                            // of nasty edge cases: for example if we allowed a non-
7448                            // system update of the app to add a library, then uninstalling
7449                            // the update would make the library go away, and assumptions
7450                            // we made such as through app install filtering would now
7451                            // have allowed apps on the device which aren't compatible
7452                            // with it.  Better to just have the restriction here, be
7453                            // conservative, and create many fewer cases that can negatively
7454                            // impact the user experience.
7455                            final PackageSetting sysPs = mSettings
7456                                    .getDisabledSystemPkgLPr(pkg.packageName);
7457                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7458                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7459                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7460                                        allowed = true;
7461                                        break;
7462                                    }
7463                                }
7464                            }
7465                        } else {
7466                            allowed = true;
7467                        }
7468                        if (allowed) {
7469                            if (!mSharedLibraries.containsKey(name)) {
7470                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7471                            } else if (!name.equals(pkg.packageName)) {
7472                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7473                                        + name + " already exists; skipping");
7474                            }
7475                        } else {
7476                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7477                                    + name + " that is not declared on system image; skipping");
7478                        }
7479                    }
7480                    if ((scanFlags & SCAN_BOOTING) == 0) {
7481                        // If we are not booting, we need to update any applications
7482                        // that are clients of our shared library.  If we are booting,
7483                        // this will all be done once the scan is complete.
7484                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7485                    }
7486                }
7487            }
7488        }
7489
7490        // Request the ActivityManager to kill the process(only for existing packages)
7491        // so that we do not end up in a confused state while the user is still using the older
7492        // version of the application while the new one gets installed.
7493        if ((scanFlags & SCAN_REPLACING) != 0) {
7494            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7495
7496            killApplication(pkg.applicationInfo.packageName,
7497                        pkg.applicationInfo.uid, "replace pkg");
7498
7499            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7500        }
7501
7502        // Also need to kill any apps that are dependent on the library.
7503        if (clientLibPkgs != null) {
7504            for (int i=0; i<clientLibPkgs.size(); i++) {
7505                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7506                killApplication(clientPkg.applicationInfo.packageName,
7507                        clientPkg.applicationInfo.uid, "update lib");
7508            }
7509        }
7510
7511        // Make sure we're not adding any bogus keyset info
7512        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7513        ksms.assertScannedPackageValid(pkg);
7514
7515        // writer
7516        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7517
7518        boolean createIdmapFailed = false;
7519        synchronized (mPackages) {
7520            // We don't expect installation to fail beyond this point
7521
7522            // Add the new setting to mSettings
7523            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7524            // Add the new setting to mPackages
7525            mPackages.put(pkg.applicationInfo.packageName, pkg);
7526            // Make sure we don't accidentally delete its data.
7527            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7528            while (iter.hasNext()) {
7529                PackageCleanItem item = iter.next();
7530                if (pkgName.equals(item.packageName)) {
7531                    iter.remove();
7532                }
7533            }
7534
7535            // Take care of first install / last update times.
7536            if (currentTime != 0) {
7537                if (pkgSetting.firstInstallTime == 0) {
7538                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7539                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7540                    pkgSetting.lastUpdateTime = currentTime;
7541                }
7542            } else if (pkgSetting.firstInstallTime == 0) {
7543                // We need *something*.  Take time time stamp of the file.
7544                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7545            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7546                if (scanFileTime != pkgSetting.timeStamp) {
7547                    // A package on the system image has changed; consider this
7548                    // to be an update.
7549                    pkgSetting.lastUpdateTime = scanFileTime;
7550                }
7551            }
7552
7553            // Add the package's KeySets to the global KeySetManagerService
7554            ksms.addScannedPackageLPw(pkg);
7555
7556            int N = pkg.providers.size();
7557            StringBuilder r = null;
7558            int i;
7559            for (i=0; i<N; i++) {
7560                PackageParser.Provider p = pkg.providers.get(i);
7561                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7562                        p.info.processName, pkg.applicationInfo.uid);
7563                mProviders.addProvider(p);
7564                p.syncable = p.info.isSyncable;
7565                if (p.info.authority != null) {
7566                    String names[] = p.info.authority.split(";");
7567                    p.info.authority = null;
7568                    for (int j = 0; j < names.length; j++) {
7569                        if (j == 1 && p.syncable) {
7570                            // We only want the first authority for a provider to possibly be
7571                            // syncable, so if we already added this provider using a different
7572                            // authority clear the syncable flag. We copy the provider before
7573                            // changing it because the mProviders object contains a reference
7574                            // to a provider that we don't want to change.
7575                            // Only do this for the second authority since the resulting provider
7576                            // object can be the same for all future authorities for this provider.
7577                            p = new PackageParser.Provider(p);
7578                            p.syncable = false;
7579                        }
7580                        if (!mProvidersByAuthority.containsKey(names[j])) {
7581                            mProvidersByAuthority.put(names[j], p);
7582                            if (p.info.authority == null) {
7583                                p.info.authority = names[j];
7584                            } else {
7585                                p.info.authority = p.info.authority + ";" + names[j];
7586                            }
7587                            if (DEBUG_PACKAGE_SCANNING) {
7588                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7589                                    Log.d(TAG, "Registered content provider: " + names[j]
7590                                            + ", className = " + p.info.name + ", isSyncable = "
7591                                            + p.info.isSyncable);
7592                            }
7593                        } else {
7594                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7595                            Slog.w(TAG, "Skipping provider name " + names[j] +
7596                                    " (in package " + pkg.applicationInfo.packageName +
7597                                    "): name already used by "
7598                                    + ((other != null && other.getComponentName() != null)
7599                                            ? other.getComponentName().getPackageName() : "?"));
7600                        }
7601                    }
7602                }
7603                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7604                    if (r == null) {
7605                        r = new StringBuilder(256);
7606                    } else {
7607                        r.append(' ');
7608                    }
7609                    r.append(p.info.name);
7610                }
7611            }
7612            if (r != null) {
7613                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7614            }
7615
7616            N = pkg.services.size();
7617            r = null;
7618            for (i=0; i<N; i++) {
7619                PackageParser.Service s = pkg.services.get(i);
7620                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7621                        s.info.processName, pkg.applicationInfo.uid);
7622                mServices.addService(s);
7623                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7624                    if (r == null) {
7625                        r = new StringBuilder(256);
7626                    } else {
7627                        r.append(' ');
7628                    }
7629                    r.append(s.info.name);
7630                }
7631            }
7632            if (r != null) {
7633                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7634            }
7635
7636            N = pkg.receivers.size();
7637            r = null;
7638            for (i=0; i<N; i++) {
7639                PackageParser.Activity a = pkg.receivers.get(i);
7640                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7641                        a.info.processName, pkg.applicationInfo.uid);
7642                mReceivers.addActivity(a, "receiver");
7643                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7644                    if (r == null) {
7645                        r = new StringBuilder(256);
7646                    } else {
7647                        r.append(' ');
7648                    }
7649                    r.append(a.info.name);
7650                }
7651            }
7652            if (r != null) {
7653                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7654            }
7655
7656            N = pkg.activities.size();
7657            r = null;
7658            for (i=0; i<N; i++) {
7659                PackageParser.Activity a = pkg.activities.get(i);
7660                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7661                        a.info.processName, pkg.applicationInfo.uid);
7662                mActivities.addActivity(a, "activity");
7663                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7664                    if (r == null) {
7665                        r = new StringBuilder(256);
7666                    } else {
7667                        r.append(' ');
7668                    }
7669                    r.append(a.info.name);
7670                }
7671            }
7672            if (r != null) {
7673                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7674            }
7675
7676            N = pkg.permissionGroups.size();
7677            r = null;
7678            for (i=0; i<N; i++) {
7679                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7680                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7681                if (cur == null) {
7682                    mPermissionGroups.put(pg.info.name, pg);
7683                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7684                        if (r == null) {
7685                            r = new StringBuilder(256);
7686                        } else {
7687                            r.append(' ');
7688                        }
7689                        r.append(pg.info.name);
7690                    }
7691                } else {
7692                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7693                            + pg.info.packageName + " ignored: original from "
7694                            + cur.info.packageName);
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("DUP:");
7702                        r.append(pg.info.name);
7703                    }
7704                }
7705            }
7706            if (r != null) {
7707                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7708            }
7709
7710            N = pkg.permissions.size();
7711            r = null;
7712            for (i=0; i<N; i++) {
7713                PackageParser.Permission p = pkg.permissions.get(i);
7714
7715                // Assume by default that we did not install this permission into the system.
7716                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7717
7718                // Now that permission groups have a special meaning, we ignore permission
7719                // groups for legacy apps to prevent unexpected behavior. In particular,
7720                // permissions for one app being granted to someone just becuase they happen
7721                // to be in a group defined by another app (before this had no implications).
7722                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7723                    p.group = mPermissionGroups.get(p.info.group);
7724                    // Warn for a permission in an unknown group.
7725                    if (p.info.group != null && p.group == null) {
7726                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7727                                + p.info.packageName + " in an unknown group " + p.info.group);
7728                    }
7729                }
7730
7731                ArrayMap<String, BasePermission> permissionMap =
7732                        p.tree ? mSettings.mPermissionTrees
7733                                : mSettings.mPermissions;
7734                BasePermission bp = permissionMap.get(p.info.name);
7735
7736                // Allow system apps to redefine non-system permissions
7737                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7738                    final boolean currentOwnerIsSystem = (bp.perm != null
7739                            && isSystemApp(bp.perm.owner));
7740                    if (isSystemApp(p.owner)) {
7741                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7742                            // It's a built-in permission and no owner, take ownership now
7743                            bp.packageSetting = pkgSetting;
7744                            bp.perm = p;
7745                            bp.uid = pkg.applicationInfo.uid;
7746                            bp.sourcePackage = p.info.packageName;
7747                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7748                        } else if (!currentOwnerIsSystem) {
7749                            String msg = "New decl " + p.owner + " of permission  "
7750                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7751                            reportSettingsProblem(Log.WARN, msg);
7752                            bp = null;
7753                        }
7754                    }
7755                }
7756
7757                if (bp == null) {
7758                    bp = new BasePermission(p.info.name, p.info.packageName,
7759                            BasePermission.TYPE_NORMAL);
7760                    permissionMap.put(p.info.name, bp);
7761                }
7762
7763                if (bp.perm == null) {
7764                    if (bp.sourcePackage == null
7765                            || bp.sourcePackage.equals(p.info.packageName)) {
7766                        BasePermission tree = findPermissionTreeLP(p.info.name);
7767                        if (tree == null
7768                                || tree.sourcePackage.equals(p.info.packageName)) {
7769                            bp.packageSetting = pkgSetting;
7770                            bp.perm = p;
7771                            bp.uid = pkg.applicationInfo.uid;
7772                            bp.sourcePackage = p.info.packageName;
7773                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7774                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7775                                if (r == null) {
7776                                    r = new StringBuilder(256);
7777                                } else {
7778                                    r.append(' ');
7779                                }
7780                                r.append(p.info.name);
7781                            }
7782                        } else {
7783                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7784                                    + p.info.packageName + " ignored: base tree "
7785                                    + tree.name + " is from package "
7786                                    + tree.sourcePackage);
7787                        }
7788                    } else {
7789                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7790                                + p.info.packageName + " ignored: original from "
7791                                + bp.sourcePackage);
7792                    }
7793                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7794                    if (r == null) {
7795                        r = new StringBuilder(256);
7796                    } else {
7797                        r.append(' ');
7798                    }
7799                    r.append("DUP:");
7800                    r.append(p.info.name);
7801                }
7802                if (bp.perm == p) {
7803                    bp.protectionLevel = p.info.protectionLevel;
7804                }
7805            }
7806
7807            if (r != null) {
7808                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7809            }
7810
7811            N = pkg.instrumentation.size();
7812            r = null;
7813            for (i=0; i<N; i++) {
7814                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7815                a.info.packageName = pkg.applicationInfo.packageName;
7816                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7817                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7818                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7819                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7820                a.info.dataDir = pkg.applicationInfo.dataDir;
7821                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7822                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7823
7824                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7825                // need other information about the application, like the ABI and what not ?
7826                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7827                mInstrumentation.put(a.getComponentName(), a);
7828                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7829                    if (r == null) {
7830                        r = new StringBuilder(256);
7831                    } else {
7832                        r.append(' ');
7833                    }
7834                    r.append(a.info.name);
7835                }
7836            }
7837            if (r != null) {
7838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7839            }
7840
7841            if (pkg.protectedBroadcasts != null) {
7842                N = pkg.protectedBroadcasts.size();
7843                for (i=0; i<N; i++) {
7844                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7845                }
7846            }
7847
7848            pkgSetting.setTimeStamp(scanFileTime);
7849
7850            // Create idmap files for pairs of (packages, overlay packages).
7851            // Note: "android", ie framework-res.apk, is handled by native layers.
7852            if (pkg.mOverlayTarget != null) {
7853                // This is an overlay package.
7854                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7855                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7856                        mOverlays.put(pkg.mOverlayTarget,
7857                                new ArrayMap<String, PackageParser.Package>());
7858                    }
7859                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7860                    map.put(pkg.packageName, pkg);
7861                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7862                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7863                        createIdmapFailed = true;
7864                    }
7865                }
7866            } else if (mOverlays.containsKey(pkg.packageName) &&
7867                    !pkg.packageName.equals("android")) {
7868                // This is a regular package, with one or more known overlay packages.
7869                createIdmapsForPackageLI(pkg);
7870            }
7871        }
7872
7873        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7874
7875        if (createIdmapFailed) {
7876            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7877                    "scanPackageLI failed to createIdmap");
7878        }
7879        return pkg;
7880    }
7881
7882    /**
7883     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7884     * is derived purely on the basis of the contents of {@code scanFile} and
7885     * {@code cpuAbiOverride}.
7886     *
7887     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7888     */
7889    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7890                                 String cpuAbiOverride, boolean extractLibs)
7891            throws PackageManagerException {
7892        // TODO: We can probably be smarter about this stuff. For installed apps,
7893        // we can calculate this information at install time once and for all. For
7894        // system apps, we can probably assume that this information doesn't change
7895        // after the first boot scan. As things stand, we do lots of unnecessary work.
7896
7897        // Give ourselves some initial paths; we'll come back for another
7898        // pass once we've determined ABI below.
7899        setNativeLibraryPaths(pkg);
7900
7901        // We would never need to extract libs for forward-locked and external packages,
7902        // since the container service will do it for us. We shouldn't attempt to
7903        // extract libs from system app when it was not updated.
7904        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7905                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7906            extractLibs = false;
7907        }
7908
7909        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7910        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7911
7912        NativeLibraryHelper.Handle handle = null;
7913        try {
7914            handle = NativeLibraryHelper.Handle.create(pkg);
7915            // TODO(multiArch): This can be null for apps that didn't go through the
7916            // usual installation process. We can calculate it again, like we
7917            // do during install time.
7918            //
7919            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7920            // unnecessary.
7921            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7922
7923            // Null out the abis so that they can be recalculated.
7924            pkg.applicationInfo.primaryCpuAbi = null;
7925            pkg.applicationInfo.secondaryCpuAbi = null;
7926            if (isMultiArch(pkg.applicationInfo)) {
7927                // Warn if we've set an abiOverride for multi-lib packages..
7928                // By definition, we need to copy both 32 and 64 bit libraries for
7929                // such packages.
7930                if (pkg.cpuAbiOverride != null
7931                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7932                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7933                }
7934
7935                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7936                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7937                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7938                    if (extractLibs) {
7939                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7940                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7941                                useIsaSpecificSubdirs);
7942                    } else {
7943                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7944                    }
7945                }
7946
7947                maybeThrowExceptionForMultiArchCopy(
7948                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7949
7950                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7951                    if (extractLibs) {
7952                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7953                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7954                                useIsaSpecificSubdirs);
7955                    } else {
7956                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7957                    }
7958                }
7959
7960                maybeThrowExceptionForMultiArchCopy(
7961                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7962
7963                if (abi64 >= 0) {
7964                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7965                }
7966
7967                if (abi32 >= 0) {
7968                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7969                    if (abi64 >= 0) {
7970                        pkg.applicationInfo.secondaryCpuAbi = abi;
7971                    } else {
7972                        pkg.applicationInfo.primaryCpuAbi = abi;
7973                    }
7974                }
7975            } else {
7976                String[] abiList = (cpuAbiOverride != null) ?
7977                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7978
7979                // Enable gross and lame hacks for apps that are built with old
7980                // SDK tools. We must scan their APKs for renderscript bitcode and
7981                // not launch them if it's present. Don't bother checking on devices
7982                // that don't have 64 bit support.
7983                boolean needsRenderScriptOverride = false;
7984                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7985                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7986                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7987                    needsRenderScriptOverride = true;
7988                }
7989
7990                final int copyRet;
7991                if (extractLibs) {
7992                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7993                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7994                } else {
7995                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7996                }
7997
7998                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7999                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8000                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8001                }
8002
8003                if (copyRet >= 0) {
8004                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8005                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8006                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8007                } else if (needsRenderScriptOverride) {
8008                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8009                }
8010            }
8011        } catch (IOException ioe) {
8012            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8013        } finally {
8014            IoUtils.closeQuietly(handle);
8015        }
8016
8017        // Now that we've calculated the ABIs and determined if it's an internal app,
8018        // we will go ahead and populate the nativeLibraryPath.
8019        setNativeLibraryPaths(pkg);
8020    }
8021
8022    /**
8023     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8024     * i.e, so that all packages can be run inside a single process if required.
8025     *
8026     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8027     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8028     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8029     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8030     * updating a package that belongs to a shared user.
8031     *
8032     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8033     * adds unnecessary complexity.
8034     */
8035    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8036            PackageParser.Package scannedPackage, boolean bootComplete) {
8037        String requiredInstructionSet = null;
8038        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8039            requiredInstructionSet = VMRuntime.getInstructionSet(
8040                     scannedPackage.applicationInfo.primaryCpuAbi);
8041        }
8042
8043        PackageSetting requirer = null;
8044        for (PackageSetting ps : packagesForUser) {
8045            // If packagesForUser contains scannedPackage, we skip it. This will happen
8046            // when scannedPackage is an update of an existing package. Without this check,
8047            // we will never be able to change the ABI of any package belonging to a shared
8048            // user, even if it's compatible with other packages.
8049            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8050                if (ps.primaryCpuAbiString == null) {
8051                    continue;
8052                }
8053
8054                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8055                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8056                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8057                    // this but there's not much we can do.
8058                    String errorMessage = "Instruction set mismatch, "
8059                            + ((requirer == null) ? "[caller]" : requirer)
8060                            + " requires " + requiredInstructionSet + " whereas " + ps
8061                            + " requires " + instructionSet;
8062                    Slog.w(TAG, errorMessage);
8063                }
8064
8065                if (requiredInstructionSet == null) {
8066                    requiredInstructionSet = instructionSet;
8067                    requirer = ps;
8068                }
8069            }
8070        }
8071
8072        if (requiredInstructionSet != null) {
8073            String adjustedAbi;
8074            if (requirer != null) {
8075                // requirer != null implies that either scannedPackage was null or that scannedPackage
8076                // did not require an ABI, in which case we have to adjust scannedPackage to match
8077                // the ABI of the set (which is the same as requirer's ABI)
8078                adjustedAbi = requirer.primaryCpuAbiString;
8079                if (scannedPackage != null) {
8080                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8081                }
8082            } else {
8083                // requirer == null implies that we're updating all ABIs in the set to
8084                // match scannedPackage.
8085                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8086            }
8087
8088            for (PackageSetting ps : packagesForUser) {
8089                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8090                    if (ps.primaryCpuAbiString != null) {
8091                        continue;
8092                    }
8093
8094                    ps.primaryCpuAbiString = adjustedAbi;
8095                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8096                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8097                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8098                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8099                                + " (requirer="
8100                                + (requirer == null ? "null" : requirer.pkg.packageName)
8101                                + ", scannedPackage="
8102                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8103                                + ")");
8104                        try {
8105                            mInstaller.rmdex(ps.codePathString,
8106                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8107                        } catch (InstallerException ignored) {
8108                        }
8109                    }
8110                }
8111            }
8112        }
8113    }
8114
8115    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8116        synchronized (mPackages) {
8117            mResolverReplaced = true;
8118            // Set up information for custom user intent resolution activity.
8119            mResolveActivity.applicationInfo = pkg.applicationInfo;
8120            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8121            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8122            mResolveActivity.processName = pkg.applicationInfo.packageName;
8123            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8124            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8125                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8126            mResolveActivity.theme = 0;
8127            mResolveActivity.exported = true;
8128            mResolveActivity.enabled = true;
8129            mResolveInfo.activityInfo = mResolveActivity;
8130            mResolveInfo.priority = 0;
8131            mResolveInfo.preferredOrder = 0;
8132            mResolveInfo.match = 0;
8133            mResolveComponentName = mCustomResolverComponentName;
8134            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8135                    mResolveComponentName);
8136        }
8137    }
8138
8139    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8140        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8141
8142        // Set up information for ephemeral installer activity
8143        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8144        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8145        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8146        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8147        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8148        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8149                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8150        mEphemeralInstallerActivity.theme = 0;
8151        mEphemeralInstallerActivity.exported = true;
8152        mEphemeralInstallerActivity.enabled = true;
8153        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8154        mEphemeralInstallerInfo.priority = 0;
8155        mEphemeralInstallerInfo.preferredOrder = 0;
8156        mEphemeralInstallerInfo.match = 0;
8157
8158        if (DEBUG_EPHEMERAL) {
8159            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8160        }
8161    }
8162
8163    private static String calculateBundledApkRoot(final String codePathString) {
8164        final File codePath = new File(codePathString);
8165        final File codeRoot;
8166        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8167            codeRoot = Environment.getRootDirectory();
8168        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8169            codeRoot = Environment.getOemDirectory();
8170        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8171            codeRoot = Environment.getVendorDirectory();
8172        } else {
8173            // Unrecognized code path; take its top real segment as the apk root:
8174            // e.g. /something/app/blah.apk => /something
8175            try {
8176                File f = codePath.getCanonicalFile();
8177                File parent = f.getParentFile();    // non-null because codePath is a file
8178                File tmp;
8179                while ((tmp = parent.getParentFile()) != null) {
8180                    f = parent;
8181                    parent = tmp;
8182                }
8183                codeRoot = f;
8184                Slog.w(TAG, "Unrecognized code path "
8185                        + codePath + " - using " + codeRoot);
8186            } catch (IOException e) {
8187                // Can't canonicalize the code path -- shenanigans?
8188                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8189                return Environment.getRootDirectory().getPath();
8190            }
8191        }
8192        return codeRoot.getPath();
8193    }
8194
8195    /**
8196     * Derive and set the location of native libraries for the given package,
8197     * which varies depending on where and how the package was installed.
8198     */
8199    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8200        final ApplicationInfo info = pkg.applicationInfo;
8201        final String codePath = pkg.codePath;
8202        final File codeFile = new File(codePath);
8203        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8204        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8205
8206        info.nativeLibraryRootDir = null;
8207        info.nativeLibraryRootRequiresIsa = false;
8208        info.nativeLibraryDir = null;
8209        info.secondaryNativeLibraryDir = null;
8210
8211        if (isApkFile(codeFile)) {
8212            // Monolithic install
8213            if (bundledApp) {
8214                // If "/system/lib64/apkname" exists, assume that is the per-package
8215                // native library directory to use; otherwise use "/system/lib/apkname".
8216                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8217                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8218                        getPrimaryInstructionSet(info));
8219
8220                // This is a bundled system app so choose the path based on the ABI.
8221                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8222                // is just the default path.
8223                final String apkName = deriveCodePathName(codePath);
8224                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8225                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8226                        apkName).getAbsolutePath();
8227
8228                if (info.secondaryCpuAbi != null) {
8229                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8230                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8231                            secondaryLibDir, apkName).getAbsolutePath();
8232                }
8233            } else if (asecApp) {
8234                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8235                        .getAbsolutePath();
8236            } else {
8237                final String apkName = deriveCodePathName(codePath);
8238                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8239                        .getAbsolutePath();
8240            }
8241
8242            info.nativeLibraryRootRequiresIsa = false;
8243            info.nativeLibraryDir = info.nativeLibraryRootDir;
8244        } else {
8245            // Cluster install
8246            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8247            info.nativeLibraryRootRequiresIsa = true;
8248
8249            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8250                    getPrimaryInstructionSet(info)).getAbsolutePath();
8251
8252            if (info.secondaryCpuAbi != null) {
8253                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8254                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8255            }
8256        }
8257    }
8258
8259    /**
8260     * Calculate the abis and roots for a bundled app. These can uniquely
8261     * be determined from the contents of the system partition, i.e whether
8262     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8263     * of this information, and instead assume that the system was built
8264     * sensibly.
8265     */
8266    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8267                                           PackageSetting pkgSetting) {
8268        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8269
8270        // If "/system/lib64/apkname" exists, assume that is the per-package
8271        // native library directory to use; otherwise use "/system/lib/apkname".
8272        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8273        setBundledAppAbi(pkg, apkRoot, apkName);
8274        // pkgSetting might be null during rescan following uninstall of updates
8275        // to a bundled app, so accommodate that possibility.  The settings in
8276        // that case will be established later from the parsed package.
8277        //
8278        // If the settings aren't null, sync them up with what we've just derived.
8279        // note that apkRoot isn't stored in the package settings.
8280        if (pkgSetting != null) {
8281            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8282            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8283        }
8284    }
8285
8286    /**
8287     * Deduces the ABI of a bundled app and sets the relevant fields on the
8288     * parsed pkg object.
8289     *
8290     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8291     *        under which system libraries are installed.
8292     * @param apkName the name of the installed package.
8293     */
8294    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8295        final File codeFile = new File(pkg.codePath);
8296
8297        final boolean has64BitLibs;
8298        final boolean has32BitLibs;
8299        if (isApkFile(codeFile)) {
8300            // Monolithic install
8301            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8302            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8303        } else {
8304            // Cluster install
8305            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8306            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8307                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8308                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8309                has64BitLibs = (new File(rootDir, isa)).exists();
8310            } else {
8311                has64BitLibs = false;
8312            }
8313            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8314                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8315                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8316                has32BitLibs = (new File(rootDir, isa)).exists();
8317            } else {
8318                has32BitLibs = false;
8319            }
8320        }
8321
8322        if (has64BitLibs && !has32BitLibs) {
8323            // The package has 64 bit libs, but not 32 bit libs. Its primary
8324            // ABI should be 64 bit. We can safely assume here that the bundled
8325            // native libraries correspond to the most preferred ABI in the list.
8326
8327            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8328            pkg.applicationInfo.secondaryCpuAbi = null;
8329        } else if (has32BitLibs && !has64BitLibs) {
8330            // The package has 32 bit libs but not 64 bit libs. Its primary
8331            // ABI should be 32 bit.
8332
8333            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8334            pkg.applicationInfo.secondaryCpuAbi = null;
8335        } else if (has32BitLibs && has64BitLibs) {
8336            // The application has both 64 and 32 bit bundled libraries. We check
8337            // here that the app declares multiArch support, and warn if it doesn't.
8338            //
8339            // We will be lenient here and record both ABIs. The primary will be the
8340            // ABI that's higher on the list, i.e, a device that's configured to prefer
8341            // 64 bit apps will see a 64 bit primary ABI,
8342
8343            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8344                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8345            }
8346
8347            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8348                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8349                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8350            } else {
8351                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8352                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8353            }
8354        } else {
8355            pkg.applicationInfo.primaryCpuAbi = null;
8356            pkg.applicationInfo.secondaryCpuAbi = null;
8357        }
8358    }
8359
8360    private void killApplication(String pkgName, int appId, String reason) {
8361        // Request the ActivityManager to kill the process(only for existing packages)
8362        // so that we do not end up in a confused state while the user is still using the older
8363        // version of the application while the new one gets installed.
8364        IActivityManager am = ActivityManagerNative.getDefault();
8365        if (am != null) {
8366            try {
8367                am.killApplicationWithAppId(pkgName, appId, reason);
8368            } catch (RemoteException e) {
8369            }
8370        }
8371    }
8372
8373    void removePackageLI(PackageSetting ps, boolean chatty) {
8374        if (DEBUG_INSTALL) {
8375            if (chatty)
8376                Log.d(TAG, "Removing package " + ps.name);
8377        }
8378
8379        // writer
8380        synchronized (mPackages) {
8381            mPackages.remove(ps.name);
8382            final PackageParser.Package pkg = ps.pkg;
8383            if (pkg != null) {
8384                cleanPackageDataStructuresLILPw(pkg, chatty);
8385            }
8386        }
8387    }
8388
8389    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8390        if (DEBUG_INSTALL) {
8391            if (chatty)
8392                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8393        }
8394
8395        // writer
8396        synchronized (mPackages) {
8397            mPackages.remove(pkg.applicationInfo.packageName);
8398            cleanPackageDataStructuresLILPw(pkg, chatty);
8399        }
8400    }
8401
8402    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8403        int N = pkg.providers.size();
8404        StringBuilder r = null;
8405        int i;
8406        for (i=0; i<N; i++) {
8407            PackageParser.Provider p = pkg.providers.get(i);
8408            mProviders.removeProvider(p);
8409            if (p.info.authority == null) {
8410
8411                /* There was another ContentProvider with this authority when
8412                 * this app was installed so this authority is null,
8413                 * Ignore it as we don't have to unregister the provider.
8414                 */
8415                continue;
8416            }
8417            String names[] = p.info.authority.split(";");
8418            for (int j = 0; j < names.length; j++) {
8419                if (mProvidersByAuthority.get(names[j]) == p) {
8420                    mProvidersByAuthority.remove(names[j]);
8421                    if (DEBUG_REMOVE) {
8422                        if (chatty)
8423                            Log.d(TAG, "Unregistered content provider: " + names[j]
8424                                    + ", className = " + p.info.name + ", isSyncable = "
8425                                    + p.info.isSyncable);
8426                    }
8427                }
8428            }
8429            if (DEBUG_REMOVE && chatty) {
8430                if (r == null) {
8431                    r = new StringBuilder(256);
8432                } else {
8433                    r.append(' ');
8434                }
8435                r.append(p.info.name);
8436            }
8437        }
8438        if (r != null) {
8439            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8440        }
8441
8442        N = pkg.services.size();
8443        r = null;
8444        for (i=0; i<N; i++) {
8445            PackageParser.Service s = pkg.services.get(i);
8446            mServices.removeService(s);
8447            if (chatty) {
8448                if (r == null) {
8449                    r = new StringBuilder(256);
8450                } else {
8451                    r.append(' ');
8452                }
8453                r.append(s.info.name);
8454            }
8455        }
8456        if (r != null) {
8457            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8458        }
8459
8460        N = pkg.receivers.size();
8461        r = null;
8462        for (i=0; i<N; i++) {
8463            PackageParser.Activity a = pkg.receivers.get(i);
8464            mReceivers.removeActivity(a, "receiver");
8465            if (DEBUG_REMOVE && chatty) {
8466                if (r == null) {
8467                    r = new StringBuilder(256);
8468                } else {
8469                    r.append(' ');
8470                }
8471                r.append(a.info.name);
8472            }
8473        }
8474        if (r != null) {
8475            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8476        }
8477
8478        N = pkg.activities.size();
8479        r = null;
8480        for (i=0; i<N; i++) {
8481            PackageParser.Activity a = pkg.activities.get(i);
8482            mActivities.removeActivity(a, "activity");
8483            if (DEBUG_REMOVE && chatty) {
8484                if (r == null) {
8485                    r = new StringBuilder(256);
8486                } else {
8487                    r.append(' ');
8488                }
8489                r.append(a.info.name);
8490            }
8491        }
8492        if (r != null) {
8493            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8494        }
8495
8496        N = pkg.permissions.size();
8497        r = null;
8498        for (i=0; i<N; i++) {
8499            PackageParser.Permission p = pkg.permissions.get(i);
8500            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8501            if (bp == null) {
8502                bp = mSettings.mPermissionTrees.get(p.info.name);
8503            }
8504            if (bp != null && bp.perm == p) {
8505                bp.perm = null;
8506                if (DEBUG_REMOVE && chatty) {
8507                    if (r == null) {
8508                        r = new StringBuilder(256);
8509                    } else {
8510                        r.append(' ');
8511                    }
8512                    r.append(p.info.name);
8513                }
8514            }
8515            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8516                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8517                if (appOpPkgs != null) {
8518                    appOpPkgs.remove(pkg.packageName);
8519                }
8520            }
8521        }
8522        if (r != null) {
8523            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8524        }
8525
8526        N = pkg.requestedPermissions.size();
8527        r = null;
8528        for (i=0; i<N; i++) {
8529            String perm = pkg.requestedPermissions.get(i);
8530            BasePermission bp = mSettings.mPermissions.get(perm);
8531            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8532                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8533                if (appOpPkgs != null) {
8534                    appOpPkgs.remove(pkg.packageName);
8535                    if (appOpPkgs.isEmpty()) {
8536                        mAppOpPermissionPackages.remove(perm);
8537                    }
8538                }
8539            }
8540        }
8541        if (r != null) {
8542            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8543        }
8544
8545        N = pkg.instrumentation.size();
8546        r = null;
8547        for (i=0; i<N; i++) {
8548            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8549            mInstrumentation.remove(a.getComponentName());
8550            if (DEBUG_REMOVE && chatty) {
8551                if (r == null) {
8552                    r = new StringBuilder(256);
8553                } else {
8554                    r.append(' ');
8555                }
8556                r.append(a.info.name);
8557            }
8558        }
8559        if (r != null) {
8560            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8561        }
8562
8563        r = null;
8564        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8565            // Only system apps can hold shared libraries.
8566            if (pkg.libraryNames != null) {
8567                for (i=0; i<pkg.libraryNames.size(); i++) {
8568                    String name = pkg.libraryNames.get(i);
8569                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8570                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8571                        mSharedLibraries.remove(name);
8572                        if (DEBUG_REMOVE && chatty) {
8573                            if (r == null) {
8574                                r = new StringBuilder(256);
8575                            } else {
8576                                r.append(' ');
8577                            }
8578                            r.append(name);
8579                        }
8580                    }
8581                }
8582            }
8583        }
8584        if (r != null) {
8585            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8586        }
8587    }
8588
8589    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8590        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8591            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8592                return true;
8593            }
8594        }
8595        return false;
8596    }
8597
8598    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8599    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8600    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8601
8602    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8603            int flags) {
8604        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8605        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8606    }
8607
8608    private void updatePermissionsLPw(String changingPkg,
8609            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8610        // Make sure there are no dangling permission trees.
8611        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8612        while (it.hasNext()) {
8613            final BasePermission bp = it.next();
8614            if (bp.packageSetting == null) {
8615                // We may not yet have parsed the package, so just see if
8616                // we still know about its settings.
8617                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8618            }
8619            if (bp.packageSetting == null) {
8620                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8621                        + " from package " + bp.sourcePackage);
8622                it.remove();
8623            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8624                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8625                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8626                            + " from package " + bp.sourcePackage);
8627                    flags |= UPDATE_PERMISSIONS_ALL;
8628                    it.remove();
8629                }
8630            }
8631        }
8632
8633        // Make sure all dynamic permissions have been assigned to a package,
8634        // and make sure there are no dangling permissions.
8635        it = mSettings.mPermissions.values().iterator();
8636        while (it.hasNext()) {
8637            final BasePermission bp = it.next();
8638            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8639                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8640                        + bp.name + " pkg=" + bp.sourcePackage
8641                        + " info=" + bp.pendingInfo);
8642                if (bp.packageSetting == null && bp.pendingInfo != null) {
8643                    final BasePermission tree = findPermissionTreeLP(bp.name);
8644                    if (tree != null && tree.perm != null) {
8645                        bp.packageSetting = tree.packageSetting;
8646                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8647                                new PermissionInfo(bp.pendingInfo));
8648                        bp.perm.info.packageName = tree.perm.info.packageName;
8649                        bp.perm.info.name = bp.name;
8650                        bp.uid = tree.uid;
8651                    }
8652                }
8653            }
8654            if (bp.packageSetting == null) {
8655                // We may not yet have parsed the package, so just see if
8656                // we still know about its settings.
8657                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8658            }
8659            if (bp.packageSetting == null) {
8660                Slog.w(TAG, "Removing dangling permission: " + bp.name
8661                        + " from package " + bp.sourcePackage);
8662                it.remove();
8663            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8664                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8665                    Slog.i(TAG, "Removing old permission: " + bp.name
8666                            + " from package " + bp.sourcePackage);
8667                    flags |= UPDATE_PERMISSIONS_ALL;
8668                    it.remove();
8669                }
8670            }
8671        }
8672
8673        // Now update the permissions for all packages, in particular
8674        // replace the granted permissions of the system packages.
8675        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8676            for (PackageParser.Package pkg : mPackages.values()) {
8677                if (pkg != pkgInfo) {
8678                    // Only replace for packages on requested volume
8679                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8680                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8681                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8682                    grantPermissionsLPw(pkg, replace, changingPkg);
8683                }
8684            }
8685        }
8686
8687        if (pkgInfo != null) {
8688            // Only replace for packages on requested volume
8689            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8690            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8691                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8692            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8693        }
8694    }
8695
8696    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8697            String packageOfInterest) {
8698        // IMPORTANT: There are two types of permissions: install and runtime.
8699        // Install time permissions are granted when the app is installed to
8700        // all device users and users added in the future. Runtime permissions
8701        // are granted at runtime explicitly to specific users. Normal and signature
8702        // protected permissions are install time permissions. Dangerous permissions
8703        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8704        // otherwise they are runtime permissions. This function does not manage
8705        // runtime permissions except for the case an app targeting Lollipop MR1
8706        // being upgraded to target a newer SDK, in which case dangerous permissions
8707        // are transformed from install time to runtime ones.
8708
8709        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8710        if (ps == null) {
8711            return;
8712        }
8713
8714        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8715
8716        PermissionsState permissionsState = ps.getPermissionsState();
8717        PermissionsState origPermissions = permissionsState;
8718
8719        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8720
8721        boolean runtimePermissionsRevoked = false;
8722        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8723
8724        boolean changedInstallPermission = false;
8725
8726        if (replace) {
8727            ps.installPermissionsFixed = false;
8728            if (!ps.isSharedUser()) {
8729                origPermissions = new PermissionsState(permissionsState);
8730                permissionsState.reset();
8731            } else {
8732                // We need to know only about runtime permission changes since the
8733                // calling code always writes the install permissions state but
8734                // the runtime ones are written only if changed. The only cases of
8735                // changed runtime permissions here are promotion of an install to
8736                // runtime and revocation of a runtime from a shared user.
8737                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8738                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8739                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8740                    runtimePermissionsRevoked = true;
8741                }
8742            }
8743        }
8744
8745        permissionsState.setGlobalGids(mGlobalGids);
8746
8747        final int N = pkg.requestedPermissions.size();
8748        for (int i=0; i<N; i++) {
8749            final String name = pkg.requestedPermissions.get(i);
8750            final BasePermission bp = mSettings.mPermissions.get(name);
8751
8752            if (DEBUG_INSTALL) {
8753                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8754            }
8755
8756            if (bp == null || bp.packageSetting == null) {
8757                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8758                    Slog.w(TAG, "Unknown permission " + name
8759                            + " in package " + pkg.packageName);
8760                }
8761                continue;
8762            }
8763
8764            final String perm = bp.name;
8765            boolean allowedSig = false;
8766            int grant = GRANT_DENIED;
8767
8768            // Keep track of app op permissions.
8769            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8770                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8771                if (pkgs == null) {
8772                    pkgs = new ArraySet<>();
8773                    mAppOpPermissionPackages.put(bp.name, pkgs);
8774                }
8775                pkgs.add(pkg.packageName);
8776            }
8777
8778            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8779            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8780                    >= Build.VERSION_CODES.M;
8781            switch (level) {
8782                case PermissionInfo.PROTECTION_NORMAL: {
8783                    // For all apps normal permissions are install time ones.
8784                    grant = GRANT_INSTALL;
8785                } break;
8786
8787                case PermissionInfo.PROTECTION_DANGEROUS: {
8788                    // If a permission review is required for legacy apps we represent
8789                    // their permissions as always granted runtime ones since we need
8790                    // to keep the review required permission flag per user while an
8791                    // install permission's state is shared across all users.
8792                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8793                        // For legacy apps dangerous permissions are install time ones.
8794                        grant = GRANT_INSTALL;
8795                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8796                        // For legacy apps that became modern, install becomes runtime.
8797                        grant = GRANT_UPGRADE;
8798                    } else if (mPromoteSystemApps
8799                            && isSystemApp(ps)
8800                            && mExistingSystemPackages.contains(ps.name)) {
8801                        // For legacy system apps, install becomes runtime.
8802                        // We cannot check hasInstallPermission() for system apps since those
8803                        // permissions were granted implicitly and not persisted pre-M.
8804                        grant = GRANT_UPGRADE;
8805                    } else {
8806                        // For modern apps keep runtime permissions unchanged.
8807                        grant = GRANT_RUNTIME;
8808                    }
8809                } break;
8810
8811                case PermissionInfo.PROTECTION_SIGNATURE: {
8812                    // For all apps signature permissions are install time ones.
8813                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8814                    if (allowedSig) {
8815                        grant = GRANT_INSTALL;
8816                    }
8817                } break;
8818            }
8819
8820            if (DEBUG_INSTALL) {
8821                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8822            }
8823
8824            if (grant != GRANT_DENIED) {
8825                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8826                    // If this is an existing, non-system package, then
8827                    // we can't add any new permissions to it.
8828                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8829                        // Except...  if this is a permission that was added
8830                        // to the platform (note: need to only do this when
8831                        // updating the platform).
8832                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8833                            grant = GRANT_DENIED;
8834                        }
8835                    }
8836                }
8837
8838                switch (grant) {
8839                    case GRANT_INSTALL: {
8840                        // Revoke this as runtime permission to handle the case of
8841                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8842                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8843                            if (origPermissions.getRuntimePermissionState(
8844                                    bp.name, userId) != null) {
8845                                // Revoke the runtime permission and clear the flags.
8846                                origPermissions.revokeRuntimePermission(bp, userId);
8847                                origPermissions.updatePermissionFlags(bp, userId,
8848                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8849                                // If we revoked a permission permission, we have to write.
8850                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8851                                        changedRuntimePermissionUserIds, userId);
8852                            }
8853                        }
8854                        // Grant an install permission.
8855                        if (permissionsState.grantInstallPermission(bp) !=
8856                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8857                            changedInstallPermission = true;
8858                        }
8859                    } break;
8860
8861                    case GRANT_RUNTIME: {
8862                        // Grant previously granted runtime permissions.
8863                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8864                            PermissionState permissionState = origPermissions
8865                                    .getRuntimePermissionState(bp.name, userId);
8866                            int flags = permissionState != null
8867                                    ? permissionState.getFlags() : 0;
8868                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8869                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8870                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8871                                    // If we cannot put the permission as it was, we have to write.
8872                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8873                                            changedRuntimePermissionUserIds, userId);
8874                                }
8875                                // If the app supports runtime permissions no need for a review.
8876                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8877                                        && appSupportsRuntimePermissions
8878                                        && (flags & PackageManager
8879                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8880                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8881                                    // Since we changed the flags, we have to write.
8882                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8883                                            changedRuntimePermissionUserIds, userId);
8884                                }
8885                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8886                                    && !appSupportsRuntimePermissions) {
8887                                // For legacy apps that need a permission review, every new
8888                                // runtime permission is granted but it is pending a review.
8889                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8890                                    permissionsState.grantRuntimePermission(bp, userId);
8891                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8892                                    // We changed the permission and flags, hence have to write.
8893                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8894                                            changedRuntimePermissionUserIds, userId);
8895                                }
8896                            }
8897                            // Propagate the permission flags.
8898                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8899                        }
8900                    } break;
8901
8902                    case GRANT_UPGRADE: {
8903                        // Grant runtime permissions for a previously held install permission.
8904                        PermissionState permissionState = origPermissions
8905                                .getInstallPermissionState(bp.name);
8906                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8907
8908                        if (origPermissions.revokeInstallPermission(bp)
8909                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8910                            // We will be transferring the permission flags, so clear them.
8911                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8912                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8913                            changedInstallPermission = true;
8914                        }
8915
8916                        // If the permission is not to be promoted to runtime we ignore it and
8917                        // also its other flags as they are not applicable to install permissions.
8918                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8919                            for (int userId : currentUserIds) {
8920                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8921                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8922                                    // Transfer the permission flags.
8923                                    permissionsState.updatePermissionFlags(bp, userId,
8924                                            flags, flags);
8925                                    // If we granted the permission, we have to write.
8926                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8927                                            changedRuntimePermissionUserIds, userId);
8928                                }
8929                            }
8930                        }
8931                    } break;
8932
8933                    default: {
8934                        if (packageOfInterest == null
8935                                || packageOfInterest.equals(pkg.packageName)) {
8936                            Slog.w(TAG, "Not granting permission " + perm
8937                                    + " to package " + pkg.packageName
8938                                    + " because it was previously installed without");
8939                        }
8940                    } break;
8941                }
8942            } else {
8943                if (permissionsState.revokeInstallPermission(bp) !=
8944                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8945                    // Also drop the permission flags.
8946                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8947                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8948                    changedInstallPermission = true;
8949                    Slog.i(TAG, "Un-granting permission " + perm
8950                            + " from package " + pkg.packageName
8951                            + " (protectionLevel=" + bp.protectionLevel
8952                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8953                            + ")");
8954                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8955                    // Don't print warning for app op permissions, since it is fine for them
8956                    // not to be granted, there is a UI for the user to decide.
8957                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8958                        Slog.w(TAG, "Not granting permission " + perm
8959                                + " to package " + pkg.packageName
8960                                + " (protectionLevel=" + bp.protectionLevel
8961                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8962                                + ")");
8963                    }
8964                }
8965            }
8966        }
8967
8968        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8969                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8970            // This is the first that we have heard about this package, so the
8971            // permissions we have now selected are fixed until explicitly
8972            // changed.
8973            ps.installPermissionsFixed = true;
8974        }
8975
8976        // Persist the runtime permissions state for users with changes. If permissions
8977        // were revoked because no app in the shared user declares them we have to
8978        // write synchronously to avoid losing runtime permissions state.
8979        for (int userId : changedRuntimePermissionUserIds) {
8980            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8981        }
8982
8983        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8984    }
8985
8986    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8987        boolean allowed = false;
8988        final int NP = PackageParser.NEW_PERMISSIONS.length;
8989        for (int ip=0; ip<NP; ip++) {
8990            final PackageParser.NewPermissionInfo npi
8991                    = PackageParser.NEW_PERMISSIONS[ip];
8992            if (npi.name.equals(perm)
8993                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8994                allowed = true;
8995                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8996                        + pkg.packageName);
8997                break;
8998            }
8999        }
9000        return allowed;
9001    }
9002
9003    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9004            BasePermission bp, PermissionsState origPermissions) {
9005        boolean allowed;
9006        allowed = (compareSignatures(
9007                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9008                        == PackageManager.SIGNATURE_MATCH)
9009                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9010                        == PackageManager.SIGNATURE_MATCH);
9011        if (!allowed && (bp.protectionLevel
9012                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9013            if (isSystemApp(pkg)) {
9014                // For updated system applications, a system permission
9015                // is granted only if it had been defined by the original application.
9016                if (pkg.isUpdatedSystemApp()) {
9017                    final PackageSetting sysPs = mSettings
9018                            .getDisabledSystemPkgLPr(pkg.packageName);
9019                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9020                        // If the original was granted this permission, we take
9021                        // that grant decision as read and propagate it to the
9022                        // update.
9023                        if (sysPs.isPrivileged()) {
9024                            allowed = true;
9025                        }
9026                    } else {
9027                        // The system apk may have been updated with an older
9028                        // version of the one on the data partition, but which
9029                        // granted a new system permission that it didn't have
9030                        // before.  In this case we do want to allow the app to
9031                        // now get the new permission if the ancestral apk is
9032                        // privileged to get it.
9033                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9034                            for (int j=0;
9035                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9036                                if (perm.equals(
9037                                        sysPs.pkg.requestedPermissions.get(j))) {
9038                                    allowed = true;
9039                                    break;
9040                                }
9041                            }
9042                        }
9043                    }
9044                } else {
9045                    allowed = isPrivilegedApp(pkg);
9046                }
9047            }
9048        }
9049        if (!allowed) {
9050            if (!allowed && (bp.protectionLevel
9051                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9052                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9053                // If this was a previously normal/dangerous permission that got moved
9054                // to a system permission as part of the runtime permission redesign, then
9055                // we still want to blindly grant it to old apps.
9056                allowed = true;
9057            }
9058            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9059                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9060                // If this permission is to be granted to the system installer and
9061                // this app is an installer, then it gets the permission.
9062                allowed = true;
9063            }
9064            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9065                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9066                // If this permission is to be granted to the system verifier and
9067                // this app is a verifier, then it gets the permission.
9068                allowed = true;
9069            }
9070            if (!allowed && (bp.protectionLevel
9071                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9072                    && isSystemApp(pkg)) {
9073                // Any pre-installed system app is allowed to get this permission.
9074                allowed = true;
9075            }
9076            if (!allowed && (bp.protectionLevel
9077                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9078                // For development permissions, a development permission
9079                // is granted only if it was already granted.
9080                allowed = origPermissions.hasInstallPermission(perm);
9081            }
9082        }
9083        return allowed;
9084    }
9085
9086    final class ActivityIntentResolver
9087            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9088        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9089                boolean defaultOnly, int userId) {
9090            if (!sUserManager.exists(userId)) return null;
9091            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9092            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9093        }
9094
9095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9096                int userId) {
9097            if (!sUserManager.exists(userId)) return null;
9098            mFlags = flags;
9099            return super.queryIntent(intent, resolvedType,
9100                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9101        }
9102
9103        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9104                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9105            if (!sUserManager.exists(userId)) return null;
9106            if (packageActivities == null) {
9107                return null;
9108            }
9109            mFlags = flags;
9110            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9111            final int N = packageActivities.size();
9112            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9113                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9114
9115            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9116            for (int i = 0; i < N; ++i) {
9117                intentFilters = packageActivities.get(i).intents;
9118                if (intentFilters != null && intentFilters.size() > 0) {
9119                    PackageParser.ActivityIntentInfo[] array =
9120                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9121                    intentFilters.toArray(array);
9122                    listCut.add(array);
9123                }
9124            }
9125            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9126        }
9127
9128        public final void addActivity(PackageParser.Activity a, String type) {
9129            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9130            mActivities.put(a.getComponentName(), a);
9131            if (DEBUG_SHOW_INFO)
9132                Log.v(
9133                TAG, "  " + type + " " +
9134                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9135            if (DEBUG_SHOW_INFO)
9136                Log.v(TAG, "    Class=" + a.info.name);
9137            final int NI = a.intents.size();
9138            for (int j=0; j<NI; j++) {
9139                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9140                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9141                    intent.setPriority(0);
9142                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9143                            + a.className + " with priority > 0, forcing to 0");
9144                }
9145                if (DEBUG_SHOW_INFO) {
9146                    Log.v(TAG, "    IntentFilter:");
9147                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9148                }
9149                if (!intent.debugCheck()) {
9150                    Log.w(TAG, "==> For Activity " + a.info.name);
9151                }
9152                addFilter(intent);
9153            }
9154        }
9155
9156        public final void removeActivity(PackageParser.Activity a, String type) {
9157            mActivities.remove(a.getComponentName());
9158            if (DEBUG_SHOW_INFO) {
9159                Log.v(TAG, "  " + type + " "
9160                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9161                                : a.info.name) + ":");
9162                Log.v(TAG, "    Class=" + a.info.name);
9163            }
9164            final int NI = a.intents.size();
9165            for (int j=0; j<NI; j++) {
9166                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9167                if (DEBUG_SHOW_INFO) {
9168                    Log.v(TAG, "    IntentFilter:");
9169                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9170                }
9171                removeFilter(intent);
9172            }
9173        }
9174
9175        @Override
9176        protected boolean allowFilterResult(
9177                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9178            ActivityInfo filterAi = filter.activity.info;
9179            for (int i=dest.size()-1; i>=0; i--) {
9180                ActivityInfo destAi = dest.get(i).activityInfo;
9181                if (destAi.name == filterAi.name
9182                        && destAi.packageName == filterAi.packageName) {
9183                    return false;
9184                }
9185            }
9186            return true;
9187        }
9188
9189        @Override
9190        protected ActivityIntentInfo[] newArray(int size) {
9191            return new ActivityIntentInfo[size];
9192        }
9193
9194        @Override
9195        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9196            if (!sUserManager.exists(userId)) return true;
9197            PackageParser.Package p = filter.activity.owner;
9198            if (p != null) {
9199                PackageSetting ps = (PackageSetting)p.mExtras;
9200                if (ps != null) {
9201                    // System apps are never considered stopped for purposes of
9202                    // filtering, because there may be no way for the user to
9203                    // actually re-launch them.
9204                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9205                            && ps.getStopped(userId);
9206                }
9207            }
9208            return false;
9209        }
9210
9211        @Override
9212        protected boolean isPackageForFilter(String packageName,
9213                PackageParser.ActivityIntentInfo info) {
9214            return packageName.equals(info.activity.owner.packageName);
9215        }
9216
9217        @Override
9218        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9219                int match, int userId) {
9220            if (!sUserManager.exists(userId)) return null;
9221            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9222                return null;
9223            }
9224            final PackageParser.Activity activity = info.activity;
9225            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9226            if (ps == null) {
9227                return null;
9228            }
9229            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9230                    ps.readUserState(userId), userId);
9231            if (ai == null) {
9232                return null;
9233            }
9234            final ResolveInfo res = new ResolveInfo();
9235            res.activityInfo = ai;
9236            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9237                res.filter = info;
9238            }
9239            if (info != null) {
9240                res.handleAllWebDataURI = info.handleAllWebDataURI();
9241            }
9242            res.priority = info.getPriority();
9243            res.preferredOrder = activity.owner.mPreferredOrder;
9244            //System.out.println("Result: " + res.activityInfo.className +
9245            //                   " = " + res.priority);
9246            res.match = match;
9247            res.isDefault = info.hasDefault;
9248            res.labelRes = info.labelRes;
9249            res.nonLocalizedLabel = info.nonLocalizedLabel;
9250            if (userNeedsBadging(userId)) {
9251                res.noResourceId = true;
9252            } else {
9253                res.icon = info.icon;
9254            }
9255            res.iconResourceId = info.icon;
9256            res.system = res.activityInfo.applicationInfo.isSystemApp();
9257            return res;
9258        }
9259
9260        @Override
9261        protected void sortResults(List<ResolveInfo> results) {
9262            Collections.sort(results, mResolvePrioritySorter);
9263        }
9264
9265        @Override
9266        protected void dumpFilter(PrintWriter out, String prefix,
9267                PackageParser.ActivityIntentInfo filter) {
9268            out.print(prefix); out.print(
9269                    Integer.toHexString(System.identityHashCode(filter.activity)));
9270                    out.print(' ');
9271                    filter.activity.printComponentShortName(out);
9272                    out.print(" filter ");
9273                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9274        }
9275
9276        @Override
9277        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9278            return filter.activity;
9279        }
9280
9281        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9282            PackageParser.Activity activity = (PackageParser.Activity)label;
9283            out.print(prefix); out.print(
9284                    Integer.toHexString(System.identityHashCode(activity)));
9285                    out.print(' ');
9286                    activity.printComponentShortName(out);
9287            if (count > 1) {
9288                out.print(" ("); out.print(count); out.print(" filters)");
9289            }
9290            out.println();
9291        }
9292
9293//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9294//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9295//            final List<ResolveInfo> retList = Lists.newArrayList();
9296//            while (i.hasNext()) {
9297//                final ResolveInfo resolveInfo = i.next();
9298//                if (isEnabledLP(resolveInfo.activityInfo)) {
9299//                    retList.add(resolveInfo);
9300//                }
9301//            }
9302//            return retList;
9303//        }
9304
9305        // Keys are String (activity class name), values are Activity.
9306        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9307                = new ArrayMap<ComponentName, PackageParser.Activity>();
9308        private int mFlags;
9309    }
9310
9311    private final class ServiceIntentResolver
9312            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9313        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9314                boolean defaultOnly, int userId) {
9315            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9316            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9317        }
9318
9319        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9320                int userId) {
9321            if (!sUserManager.exists(userId)) return null;
9322            mFlags = flags;
9323            return super.queryIntent(intent, resolvedType,
9324                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9325        }
9326
9327        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9328                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9329            if (!sUserManager.exists(userId)) return null;
9330            if (packageServices == null) {
9331                return null;
9332            }
9333            mFlags = flags;
9334            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9335            final int N = packageServices.size();
9336            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9337                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9338
9339            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9340            for (int i = 0; i < N; ++i) {
9341                intentFilters = packageServices.get(i).intents;
9342                if (intentFilters != null && intentFilters.size() > 0) {
9343                    PackageParser.ServiceIntentInfo[] array =
9344                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9345                    intentFilters.toArray(array);
9346                    listCut.add(array);
9347                }
9348            }
9349            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9350        }
9351
9352        public final void addService(PackageParser.Service s) {
9353            mServices.put(s.getComponentName(), s);
9354            if (DEBUG_SHOW_INFO) {
9355                Log.v(TAG, "  "
9356                        + (s.info.nonLocalizedLabel != null
9357                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9358                Log.v(TAG, "    Class=" + s.info.name);
9359            }
9360            final int NI = s.intents.size();
9361            int j;
9362            for (j=0; j<NI; j++) {
9363                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9364                if (DEBUG_SHOW_INFO) {
9365                    Log.v(TAG, "    IntentFilter:");
9366                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9367                }
9368                if (!intent.debugCheck()) {
9369                    Log.w(TAG, "==> For Service " + s.info.name);
9370                }
9371                addFilter(intent);
9372            }
9373        }
9374
9375        public final void removeService(PackageParser.Service s) {
9376            mServices.remove(s.getComponentName());
9377            if (DEBUG_SHOW_INFO) {
9378                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9379                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9380                Log.v(TAG, "    Class=" + s.info.name);
9381            }
9382            final int NI = s.intents.size();
9383            int j;
9384            for (j=0; j<NI; j++) {
9385                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9386                if (DEBUG_SHOW_INFO) {
9387                    Log.v(TAG, "    IntentFilter:");
9388                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9389                }
9390                removeFilter(intent);
9391            }
9392        }
9393
9394        @Override
9395        protected boolean allowFilterResult(
9396                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9397            ServiceInfo filterSi = filter.service.info;
9398            for (int i=dest.size()-1; i>=0; i--) {
9399                ServiceInfo destAi = dest.get(i).serviceInfo;
9400                if (destAi.name == filterSi.name
9401                        && destAi.packageName == filterSi.packageName) {
9402                    return false;
9403                }
9404            }
9405            return true;
9406        }
9407
9408        @Override
9409        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9410            return new PackageParser.ServiceIntentInfo[size];
9411        }
9412
9413        @Override
9414        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9415            if (!sUserManager.exists(userId)) return true;
9416            PackageParser.Package p = filter.service.owner;
9417            if (p != null) {
9418                PackageSetting ps = (PackageSetting)p.mExtras;
9419                if (ps != null) {
9420                    // System apps are never considered stopped for purposes of
9421                    // filtering, because there may be no way for the user to
9422                    // actually re-launch them.
9423                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9424                            && ps.getStopped(userId);
9425                }
9426            }
9427            return false;
9428        }
9429
9430        @Override
9431        protected boolean isPackageForFilter(String packageName,
9432                PackageParser.ServiceIntentInfo info) {
9433            return packageName.equals(info.service.owner.packageName);
9434        }
9435
9436        @Override
9437        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9438                int match, int userId) {
9439            if (!sUserManager.exists(userId)) return null;
9440            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9441            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9442                return null;
9443            }
9444            final PackageParser.Service service = info.service;
9445            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9446            if (ps == null) {
9447                return null;
9448            }
9449            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9450                    ps.readUserState(userId), userId);
9451            if (si == null) {
9452                return null;
9453            }
9454            final ResolveInfo res = new ResolveInfo();
9455            res.serviceInfo = si;
9456            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9457                res.filter = filter;
9458            }
9459            res.priority = info.getPriority();
9460            res.preferredOrder = service.owner.mPreferredOrder;
9461            res.match = match;
9462            res.isDefault = info.hasDefault;
9463            res.labelRes = info.labelRes;
9464            res.nonLocalizedLabel = info.nonLocalizedLabel;
9465            res.icon = info.icon;
9466            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9467            return res;
9468        }
9469
9470        @Override
9471        protected void sortResults(List<ResolveInfo> results) {
9472            Collections.sort(results, mResolvePrioritySorter);
9473        }
9474
9475        @Override
9476        protected void dumpFilter(PrintWriter out, String prefix,
9477                PackageParser.ServiceIntentInfo filter) {
9478            out.print(prefix); out.print(
9479                    Integer.toHexString(System.identityHashCode(filter.service)));
9480                    out.print(' ');
9481                    filter.service.printComponentShortName(out);
9482                    out.print(" filter ");
9483                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9484        }
9485
9486        @Override
9487        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9488            return filter.service;
9489        }
9490
9491        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9492            PackageParser.Service service = (PackageParser.Service)label;
9493            out.print(prefix); out.print(
9494                    Integer.toHexString(System.identityHashCode(service)));
9495                    out.print(' ');
9496                    service.printComponentShortName(out);
9497            if (count > 1) {
9498                out.print(" ("); out.print(count); out.print(" filters)");
9499            }
9500            out.println();
9501        }
9502
9503//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9504//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9505//            final List<ResolveInfo> retList = Lists.newArrayList();
9506//            while (i.hasNext()) {
9507//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9508//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9509//                    retList.add(resolveInfo);
9510//                }
9511//            }
9512//            return retList;
9513//        }
9514
9515        // Keys are String (activity class name), values are Activity.
9516        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9517                = new ArrayMap<ComponentName, PackageParser.Service>();
9518        private int mFlags;
9519    };
9520
9521    private final class ProviderIntentResolver
9522            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9523        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9524                boolean defaultOnly, int userId) {
9525            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9526            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9527        }
9528
9529        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9530                int userId) {
9531            if (!sUserManager.exists(userId))
9532                return null;
9533            mFlags = flags;
9534            return super.queryIntent(intent, resolvedType,
9535                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9536        }
9537
9538        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9539                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9540            if (!sUserManager.exists(userId))
9541                return null;
9542            if (packageProviders == null) {
9543                return null;
9544            }
9545            mFlags = flags;
9546            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9547            final int N = packageProviders.size();
9548            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9549                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9550
9551            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9552            for (int i = 0; i < N; ++i) {
9553                intentFilters = packageProviders.get(i).intents;
9554                if (intentFilters != null && intentFilters.size() > 0) {
9555                    PackageParser.ProviderIntentInfo[] array =
9556                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9557                    intentFilters.toArray(array);
9558                    listCut.add(array);
9559                }
9560            }
9561            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9562        }
9563
9564        public final void addProvider(PackageParser.Provider p) {
9565            if (mProviders.containsKey(p.getComponentName())) {
9566                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9567                return;
9568            }
9569
9570            mProviders.put(p.getComponentName(), p);
9571            if (DEBUG_SHOW_INFO) {
9572                Log.v(TAG, "  "
9573                        + (p.info.nonLocalizedLabel != null
9574                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9575                Log.v(TAG, "    Class=" + p.info.name);
9576            }
9577            final int NI = p.intents.size();
9578            int j;
9579            for (j = 0; j < NI; j++) {
9580                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9581                if (DEBUG_SHOW_INFO) {
9582                    Log.v(TAG, "    IntentFilter:");
9583                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9584                }
9585                if (!intent.debugCheck()) {
9586                    Log.w(TAG, "==> For Provider " + p.info.name);
9587                }
9588                addFilter(intent);
9589            }
9590        }
9591
9592        public final void removeProvider(PackageParser.Provider p) {
9593            mProviders.remove(p.getComponentName());
9594            if (DEBUG_SHOW_INFO) {
9595                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9596                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9597                Log.v(TAG, "    Class=" + p.info.name);
9598            }
9599            final int NI = p.intents.size();
9600            int j;
9601            for (j = 0; j < NI; j++) {
9602                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9603                if (DEBUG_SHOW_INFO) {
9604                    Log.v(TAG, "    IntentFilter:");
9605                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9606                }
9607                removeFilter(intent);
9608            }
9609        }
9610
9611        @Override
9612        protected boolean allowFilterResult(
9613                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9614            ProviderInfo filterPi = filter.provider.info;
9615            for (int i = dest.size() - 1; i >= 0; i--) {
9616                ProviderInfo destPi = dest.get(i).providerInfo;
9617                if (destPi.name == filterPi.name
9618                        && destPi.packageName == filterPi.packageName) {
9619                    return false;
9620                }
9621            }
9622            return true;
9623        }
9624
9625        @Override
9626        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9627            return new PackageParser.ProviderIntentInfo[size];
9628        }
9629
9630        @Override
9631        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9632            if (!sUserManager.exists(userId))
9633                return true;
9634            PackageParser.Package p = filter.provider.owner;
9635            if (p != null) {
9636                PackageSetting ps = (PackageSetting) p.mExtras;
9637                if (ps != null) {
9638                    // System apps are never considered stopped for purposes of
9639                    // filtering, because there may be no way for the user to
9640                    // actually re-launch them.
9641                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9642                            && ps.getStopped(userId);
9643                }
9644            }
9645            return false;
9646        }
9647
9648        @Override
9649        protected boolean isPackageForFilter(String packageName,
9650                PackageParser.ProviderIntentInfo info) {
9651            return packageName.equals(info.provider.owner.packageName);
9652        }
9653
9654        @Override
9655        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9656                int match, int userId) {
9657            if (!sUserManager.exists(userId))
9658                return null;
9659            final PackageParser.ProviderIntentInfo info = filter;
9660            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9661                return null;
9662            }
9663            final PackageParser.Provider provider = info.provider;
9664            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9665            if (ps == null) {
9666                return null;
9667            }
9668            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9669                    ps.readUserState(userId), userId);
9670            if (pi == null) {
9671                return null;
9672            }
9673            final ResolveInfo res = new ResolveInfo();
9674            res.providerInfo = pi;
9675            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9676                res.filter = filter;
9677            }
9678            res.priority = info.getPriority();
9679            res.preferredOrder = provider.owner.mPreferredOrder;
9680            res.match = match;
9681            res.isDefault = info.hasDefault;
9682            res.labelRes = info.labelRes;
9683            res.nonLocalizedLabel = info.nonLocalizedLabel;
9684            res.icon = info.icon;
9685            res.system = res.providerInfo.applicationInfo.isSystemApp();
9686            return res;
9687        }
9688
9689        @Override
9690        protected void sortResults(List<ResolveInfo> results) {
9691            Collections.sort(results, mResolvePrioritySorter);
9692        }
9693
9694        @Override
9695        protected void dumpFilter(PrintWriter out, String prefix,
9696                PackageParser.ProviderIntentInfo filter) {
9697            out.print(prefix);
9698            out.print(
9699                    Integer.toHexString(System.identityHashCode(filter.provider)));
9700            out.print(' ');
9701            filter.provider.printComponentShortName(out);
9702            out.print(" filter ");
9703            out.println(Integer.toHexString(System.identityHashCode(filter)));
9704        }
9705
9706        @Override
9707        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9708            return filter.provider;
9709        }
9710
9711        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9712            PackageParser.Provider provider = (PackageParser.Provider)label;
9713            out.print(prefix); out.print(
9714                    Integer.toHexString(System.identityHashCode(provider)));
9715                    out.print(' ');
9716                    provider.printComponentShortName(out);
9717            if (count > 1) {
9718                out.print(" ("); out.print(count); out.print(" filters)");
9719            }
9720            out.println();
9721        }
9722
9723        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9724                = new ArrayMap<ComponentName, PackageParser.Provider>();
9725        private int mFlags;
9726    }
9727
9728    private static final class EphemeralIntentResolver
9729            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9730        @Override
9731        protected EphemeralResolveIntentInfo[] newArray(int size) {
9732            return new EphemeralResolveIntentInfo[size];
9733        }
9734
9735        @Override
9736        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9737            return true;
9738        }
9739
9740        @Override
9741        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9742                int userId) {
9743            if (!sUserManager.exists(userId)) {
9744                return null;
9745            }
9746            return info.getEphemeralResolveInfo();
9747        }
9748    }
9749
9750    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9751            new Comparator<ResolveInfo>() {
9752        public int compare(ResolveInfo r1, ResolveInfo r2) {
9753            int v1 = r1.priority;
9754            int v2 = r2.priority;
9755            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9756            if (v1 != v2) {
9757                return (v1 > v2) ? -1 : 1;
9758            }
9759            v1 = r1.preferredOrder;
9760            v2 = r2.preferredOrder;
9761            if (v1 != v2) {
9762                return (v1 > v2) ? -1 : 1;
9763            }
9764            if (r1.isDefault != r2.isDefault) {
9765                return r1.isDefault ? -1 : 1;
9766            }
9767            v1 = r1.match;
9768            v2 = r2.match;
9769            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9770            if (v1 != v2) {
9771                return (v1 > v2) ? -1 : 1;
9772            }
9773            if (r1.system != r2.system) {
9774                return r1.system ? -1 : 1;
9775            }
9776            if (r1.activityInfo != null) {
9777                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9778            }
9779            if (r1.serviceInfo != null) {
9780                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9781            }
9782            if (r1.providerInfo != null) {
9783                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9784            }
9785            return 0;
9786        }
9787    };
9788
9789    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9790            new Comparator<ProviderInfo>() {
9791        public int compare(ProviderInfo p1, ProviderInfo p2) {
9792            final int v1 = p1.initOrder;
9793            final int v2 = p2.initOrder;
9794            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9795        }
9796    };
9797
9798    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9799            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9800            final int[] userIds) {
9801        mHandler.post(new Runnable() {
9802            @Override
9803            public void run() {
9804                try {
9805                    final IActivityManager am = ActivityManagerNative.getDefault();
9806                    if (am == null) return;
9807                    final int[] resolvedUserIds;
9808                    if (userIds == null) {
9809                        resolvedUserIds = am.getRunningUserIds();
9810                    } else {
9811                        resolvedUserIds = userIds;
9812                    }
9813                    for (int id : resolvedUserIds) {
9814                        final Intent intent = new Intent(action,
9815                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9816                        if (extras != null) {
9817                            intent.putExtras(extras);
9818                        }
9819                        if (targetPkg != null) {
9820                            intent.setPackage(targetPkg);
9821                        }
9822                        // Modify the UID when posting to other users
9823                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9824                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9825                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9826                            intent.putExtra(Intent.EXTRA_UID, uid);
9827                        }
9828                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9829                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9830                        if (DEBUG_BROADCASTS) {
9831                            RuntimeException here = new RuntimeException("here");
9832                            here.fillInStackTrace();
9833                            Slog.d(TAG, "Sending to user " + id + ": "
9834                                    + intent.toShortString(false, true, false, false)
9835                                    + " " + intent.getExtras(), here);
9836                        }
9837                        am.broadcastIntent(null, intent, null, finishedReceiver,
9838                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9839                                null, finishedReceiver != null, false, id);
9840                    }
9841                } catch (RemoteException ex) {
9842                }
9843            }
9844        });
9845    }
9846
9847    /**
9848     * Check if the external storage media is available. This is true if there
9849     * is a mounted external storage medium or if the external storage is
9850     * emulated.
9851     */
9852    private boolean isExternalMediaAvailable() {
9853        return mMediaMounted || Environment.isExternalStorageEmulated();
9854    }
9855
9856    @Override
9857    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9858        // writer
9859        synchronized (mPackages) {
9860            if (!isExternalMediaAvailable()) {
9861                // If the external storage is no longer mounted at this point,
9862                // the caller may not have been able to delete all of this
9863                // packages files and can not delete any more.  Bail.
9864                return null;
9865            }
9866            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9867            if (lastPackage != null) {
9868                pkgs.remove(lastPackage);
9869            }
9870            if (pkgs.size() > 0) {
9871                return pkgs.get(0);
9872            }
9873        }
9874        return null;
9875    }
9876
9877    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9878        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9879                userId, andCode ? 1 : 0, packageName);
9880        if (mSystemReady) {
9881            msg.sendToTarget();
9882        } else {
9883            if (mPostSystemReadyMessages == null) {
9884                mPostSystemReadyMessages = new ArrayList<>();
9885            }
9886            mPostSystemReadyMessages.add(msg);
9887        }
9888    }
9889
9890    void startCleaningPackages() {
9891        // reader
9892        synchronized (mPackages) {
9893            if (!isExternalMediaAvailable()) {
9894                return;
9895            }
9896            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9897                return;
9898            }
9899        }
9900        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9901        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9902        IActivityManager am = ActivityManagerNative.getDefault();
9903        if (am != null) {
9904            try {
9905                am.startService(null, intent, null, mContext.getOpPackageName(),
9906                        UserHandle.USER_SYSTEM);
9907            } catch (RemoteException e) {
9908            }
9909        }
9910    }
9911
9912    @Override
9913    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9914            int installFlags, String installerPackageName, VerificationParams verificationParams,
9915            String packageAbiOverride) {
9916        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9917                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9918    }
9919
9920    @Override
9921    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9922            int installFlags, String installerPackageName, VerificationParams verificationParams,
9923            String packageAbiOverride, int userId) {
9924        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9925
9926        final int callingUid = Binder.getCallingUid();
9927        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9928
9929        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9930            try {
9931                if (observer != null) {
9932                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9933                }
9934            } catch (RemoteException re) {
9935            }
9936            return;
9937        }
9938
9939        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9940            installFlags |= PackageManager.INSTALL_FROM_ADB;
9941
9942        } else {
9943            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9944            // about installerPackageName.
9945
9946            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9947            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9948        }
9949
9950        UserHandle user;
9951        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9952            user = UserHandle.ALL;
9953        } else {
9954            user = new UserHandle(userId);
9955        }
9956
9957        // Only system components can circumvent runtime permissions when installing.
9958        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9959                && mContext.checkCallingOrSelfPermission(Manifest.permission
9960                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9961            throw new SecurityException("You need the "
9962                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9963                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9964        }
9965
9966        verificationParams.setInstallerUid(callingUid);
9967
9968        final File originFile = new File(originPath);
9969        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9970
9971        final Message msg = mHandler.obtainMessage(INIT_COPY);
9972        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9973                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9974        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9975        msg.obj = params;
9976
9977        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9978                System.identityHashCode(msg.obj));
9979        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9980                System.identityHashCode(msg.obj));
9981
9982        mHandler.sendMessage(msg);
9983    }
9984
9985    void installStage(String packageName, File stagedDir, String stagedCid,
9986            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9987            String installerPackageName, int installerUid, UserHandle user) {
9988        if (DEBUG_EPHEMERAL) {
9989            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9990                Slog.d(TAG, "Ephemeral install of " + packageName);
9991            }
9992        }
9993        final VerificationParams verifParams = new VerificationParams(
9994                null, sessionParams.originatingUri, sessionParams.referrerUri,
9995                sessionParams.originatingUid);
9996        verifParams.setInstallerUid(installerUid);
9997
9998        final OriginInfo origin;
9999        if (stagedDir != null) {
10000            origin = OriginInfo.fromStagedFile(stagedDir);
10001        } else {
10002            origin = OriginInfo.fromStagedContainer(stagedCid);
10003        }
10004
10005        final Message msg = mHandler.obtainMessage(INIT_COPY);
10006        final InstallParams params = new InstallParams(origin, null, observer,
10007                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10008                verifParams, user, sessionParams.abiOverride,
10009                sessionParams.grantedRuntimePermissions);
10010        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10011        msg.obj = params;
10012
10013        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10014                System.identityHashCode(msg.obj));
10015        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10016                System.identityHashCode(msg.obj));
10017
10018        mHandler.sendMessage(msg);
10019    }
10020
10021    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10022        Bundle extras = new Bundle(1);
10023        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10024
10025        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10026                packageName, extras, 0, null, null, new int[] {userId});
10027        try {
10028            IActivityManager am = ActivityManagerNative.getDefault();
10029            final boolean isSystem =
10030                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10031            if (isSystem && am.isUserRunning(userId, 0)) {
10032                // The just-installed/enabled app is bundled on the system, so presumed
10033                // to be able to run automatically without needing an explicit launch.
10034                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10035                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10036                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10037                        .setPackage(packageName);
10038                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10039                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10040            }
10041        } catch (RemoteException e) {
10042            // shouldn't happen
10043            Slog.w(TAG, "Unable to bootstrap installed package", e);
10044        }
10045    }
10046
10047    @Override
10048    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10049            int userId) {
10050        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10051        PackageSetting pkgSetting;
10052        final int uid = Binder.getCallingUid();
10053        enforceCrossUserPermission(uid, userId, true, true,
10054                "setApplicationHiddenSetting for user " + userId);
10055
10056        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10057            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10058            return false;
10059        }
10060
10061        long callingId = Binder.clearCallingIdentity();
10062        try {
10063            boolean sendAdded = false;
10064            boolean sendRemoved = false;
10065            // writer
10066            synchronized (mPackages) {
10067                pkgSetting = mSettings.mPackages.get(packageName);
10068                if (pkgSetting == null) {
10069                    return false;
10070                }
10071                if (pkgSetting.getHidden(userId) != hidden) {
10072                    pkgSetting.setHidden(hidden, userId);
10073                    mSettings.writePackageRestrictionsLPr(userId);
10074                    if (hidden) {
10075                        sendRemoved = true;
10076                    } else {
10077                        sendAdded = true;
10078                    }
10079                }
10080            }
10081            if (sendAdded) {
10082                sendPackageAddedForUser(packageName, pkgSetting, userId);
10083                return true;
10084            }
10085            if (sendRemoved) {
10086                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10087                        "hiding pkg");
10088                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10089                return true;
10090            }
10091        } finally {
10092            Binder.restoreCallingIdentity(callingId);
10093        }
10094        return false;
10095    }
10096
10097    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10098            int userId) {
10099        final PackageRemovedInfo info = new PackageRemovedInfo();
10100        info.removedPackage = packageName;
10101        info.removedUsers = new int[] {userId};
10102        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10103        info.sendBroadcast(false, false, false);
10104    }
10105
10106    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10107        if (pkgList.length > 0) {
10108            Bundle extras = new Bundle(1);
10109            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10110
10111            sendPackageBroadcast(
10112                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10113                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10114                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10115                    new int[] {userId});
10116        }
10117    }
10118
10119    /**
10120     * Returns true if application is not found or there was an error. Otherwise it returns
10121     * the hidden state of the package for the given user.
10122     */
10123    @Override
10124    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10125        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10126        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10127                false, "getApplicationHidden for user " + userId);
10128        PackageSetting pkgSetting;
10129        long callingId = Binder.clearCallingIdentity();
10130        try {
10131            // writer
10132            synchronized (mPackages) {
10133                pkgSetting = mSettings.mPackages.get(packageName);
10134                if (pkgSetting == null) {
10135                    return true;
10136                }
10137                return pkgSetting.getHidden(userId);
10138            }
10139        } finally {
10140            Binder.restoreCallingIdentity(callingId);
10141        }
10142    }
10143
10144    /**
10145     * @hide
10146     */
10147    @Override
10148    public int installExistingPackageAsUser(String packageName, int userId) {
10149        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10150                null);
10151        PackageSetting pkgSetting;
10152        final int uid = Binder.getCallingUid();
10153        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10154                + userId);
10155        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10156            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10157        }
10158
10159        long callingId = Binder.clearCallingIdentity();
10160        try {
10161            boolean installed = false;
10162
10163            // writer
10164            synchronized (mPackages) {
10165                pkgSetting = mSettings.mPackages.get(packageName);
10166                if (pkgSetting == null) {
10167                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10168                }
10169                if (!pkgSetting.getInstalled(userId)) {
10170                    pkgSetting.setInstalled(true, userId);
10171                    pkgSetting.setHidden(false, userId);
10172                    mSettings.writePackageRestrictionsLPr(userId);
10173                    if (pkgSetting.pkg != null) {
10174                        prepareAppDataAfterInstall(pkgSetting.pkg);
10175                    }
10176                    installed = true;
10177                }
10178            }
10179
10180            if (installed) {
10181                sendPackageAddedForUser(packageName, pkgSetting, userId);
10182            }
10183        } finally {
10184            Binder.restoreCallingIdentity(callingId);
10185        }
10186
10187        return PackageManager.INSTALL_SUCCEEDED;
10188    }
10189
10190    boolean isUserRestricted(int userId, String restrictionKey) {
10191        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10192        if (restrictions.getBoolean(restrictionKey, false)) {
10193            Log.w(TAG, "User is restricted: " + restrictionKey);
10194            return true;
10195        }
10196        return false;
10197    }
10198
10199    @Override
10200    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10201        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10202        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10203                "setPackageSuspended for user " + userId);
10204
10205        // TODO: investigate and add more restrictions for suspending crucial packages.
10206        if (isPackageDeviceAdmin(packageName, userId)) {
10207            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10208                    + "\": has active device admin");
10209            return false;
10210        }
10211
10212        long callingId = Binder.clearCallingIdentity();
10213        try {
10214            boolean changed = false;
10215            boolean success = false;
10216            int appId = -1;
10217            synchronized (mPackages) {
10218                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10219                if (pkgSetting != null) {
10220                    if (pkgSetting.getSuspended(userId) != suspended) {
10221                        pkgSetting.setSuspended(suspended, userId);
10222                        mSettings.writePackageRestrictionsLPr(userId);
10223                        appId = pkgSetting.appId;
10224                        changed = true;
10225                    }
10226                    success = true;
10227                }
10228            }
10229
10230            if (changed) {
10231                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10232                if (suspended) {
10233                    killApplication(packageName, UserHandle.getUid(userId, appId),
10234                            "suspending package");
10235                }
10236            }
10237            return success;
10238        } finally {
10239            Binder.restoreCallingIdentity(callingId);
10240        }
10241    }
10242
10243    @Override
10244    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10245        mContext.enforceCallingOrSelfPermission(
10246                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10247                "Only package verification agents can verify applications");
10248
10249        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10250        final PackageVerificationResponse response = new PackageVerificationResponse(
10251                verificationCode, Binder.getCallingUid());
10252        msg.arg1 = id;
10253        msg.obj = response;
10254        mHandler.sendMessage(msg);
10255    }
10256
10257    @Override
10258    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10259            long millisecondsToDelay) {
10260        mContext.enforceCallingOrSelfPermission(
10261                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10262                "Only package verification agents can extend verification timeouts");
10263
10264        final PackageVerificationState state = mPendingVerification.get(id);
10265        final PackageVerificationResponse response = new PackageVerificationResponse(
10266                verificationCodeAtTimeout, Binder.getCallingUid());
10267
10268        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10269            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10270        }
10271        if (millisecondsToDelay < 0) {
10272            millisecondsToDelay = 0;
10273        }
10274        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10275                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10276            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10277        }
10278
10279        if ((state != null) && !state.timeoutExtended()) {
10280            state.extendTimeout();
10281
10282            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10283            msg.arg1 = id;
10284            msg.obj = response;
10285            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10286        }
10287    }
10288
10289    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10290            int verificationCode, UserHandle user) {
10291        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10292        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10293        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10294        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10295        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10296
10297        mContext.sendBroadcastAsUser(intent, user,
10298                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10299    }
10300
10301    private ComponentName matchComponentForVerifier(String packageName,
10302            List<ResolveInfo> receivers) {
10303        ActivityInfo targetReceiver = null;
10304
10305        final int NR = receivers.size();
10306        for (int i = 0; i < NR; i++) {
10307            final ResolveInfo info = receivers.get(i);
10308            if (info.activityInfo == null) {
10309                continue;
10310            }
10311
10312            if (packageName.equals(info.activityInfo.packageName)) {
10313                targetReceiver = info.activityInfo;
10314                break;
10315            }
10316        }
10317
10318        if (targetReceiver == null) {
10319            return null;
10320        }
10321
10322        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10323    }
10324
10325    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10326            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10327        if (pkgInfo.verifiers.length == 0) {
10328            return null;
10329        }
10330
10331        final int N = pkgInfo.verifiers.length;
10332        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10333        for (int i = 0; i < N; i++) {
10334            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10335
10336            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10337                    receivers);
10338            if (comp == null) {
10339                continue;
10340            }
10341
10342            final int verifierUid = getUidForVerifier(verifierInfo);
10343            if (verifierUid == -1) {
10344                continue;
10345            }
10346
10347            if (DEBUG_VERIFY) {
10348                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10349                        + " with the correct signature");
10350            }
10351            sufficientVerifiers.add(comp);
10352            verificationState.addSufficientVerifier(verifierUid);
10353        }
10354
10355        return sufficientVerifiers;
10356    }
10357
10358    private int getUidForVerifier(VerifierInfo verifierInfo) {
10359        synchronized (mPackages) {
10360            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10361            if (pkg == null) {
10362                return -1;
10363            } else if (pkg.mSignatures.length != 1) {
10364                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10365                        + " has more than one signature; ignoring");
10366                return -1;
10367            }
10368
10369            /*
10370             * If the public key of the package's signature does not match
10371             * our expected public key, then this is a different package and
10372             * we should skip.
10373             */
10374
10375            final byte[] expectedPublicKey;
10376            try {
10377                final Signature verifierSig = pkg.mSignatures[0];
10378                final PublicKey publicKey = verifierSig.getPublicKey();
10379                expectedPublicKey = publicKey.getEncoded();
10380            } catch (CertificateException e) {
10381                return -1;
10382            }
10383
10384            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10385
10386            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10387                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10388                        + " does not have the expected public key; ignoring");
10389                return -1;
10390            }
10391
10392            return pkg.applicationInfo.uid;
10393        }
10394    }
10395
10396    @Override
10397    public void finishPackageInstall(int token) {
10398        enforceSystemOrRoot("Only the system is allowed to finish installs");
10399
10400        if (DEBUG_INSTALL) {
10401            Slog.v(TAG, "BM finishing package install for " + token);
10402        }
10403        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10404
10405        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10406        mHandler.sendMessage(msg);
10407    }
10408
10409    /**
10410     * Get the verification agent timeout.
10411     *
10412     * @return verification timeout in milliseconds
10413     */
10414    private long getVerificationTimeout() {
10415        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10416                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10417                DEFAULT_VERIFICATION_TIMEOUT);
10418    }
10419
10420    /**
10421     * Get the default verification agent response code.
10422     *
10423     * @return default verification response code
10424     */
10425    private int getDefaultVerificationResponse() {
10426        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10427                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10428                DEFAULT_VERIFICATION_RESPONSE);
10429    }
10430
10431    /**
10432     * Check whether or not package verification has been enabled.
10433     *
10434     * @return true if verification should be performed
10435     */
10436    private boolean isVerificationEnabled(int userId, int installFlags) {
10437        if (!DEFAULT_VERIFY_ENABLE) {
10438            return false;
10439        }
10440        // Ephemeral apps don't get the full verification treatment
10441        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10442            if (DEBUG_EPHEMERAL) {
10443                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10444            }
10445            return false;
10446        }
10447
10448        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10449
10450        // Check if installing from ADB
10451        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10452            // Do not run verification in a test harness environment
10453            if (ActivityManager.isRunningInTestHarness()) {
10454                return false;
10455            }
10456            if (ensureVerifyAppsEnabled) {
10457                return true;
10458            }
10459            // Check if the developer does not want package verification for ADB installs
10460            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10461                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10462                return false;
10463            }
10464        }
10465
10466        if (ensureVerifyAppsEnabled) {
10467            return true;
10468        }
10469
10470        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10471                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10472    }
10473
10474    @Override
10475    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10476            throws RemoteException {
10477        mContext.enforceCallingOrSelfPermission(
10478                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10479                "Only intentfilter verification agents can verify applications");
10480
10481        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10482        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10483                Binder.getCallingUid(), verificationCode, failedDomains);
10484        msg.arg1 = id;
10485        msg.obj = response;
10486        mHandler.sendMessage(msg);
10487    }
10488
10489    @Override
10490    public int getIntentVerificationStatus(String packageName, int userId) {
10491        synchronized (mPackages) {
10492            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10493        }
10494    }
10495
10496    @Override
10497    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10498        mContext.enforceCallingOrSelfPermission(
10499                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10500
10501        boolean result = false;
10502        synchronized (mPackages) {
10503            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10504        }
10505        if (result) {
10506            scheduleWritePackageRestrictionsLocked(userId);
10507        }
10508        return result;
10509    }
10510
10511    @Override
10512    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10513        synchronized (mPackages) {
10514            return mSettings.getIntentFilterVerificationsLPr(packageName);
10515        }
10516    }
10517
10518    @Override
10519    public List<IntentFilter> getAllIntentFilters(String packageName) {
10520        if (TextUtils.isEmpty(packageName)) {
10521            return Collections.<IntentFilter>emptyList();
10522        }
10523        synchronized (mPackages) {
10524            PackageParser.Package pkg = mPackages.get(packageName);
10525            if (pkg == null || pkg.activities == null) {
10526                return Collections.<IntentFilter>emptyList();
10527            }
10528            final int count = pkg.activities.size();
10529            ArrayList<IntentFilter> result = new ArrayList<>();
10530            for (int n=0; n<count; n++) {
10531                PackageParser.Activity activity = pkg.activities.get(n);
10532                if (activity.intents != null && activity.intents.size() > 0) {
10533                    result.addAll(activity.intents);
10534                }
10535            }
10536            return result;
10537        }
10538    }
10539
10540    @Override
10541    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10542        mContext.enforceCallingOrSelfPermission(
10543                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10544
10545        synchronized (mPackages) {
10546            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10547            if (packageName != null) {
10548                result |= updateIntentVerificationStatus(packageName,
10549                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10550                        userId);
10551                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10552                        packageName, userId);
10553            }
10554            return result;
10555        }
10556    }
10557
10558    @Override
10559    public String getDefaultBrowserPackageName(int userId) {
10560        synchronized (mPackages) {
10561            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10562        }
10563    }
10564
10565    /**
10566     * Get the "allow unknown sources" setting.
10567     *
10568     * @return the current "allow unknown sources" setting
10569     */
10570    private int getUnknownSourcesSettings() {
10571        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10572                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10573                -1);
10574    }
10575
10576    @Override
10577    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10578        final int uid = Binder.getCallingUid();
10579        // writer
10580        synchronized (mPackages) {
10581            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10582            if (targetPackageSetting == null) {
10583                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10584            }
10585
10586            PackageSetting installerPackageSetting;
10587            if (installerPackageName != null) {
10588                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10589                if (installerPackageSetting == null) {
10590                    throw new IllegalArgumentException("Unknown installer package: "
10591                            + installerPackageName);
10592                }
10593            } else {
10594                installerPackageSetting = null;
10595            }
10596
10597            Signature[] callerSignature;
10598            Object obj = mSettings.getUserIdLPr(uid);
10599            if (obj != null) {
10600                if (obj instanceof SharedUserSetting) {
10601                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10602                } else if (obj instanceof PackageSetting) {
10603                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10604                } else {
10605                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10606                }
10607            } else {
10608                throw new SecurityException("Unknown calling UID: " + uid);
10609            }
10610
10611            // Verify: can't set installerPackageName to a package that is
10612            // not signed with the same cert as the caller.
10613            if (installerPackageSetting != null) {
10614                if (compareSignatures(callerSignature,
10615                        installerPackageSetting.signatures.mSignatures)
10616                        != PackageManager.SIGNATURE_MATCH) {
10617                    throw new SecurityException(
10618                            "Caller does not have same cert as new installer package "
10619                            + installerPackageName);
10620                }
10621            }
10622
10623            // Verify: if target already has an installer package, it must
10624            // be signed with the same cert as the caller.
10625            if (targetPackageSetting.installerPackageName != null) {
10626                PackageSetting setting = mSettings.mPackages.get(
10627                        targetPackageSetting.installerPackageName);
10628                // If the currently set package isn't valid, then it's always
10629                // okay to change it.
10630                if (setting != null) {
10631                    if (compareSignatures(callerSignature,
10632                            setting.signatures.mSignatures)
10633                            != PackageManager.SIGNATURE_MATCH) {
10634                        throw new SecurityException(
10635                                "Caller does not have same cert as old installer package "
10636                                + targetPackageSetting.installerPackageName);
10637                    }
10638                }
10639            }
10640
10641            // Okay!
10642            targetPackageSetting.installerPackageName = installerPackageName;
10643            scheduleWriteSettingsLocked();
10644        }
10645    }
10646
10647    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10648        // Queue up an async operation since the package installation may take a little while.
10649        mHandler.post(new Runnable() {
10650            public void run() {
10651                mHandler.removeCallbacks(this);
10652                 // Result object to be returned
10653                PackageInstalledInfo res = new PackageInstalledInfo();
10654                res.returnCode = currentStatus;
10655                res.uid = -1;
10656                res.pkg = null;
10657                res.removedInfo = new PackageRemovedInfo();
10658                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10659                    args.doPreInstall(res.returnCode);
10660                    synchronized (mInstallLock) {
10661                        installPackageTracedLI(args, res);
10662                    }
10663                    args.doPostInstall(res.returnCode, res.uid);
10664                }
10665
10666                // A restore should be performed at this point if (a) the install
10667                // succeeded, (b) the operation is not an update, and (c) the new
10668                // package has not opted out of backup participation.
10669                final boolean update = res.removedInfo.removedPackage != null;
10670                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10671                boolean doRestore = !update
10672                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10673
10674                // Set up the post-install work request bookkeeping.  This will be used
10675                // and cleaned up by the post-install event handling regardless of whether
10676                // there's a restore pass performed.  Token values are >= 1.
10677                int token;
10678                if (mNextInstallToken < 0) mNextInstallToken = 1;
10679                token = mNextInstallToken++;
10680
10681                PostInstallData data = new PostInstallData(args, res);
10682                mRunningInstalls.put(token, data);
10683                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10684
10685                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10686                    // Pass responsibility to the Backup Manager.  It will perform a
10687                    // restore if appropriate, then pass responsibility back to the
10688                    // Package Manager to run the post-install observer callbacks
10689                    // and broadcasts.
10690                    IBackupManager bm = IBackupManager.Stub.asInterface(
10691                            ServiceManager.getService(Context.BACKUP_SERVICE));
10692                    if (bm != null) {
10693                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10694                                + " to BM for possible restore");
10695                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10696                        try {
10697                            // TODO: http://b/22388012
10698                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10699                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10700                            } else {
10701                                doRestore = false;
10702                            }
10703                        } catch (RemoteException e) {
10704                            // can't happen; the backup manager is local
10705                        } catch (Exception e) {
10706                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10707                            doRestore = false;
10708                        }
10709                    } else {
10710                        Slog.e(TAG, "Backup Manager not found!");
10711                        doRestore = false;
10712                    }
10713                }
10714
10715                if (!doRestore) {
10716                    // No restore possible, or the Backup Manager was mysteriously not
10717                    // available -- just fire the post-install work request directly.
10718                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10719
10720                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10721
10722                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10723                    mHandler.sendMessage(msg);
10724                }
10725            }
10726        });
10727    }
10728
10729    private abstract class HandlerParams {
10730        private static final int MAX_RETRIES = 4;
10731
10732        /**
10733         * Number of times startCopy() has been attempted and had a non-fatal
10734         * error.
10735         */
10736        private int mRetries = 0;
10737
10738        /** User handle for the user requesting the information or installation. */
10739        private final UserHandle mUser;
10740        String traceMethod;
10741        int traceCookie;
10742
10743        HandlerParams(UserHandle user) {
10744            mUser = user;
10745        }
10746
10747        UserHandle getUser() {
10748            return mUser;
10749        }
10750
10751        HandlerParams setTraceMethod(String traceMethod) {
10752            this.traceMethod = traceMethod;
10753            return this;
10754        }
10755
10756        HandlerParams setTraceCookie(int traceCookie) {
10757            this.traceCookie = traceCookie;
10758            return this;
10759        }
10760
10761        final boolean startCopy() {
10762            boolean res;
10763            try {
10764                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10765
10766                if (++mRetries > MAX_RETRIES) {
10767                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10768                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10769                    handleServiceError();
10770                    return false;
10771                } else {
10772                    handleStartCopy();
10773                    res = true;
10774                }
10775            } catch (RemoteException e) {
10776                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10777                mHandler.sendEmptyMessage(MCS_RECONNECT);
10778                res = false;
10779            }
10780            handleReturnCode();
10781            return res;
10782        }
10783
10784        final void serviceError() {
10785            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10786            handleServiceError();
10787            handleReturnCode();
10788        }
10789
10790        abstract void handleStartCopy() throws RemoteException;
10791        abstract void handleServiceError();
10792        abstract void handleReturnCode();
10793    }
10794
10795    class MeasureParams extends HandlerParams {
10796        private final PackageStats mStats;
10797        private boolean mSuccess;
10798
10799        private final IPackageStatsObserver mObserver;
10800
10801        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10802            super(new UserHandle(stats.userHandle));
10803            mObserver = observer;
10804            mStats = stats;
10805        }
10806
10807        @Override
10808        public String toString() {
10809            return "MeasureParams{"
10810                + Integer.toHexString(System.identityHashCode(this))
10811                + " " + mStats.packageName + "}";
10812        }
10813
10814        @Override
10815        void handleStartCopy() throws RemoteException {
10816            synchronized (mInstallLock) {
10817                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10818            }
10819
10820            if (mSuccess) {
10821                final boolean mounted;
10822                if (Environment.isExternalStorageEmulated()) {
10823                    mounted = true;
10824                } else {
10825                    final String status = Environment.getExternalStorageState();
10826                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10827                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10828                }
10829
10830                if (mounted) {
10831                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10832
10833                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10834                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10835
10836                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10837                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10838
10839                    // Always subtract cache size, since it's a subdirectory
10840                    mStats.externalDataSize -= mStats.externalCacheSize;
10841
10842                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10843                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10844
10845                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10846                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10847                }
10848            }
10849        }
10850
10851        @Override
10852        void handleReturnCode() {
10853            if (mObserver != null) {
10854                try {
10855                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10856                } catch (RemoteException e) {
10857                    Slog.i(TAG, "Observer no longer exists.");
10858                }
10859            }
10860        }
10861
10862        @Override
10863        void handleServiceError() {
10864            Slog.e(TAG, "Could not measure application " + mStats.packageName
10865                            + " external storage");
10866        }
10867    }
10868
10869    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10870            throws RemoteException {
10871        long result = 0;
10872        for (File path : paths) {
10873            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10874        }
10875        return result;
10876    }
10877
10878    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10879        for (File path : paths) {
10880            try {
10881                mcs.clearDirectory(path.getAbsolutePath());
10882            } catch (RemoteException e) {
10883            }
10884        }
10885    }
10886
10887    static class OriginInfo {
10888        /**
10889         * Location where install is coming from, before it has been
10890         * copied/renamed into place. This could be a single monolithic APK
10891         * file, or a cluster directory. This location may be untrusted.
10892         */
10893        final File file;
10894        final String cid;
10895
10896        /**
10897         * Flag indicating that {@link #file} or {@link #cid} has already been
10898         * staged, meaning downstream users don't need to defensively copy the
10899         * contents.
10900         */
10901        final boolean staged;
10902
10903        /**
10904         * Flag indicating that {@link #file} or {@link #cid} is an already
10905         * installed app that is being moved.
10906         */
10907        final boolean existing;
10908
10909        final String resolvedPath;
10910        final File resolvedFile;
10911
10912        static OriginInfo fromNothing() {
10913            return new OriginInfo(null, null, false, false);
10914        }
10915
10916        static OriginInfo fromUntrustedFile(File file) {
10917            return new OriginInfo(file, null, false, false);
10918        }
10919
10920        static OriginInfo fromExistingFile(File file) {
10921            return new OriginInfo(file, null, false, true);
10922        }
10923
10924        static OriginInfo fromStagedFile(File file) {
10925            return new OriginInfo(file, null, true, false);
10926        }
10927
10928        static OriginInfo fromStagedContainer(String cid) {
10929            return new OriginInfo(null, cid, true, false);
10930        }
10931
10932        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10933            this.file = file;
10934            this.cid = cid;
10935            this.staged = staged;
10936            this.existing = existing;
10937
10938            if (cid != null) {
10939                resolvedPath = PackageHelper.getSdDir(cid);
10940                resolvedFile = new File(resolvedPath);
10941            } else if (file != null) {
10942                resolvedPath = file.getAbsolutePath();
10943                resolvedFile = file;
10944            } else {
10945                resolvedPath = null;
10946                resolvedFile = null;
10947            }
10948        }
10949    }
10950
10951    static class MoveInfo {
10952        final int moveId;
10953        final String fromUuid;
10954        final String toUuid;
10955        final String packageName;
10956        final String dataAppName;
10957        final int appId;
10958        final String seinfo;
10959        final int targetSdkVersion;
10960
10961        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10962                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
10963            this.moveId = moveId;
10964            this.fromUuid = fromUuid;
10965            this.toUuid = toUuid;
10966            this.packageName = packageName;
10967            this.dataAppName = dataAppName;
10968            this.appId = appId;
10969            this.seinfo = seinfo;
10970            this.targetSdkVersion = targetSdkVersion;
10971        }
10972    }
10973
10974    class InstallParams extends HandlerParams {
10975        final OriginInfo origin;
10976        final MoveInfo move;
10977        final IPackageInstallObserver2 observer;
10978        int installFlags;
10979        final String installerPackageName;
10980        final String volumeUuid;
10981        final VerificationParams verificationParams;
10982        private InstallArgs mArgs;
10983        private int mRet;
10984        final String packageAbiOverride;
10985        final String[] grantedRuntimePermissions;
10986
10987        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10988                int installFlags, String installerPackageName, String volumeUuid,
10989                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10990                String[] grantedPermissions) {
10991            super(user);
10992            this.origin = origin;
10993            this.move = move;
10994            this.observer = observer;
10995            this.installFlags = installFlags;
10996            this.installerPackageName = installerPackageName;
10997            this.volumeUuid = volumeUuid;
10998            this.verificationParams = verificationParams;
10999            this.packageAbiOverride = packageAbiOverride;
11000            this.grantedRuntimePermissions = grantedPermissions;
11001        }
11002
11003        @Override
11004        public String toString() {
11005            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11006                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11007        }
11008
11009        private int installLocationPolicy(PackageInfoLite pkgLite) {
11010            String packageName = pkgLite.packageName;
11011            int installLocation = pkgLite.installLocation;
11012            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11013            // reader
11014            synchronized (mPackages) {
11015                PackageParser.Package pkg = mPackages.get(packageName);
11016                if (pkg != null) {
11017                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11018                        // Check for downgrading.
11019                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11020                            try {
11021                                checkDowngrade(pkg, pkgLite);
11022                            } catch (PackageManagerException e) {
11023                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11024                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11025                            }
11026                        }
11027                        // Check for updated system application.
11028                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11029                            if (onSd) {
11030                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11031                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11032                            }
11033                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11034                        } else {
11035                            if (onSd) {
11036                                // Install flag overrides everything.
11037                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11038                            }
11039                            // If current upgrade specifies particular preference
11040                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11041                                // Application explicitly specified internal.
11042                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11043                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11044                                // App explictly prefers external. Let policy decide
11045                            } else {
11046                                // Prefer previous location
11047                                if (isExternal(pkg)) {
11048                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11049                                }
11050                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11051                            }
11052                        }
11053                    } else {
11054                        // Invalid install. Return error code
11055                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11056                    }
11057                }
11058            }
11059            // All the special cases have been taken care of.
11060            // Return result based on recommended install location.
11061            if (onSd) {
11062                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11063            }
11064            return pkgLite.recommendedInstallLocation;
11065        }
11066
11067        /*
11068         * Invoke remote method to get package information and install
11069         * location values. Override install location based on default
11070         * policy if needed and then create install arguments based
11071         * on the install location.
11072         */
11073        public void handleStartCopy() throws RemoteException {
11074            int ret = PackageManager.INSTALL_SUCCEEDED;
11075
11076            // If we're already staged, we've firmly committed to an install location
11077            if (origin.staged) {
11078                if (origin.file != null) {
11079                    installFlags |= PackageManager.INSTALL_INTERNAL;
11080                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11081                } else if (origin.cid != null) {
11082                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11083                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11084                } else {
11085                    throw new IllegalStateException("Invalid stage location");
11086                }
11087            }
11088
11089            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11090            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11091            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11092            PackageInfoLite pkgLite = null;
11093
11094            if (onInt && onSd) {
11095                // Check if both bits are set.
11096                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11097                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11098            } else if (onSd && ephemeral) {
11099                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11100                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11101            } else {
11102                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11103                        packageAbiOverride);
11104
11105                if (DEBUG_EPHEMERAL && ephemeral) {
11106                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11107                }
11108
11109                /*
11110                 * If we have too little free space, try to free cache
11111                 * before giving up.
11112                 */
11113                if (!origin.staged && pkgLite.recommendedInstallLocation
11114                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11115                    // TODO: focus freeing disk space on the target device
11116                    final StorageManager storage = StorageManager.from(mContext);
11117                    final long lowThreshold = storage.getStorageLowBytes(
11118                            Environment.getDataDirectory());
11119
11120                    final long sizeBytes = mContainerService.calculateInstalledSize(
11121                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11122
11123                    try {
11124                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11125                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11126                                installFlags, packageAbiOverride);
11127                    } catch (InstallerException e) {
11128                        Slog.w(TAG, "Failed to free cache", e);
11129                    }
11130
11131                    /*
11132                     * The cache free must have deleted the file we
11133                     * downloaded to install.
11134                     *
11135                     * TODO: fix the "freeCache" call to not delete
11136                     *       the file we care about.
11137                     */
11138                    if (pkgLite.recommendedInstallLocation
11139                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11140                        pkgLite.recommendedInstallLocation
11141                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11142                    }
11143                }
11144            }
11145
11146            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11147                int loc = pkgLite.recommendedInstallLocation;
11148                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11149                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11150                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11151                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11152                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11153                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11154                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11155                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11156                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11157                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11158                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11159                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11160                } else {
11161                    // Override with defaults if needed.
11162                    loc = installLocationPolicy(pkgLite);
11163                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11164                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11165                    } else if (!onSd && !onInt) {
11166                        // Override install location with flags
11167                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11168                            // Set the flag to install on external media.
11169                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11170                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11171                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11172                            if (DEBUG_EPHEMERAL) {
11173                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11174                            }
11175                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11176                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11177                                    |PackageManager.INSTALL_INTERNAL);
11178                        } else {
11179                            // Make sure the flag for installing on external
11180                            // media is unset
11181                            installFlags |= PackageManager.INSTALL_INTERNAL;
11182                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11183                        }
11184                    }
11185                }
11186            }
11187
11188            final InstallArgs args = createInstallArgs(this);
11189            mArgs = args;
11190
11191            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11192                // TODO: http://b/22976637
11193                // Apps installed for "all" users use the device owner to verify the app
11194                UserHandle verifierUser = getUser();
11195                if (verifierUser == UserHandle.ALL) {
11196                    verifierUser = UserHandle.SYSTEM;
11197                }
11198
11199                /*
11200                 * Determine if we have any installed package verifiers. If we
11201                 * do, then we'll defer to them to verify the packages.
11202                 */
11203                final int requiredUid = mRequiredVerifierPackage == null ? -1
11204                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11205                                verifierUser.getIdentifier());
11206                if (!origin.existing && requiredUid != -1
11207                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11208                    final Intent verification = new Intent(
11209                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11210                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11211                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11212                            PACKAGE_MIME_TYPE);
11213                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11214
11215                    // Query all live verifiers based on current user state
11216                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11217                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11218
11219                    if (DEBUG_VERIFY) {
11220                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11221                                + verification.toString() + " with " + pkgLite.verifiers.length
11222                                + " optional verifiers");
11223                    }
11224
11225                    final int verificationId = mPendingVerificationToken++;
11226
11227                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11228
11229                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11230                            installerPackageName);
11231
11232                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11233                            installFlags);
11234
11235                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11236                            pkgLite.packageName);
11237
11238                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11239                            pkgLite.versionCode);
11240
11241                    if (verificationParams != null) {
11242                        if (verificationParams.getVerificationURI() != null) {
11243                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11244                                 verificationParams.getVerificationURI());
11245                        }
11246                        if (verificationParams.getOriginatingURI() != null) {
11247                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11248                                  verificationParams.getOriginatingURI());
11249                        }
11250                        if (verificationParams.getReferrer() != null) {
11251                            verification.putExtra(Intent.EXTRA_REFERRER,
11252                                  verificationParams.getReferrer());
11253                        }
11254                        if (verificationParams.getOriginatingUid() >= 0) {
11255                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11256                                  verificationParams.getOriginatingUid());
11257                        }
11258                        if (verificationParams.getInstallerUid() >= 0) {
11259                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11260                                  verificationParams.getInstallerUid());
11261                        }
11262                    }
11263
11264                    final PackageVerificationState verificationState = new PackageVerificationState(
11265                            requiredUid, args);
11266
11267                    mPendingVerification.append(verificationId, verificationState);
11268
11269                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11270                            receivers, verificationState);
11271
11272                    /*
11273                     * If any sufficient verifiers were listed in the package
11274                     * manifest, attempt to ask them.
11275                     */
11276                    if (sufficientVerifiers != null) {
11277                        final int N = sufficientVerifiers.size();
11278                        if (N == 0) {
11279                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11280                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11281                        } else {
11282                            for (int i = 0; i < N; i++) {
11283                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11284
11285                                final Intent sufficientIntent = new Intent(verification);
11286                                sufficientIntent.setComponent(verifierComponent);
11287                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11288                            }
11289                        }
11290                    }
11291
11292                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11293                            mRequiredVerifierPackage, receivers);
11294                    if (ret == PackageManager.INSTALL_SUCCEEDED
11295                            && mRequiredVerifierPackage != null) {
11296                        Trace.asyncTraceBegin(
11297                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11298                        /*
11299                         * Send the intent to the required verification agent,
11300                         * but only start the verification timeout after the
11301                         * target BroadcastReceivers have run.
11302                         */
11303                        verification.setComponent(requiredVerifierComponent);
11304                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11305                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11306                                new BroadcastReceiver() {
11307                                    @Override
11308                                    public void onReceive(Context context, Intent intent) {
11309                                        final Message msg = mHandler
11310                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11311                                        msg.arg1 = verificationId;
11312                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11313                                    }
11314                                }, null, 0, null, null);
11315
11316                        /*
11317                         * We don't want the copy to proceed until verification
11318                         * succeeds, so null out this field.
11319                         */
11320                        mArgs = null;
11321                    }
11322                } else {
11323                    /*
11324                     * No package verification is enabled, so immediately start
11325                     * the remote call to initiate copy using temporary file.
11326                     */
11327                    ret = args.copyApk(mContainerService, true);
11328                }
11329            }
11330
11331            mRet = ret;
11332        }
11333
11334        @Override
11335        void handleReturnCode() {
11336            // If mArgs is null, then MCS couldn't be reached. When it
11337            // reconnects, it will try again to install. At that point, this
11338            // will succeed.
11339            if (mArgs != null) {
11340                processPendingInstall(mArgs, mRet);
11341            }
11342        }
11343
11344        @Override
11345        void handleServiceError() {
11346            mArgs = createInstallArgs(this);
11347            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11348        }
11349
11350        public boolean isForwardLocked() {
11351            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11352        }
11353    }
11354
11355    /**
11356     * Used during creation of InstallArgs
11357     *
11358     * @param installFlags package installation flags
11359     * @return true if should be installed on external storage
11360     */
11361    private static boolean installOnExternalAsec(int installFlags) {
11362        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11363            return false;
11364        }
11365        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11366            return true;
11367        }
11368        return false;
11369    }
11370
11371    /**
11372     * Used during creation of InstallArgs
11373     *
11374     * @param installFlags package installation flags
11375     * @return true if should be installed as forward locked
11376     */
11377    private static boolean installForwardLocked(int installFlags) {
11378        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11379    }
11380
11381    private InstallArgs createInstallArgs(InstallParams params) {
11382        if (params.move != null) {
11383            return new MoveInstallArgs(params);
11384        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11385            return new AsecInstallArgs(params);
11386        } else {
11387            return new FileInstallArgs(params);
11388        }
11389    }
11390
11391    /**
11392     * Create args that describe an existing installed package. Typically used
11393     * when cleaning up old installs, or used as a move source.
11394     */
11395    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11396            String resourcePath, String[] instructionSets) {
11397        final boolean isInAsec;
11398        if (installOnExternalAsec(installFlags)) {
11399            /* Apps on SD card are always in ASEC containers. */
11400            isInAsec = true;
11401        } else if (installForwardLocked(installFlags)
11402                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11403            /*
11404             * Forward-locked apps are only in ASEC containers if they're the
11405             * new style
11406             */
11407            isInAsec = true;
11408        } else {
11409            isInAsec = false;
11410        }
11411
11412        if (isInAsec) {
11413            return new AsecInstallArgs(codePath, instructionSets,
11414                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11415        } else {
11416            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11417        }
11418    }
11419
11420    static abstract class InstallArgs {
11421        /** @see InstallParams#origin */
11422        final OriginInfo origin;
11423        /** @see InstallParams#move */
11424        final MoveInfo move;
11425
11426        final IPackageInstallObserver2 observer;
11427        // Always refers to PackageManager flags only
11428        final int installFlags;
11429        final String installerPackageName;
11430        final String volumeUuid;
11431        final UserHandle user;
11432        final String abiOverride;
11433        final String[] installGrantPermissions;
11434        /** If non-null, drop an async trace when the install completes */
11435        final String traceMethod;
11436        final int traceCookie;
11437
11438        // The list of instruction sets supported by this app. This is currently
11439        // only used during the rmdex() phase to clean up resources. We can get rid of this
11440        // if we move dex files under the common app path.
11441        /* nullable */ String[] instructionSets;
11442
11443        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11444                int installFlags, String installerPackageName, String volumeUuid,
11445                UserHandle user, String[] instructionSets,
11446                String abiOverride, String[] installGrantPermissions,
11447                String traceMethod, int traceCookie) {
11448            this.origin = origin;
11449            this.move = move;
11450            this.installFlags = installFlags;
11451            this.observer = observer;
11452            this.installerPackageName = installerPackageName;
11453            this.volumeUuid = volumeUuid;
11454            this.user = user;
11455            this.instructionSets = instructionSets;
11456            this.abiOverride = abiOverride;
11457            this.installGrantPermissions = installGrantPermissions;
11458            this.traceMethod = traceMethod;
11459            this.traceCookie = traceCookie;
11460        }
11461
11462        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11463        abstract int doPreInstall(int status);
11464
11465        /**
11466         * Rename package into final resting place. All paths on the given
11467         * scanned package should be updated to reflect the rename.
11468         */
11469        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11470        abstract int doPostInstall(int status, int uid);
11471
11472        /** @see PackageSettingBase#codePathString */
11473        abstract String getCodePath();
11474        /** @see PackageSettingBase#resourcePathString */
11475        abstract String getResourcePath();
11476
11477        // Need installer lock especially for dex file removal.
11478        abstract void cleanUpResourcesLI();
11479        abstract boolean doPostDeleteLI(boolean delete);
11480
11481        /**
11482         * Called before the source arguments are copied. This is used mostly
11483         * for MoveParams when it needs to read the source file to put it in the
11484         * destination.
11485         */
11486        int doPreCopy() {
11487            return PackageManager.INSTALL_SUCCEEDED;
11488        }
11489
11490        /**
11491         * Called after the source arguments are copied. This is used mostly for
11492         * MoveParams when it needs to read the source file to put it in the
11493         * destination.
11494         *
11495         * @return
11496         */
11497        int doPostCopy(int uid) {
11498            return PackageManager.INSTALL_SUCCEEDED;
11499        }
11500
11501        protected boolean isFwdLocked() {
11502            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11503        }
11504
11505        protected boolean isExternalAsec() {
11506            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11507        }
11508
11509        protected boolean isEphemeral() {
11510            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11511        }
11512
11513        UserHandle getUser() {
11514            return user;
11515        }
11516    }
11517
11518    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11519        if (!allCodePaths.isEmpty()) {
11520            if (instructionSets == null) {
11521                throw new IllegalStateException("instructionSet == null");
11522            }
11523            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11524            for (String codePath : allCodePaths) {
11525                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11526                    try {
11527                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11528                    } catch (InstallerException ignored) {
11529                    }
11530                }
11531            }
11532        }
11533    }
11534
11535    /**
11536     * Logic to handle installation of non-ASEC applications, including copying
11537     * and renaming logic.
11538     */
11539    class FileInstallArgs extends InstallArgs {
11540        private File codeFile;
11541        private File resourceFile;
11542
11543        // Example topology:
11544        // /data/app/com.example/base.apk
11545        // /data/app/com.example/split_foo.apk
11546        // /data/app/com.example/lib/arm/libfoo.so
11547        // /data/app/com.example/lib/arm64/libfoo.so
11548        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11549
11550        /** New install */
11551        FileInstallArgs(InstallParams params) {
11552            super(params.origin, params.move, params.observer, params.installFlags,
11553                    params.installerPackageName, params.volumeUuid,
11554                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11555                    params.grantedRuntimePermissions,
11556                    params.traceMethod, params.traceCookie);
11557            if (isFwdLocked()) {
11558                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11559            }
11560        }
11561
11562        /** Existing install */
11563        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11564            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11565                    null, null, null, 0);
11566            this.codeFile = (codePath != null) ? new File(codePath) : null;
11567            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11568        }
11569
11570        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11571            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11572            try {
11573                return doCopyApk(imcs, temp);
11574            } finally {
11575                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11576            }
11577        }
11578
11579        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11580            if (origin.staged) {
11581                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11582                codeFile = origin.file;
11583                resourceFile = origin.file;
11584                return PackageManager.INSTALL_SUCCEEDED;
11585            }
11586
11587            try {
11588                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11589                final File tempDir =
11590                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11591                codeFile = tempDir;
11592                resourceFile = tempDir;
11593            } catch (IOException e) {
11594                Slog.w(TAG, "Failed to create copy file: " + e);
11595                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11596            }
11597
11598            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11599                @Override
11600                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11601                    if (!FileUtils.isValidExtFilename(name)) {
11602                        throw new IllegalArgumentException("Invalid filename: " + name);
11603                    }
11604                    try {
11605                        final File file = new File(codeFile, name);
11606                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11607                                O_RDWR | O_CREAT, 0644);
11608                        Os.chmod(file.getAbsolutePath(), 0644);
11609                        return new ParcelFileDescriptor(fd);
11610                    } catch (ErrnoException e) {
11611                        throw new RemoteException("Failed to open: " + e.getMessage());
11612                    }
11613                }
11614            };
11615
11616            int ret = PackageManager.INSTALL_SUCCEEDED;
11617            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11618            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11619                Slog.e(TAG, "Failed to copy package");
11620                return ret;
11621            }
11622
11623            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11624            NativeLibraryHelper.Handle handle = null;
11625            try {
11626                handle = NativeLibraryHelper.Handle.create(codeFile);
11627                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11628                        abiOverride);
11629            } catch (IOException e) {
11630                Slog.e(TAG, "Copying native libraries failed", e);
11631                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11632            } finally {
11633                IoUtils.closeQuietly(handle);
11634            }
11635
11636            return ret;
11637        }
11638
11639        int doPreInstall(int status) {
11640            if (status != PackageManager.INSTALL_SUCCEEDED) {
11641                cleanUp();
11642            }
11643            return status;
11644        }
11645
11646        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11647            if (status != PackageManager.INSTALL_SUCCEEDED) {
11648                cleanUp();
11649                return false;
11650            }
11651
11652            final File targetDir = codeFile.getParentFile();
11653            final File beforeCodeFile = codeFile;
11654            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11655
11656            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11657            try {
11658                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11659            } catch (ErrnoException e) {
11660                Slog.w(TAG, "Failed to rename", e);
11661                return false;
11662            }
11663
11664            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11665                Slog.w(TAG, "Failed to restorecon");
11666                return false;
11667            }
11668
11669            // Reflect the rename internally
11670            codeFile = afterCodeFile;
11671            resourceFile = afterCodeFile;
11672
11673            // Reflect the rename in scanned details
11674            pkg.codePath = afterCodeFile.getAbsolutePath();
11675            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11676                    pkg.baseCodePath);
11677            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11678                    pkg.splitCodePaths);
11679
11680            // Reflect the rename in app info
11681            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11682            pkg.applicationInfo.setCodePath(pkg.codePath);
11683            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11684            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11685            pkg.applicationInfo.setResourcePath(pkg.codePath);
11686            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11687            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11688
11689            return true;
11690        }
11691
11692        int doPostInstall(int status, int uid) {
11693            if (status != PackageManager.INSTALL_SUCCEEDED) {
11694                cleanUp();
11695            }
11696            return status;
11697        }
11698
11699        @Override
11700        String getCodePath() {
11701            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11702        }
11703
11704        @Override
11705        String getResourcePath() {
11706            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11707        }
11708
11709        private boolean cleanUp() {
11710            if (codeFile == null || !codeFile.exists()) {
11711                return false;
11712            }
11713
11714            removeCodePathLI(codeFile);
11715
11716            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11717                resourceFile.delete();
11718            }
11719
11720            return true;
11721        }
11722
11723        void cleanUpResourcesLI() {
11724            // Try enumerating all code paths before deleting
11725            List<String> allCodePaths = Collections.EMPTY_LIST;
11726            if (codeFile != null && codeFile.exists()) {
11727                try {
11728                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11729                    allCodePaths = pkg.getAllCodePaths();
11730                } catch (PackageParserException e) {
11731                    // Ignored; we tried our best
11732                }
11733            }
11734
11735            cleanUp();
11736            removeDexFiles(allCodePaths, instructionSets);
11737        }
11738
11739        boolean doPostDeleteLI(boolean delete) {
11740            // XXX err, shouldn't we respect the delete flag?
11741            cleanUpResourcesLI();
11742            return true;
11743        }
11744    }
11745
11746    private boolean isAsecExternal(String cid) {
11747        final String asecPath = PackageHelper.getSdFilesystem(cid);
11748        return !asecPath.startsWith(mAsecInternalPath);
11749    }
11750
11751    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11752            PackageManagerException {
11753        if (copyRet < 0) {
11754            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11755                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11756                throw new PackageManagerException(copyRet, message);
11757            }
11758        }
11759    }
11760
11761    /**
11762     * Extract the MountService "container ID" from the full code path of an
11763     * .apk.
11764     */
11765    static String cidFromCodePath(String fullCodePath) {
11766        int eidx = fullCodePath.lastIndexOf("/");
11767        String subStr1 = fullCodePath.substring(0, eidx);
11768        int sidx = subStr1.lastIndexOf("/");
11769        return subStr1.substring(sidx+1, eidx);
11770    }
11771
11772    /**
11773     * Logic to handle installation of ASEC applications, including copying and
11774     * renaming logic.
11775     */
11776    class AsecInstallArgs extends InstallArgs {
11777        static final String RES_FILE_NAME = "pkg.apk";
11778        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11779
11780        String cid;
11781        String packagePath;
11782        String resourcePath;
11783
11784        /** New install */
11785        AsecInstallArgs(InstallParams params) {
11786            super(params.origin, params.move, params.observer, params.installFlags,
11787                    params.installerPackageName, params.volumeUuid,
11788                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11789                    params.grantedRuntimePermissions,
11790                    params.traceMethod, params.traceCookie);
11791        }
11792
11793        /** Existing install */
11794        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11795                        boolean isExternal, boolean isForwardLocked) {
11796            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11797                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11798                    instructionSets, null, null, null, 0);
11799            // Hackily pretend we're still looking at a full code path
11800            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11801                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11802            }
11803
11804            // Extract cid from fullCodePath
11805            int eidx = fullCodePath.lastIndexOf("/");
11806            String subStr1 = fullCodePath.substring(0, eidx);
11807            int sidx = subStr1.lastIndexOf("/");
11808            cid = subStr1.substring(sidx+1, eidx);
11809            setMountPath(subStr1);
11810        }
11811
11812        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11813            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11814                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11815                    instructionSets, null, null, null, 0);
11816            this.cid = cid;
11817            setMountPath(PackageHelper.getSdDir(cid));
11818        }
11819
11820        void createCopyFile() {
11821            cid = mInstallerService.allocateExternalStageCidLegacy();
11822        }
11823
11824        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11825            if (origin.staged && origin.cid != null) {
11826                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11827                cid = origin.cid;
11828                setMountPath(PackageHelper.getSdDir(cid));
11829                return PackageManager.INSTALL_SUCCEEDED;
11830            }
11831
11832            if (temp) {
11833                createCopyFile();
11834            } else {
11835                /*
11836                 * Pre-emptively destroy the container since it's destroyed if
11837                 * copying fails due to it existing anyway.
11838                 */
11839                PackageHelper.destroySdDir(cid);
11840            }
11841
11842            final String newMountPath = imcs.copyPackageToContainer(
11843                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11844                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11845
11846            if (newMountPath != null) {
11847                setMountPath(newMountPath);
11848                return PackageManager.INSTALL_SUCCEEDED;
11849            } else {
11850                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11851            }
11852        }
11853
11854        @Override
11855        String getCodePath() {
11856            return packagePath;
11857        }
11858
11859        @Override
11860        String getResourcePath() {
11861            return resourcePath;
11862        }
11863
11864        int doPreInstall(int status) {
11865            if (status != PackageManager.INSTALL_SUCCEEDED) {
11866                // Destroy container
11867                PackageHelper.destroySdDir(cid);
11868            } else {
11869                boolean mounted = PackageHelper.isContainerMounted(cid);
11870                if (!mounted) {
11871                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11872                            Process.SYSTEM_UID);
11873                    if (newMountPath != null) {
11874                        setMountPath(newMountPath);
11875                    } else {
11876                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11877                    }
11878                }
11879            }
11880            return status;
11881        }
11882
11883        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11884            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11885            String newMountPath = null;
11886            if (PackageHelper.isContainerMounted(cid)) {
11887                // Unmount the container
11888                if (!PackageHelper.unMountSdDir(cid)) {
11889                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11890                    return false;
11891                }
11892            }
11893            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11894                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11895                        " which might be stale. Will try to clean up.");
11896                // Clean up the stale container and proceed to recreate.
11897                if (!PackageHelper.destroySdDir(newCacheId)) {
11898                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11899                    return false;
11900                }
11901                // Successfully cleaned up stale container. Try to rename again.
11902                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11903                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11904                            + " inspite of cleaning it up.");
11905                    return false;
11906                }
11907            }
11908            if (!PackageHelper.isContainerMounted(newCacheId)) {
11909                Slog.w(TAG, "Mounting container " + newCacheId);
11910                newMountPath = PackageHelper.mountSdDir(newCacheId,
11911                        getEncryptKey(), Process.SYSTEM_UID);
11912            } else {
11913                newMountPath = PackageHelper.getSdDir(newCacheId);
11914            }
11915            if (newMountPath == null) {
11916                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11917                return false;
11918            }
11919            Log.i(TAG, "Succesfully renamed " + cid +
11920                    " to " + newCacheId +
11921                    " at new path: " + newMountPath);
11922            cid = newCacheId;
11923
11924            final File beforeCodeFile = new File(packagePath);
11925            setMountPath(newMountPath);
11926            final File afterCodeFile = new File(packagePath);
11927
11928            // Reflect the rename in scanned details
11929            pkg.codePath = afterCodeFile.getAbsolutePath();
11930            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11931                    pkg.baseCodePath);
11932            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11933                    pkg.splitCodePaths);
11934
11935            // Reflect the rename in app info
11936            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11937            pkg.applicationInfo.setCodePath(pkg.codePath);
11938            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11939            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11940            pkg.applicationInfo.setResourcePath(pkg.codePath);
11941            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11942            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11943
11944            return true;
11945        }
11946
11947        private void setMountPath(String mountPath) {
11948            final File mountFile = new File(mountPath);
11949
11950            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11951            if (monolithicFile.exists()) {
11952                packagePath = monolithicFile.getAbsolutePath();
11953                if (isFwdLocked()) {
11954                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11955                } else {
11956                    resourcePath = packagePath;
11957                }
11958            } else {
11959                packagePath = mountFile.getAbsolutePath();
11960                resourcePath = packagePath;
11961            }
11962        }
11963
11964        int doPostInstall(int status, int uid) {
11965            if (status != PackageManager.INSTALL_SUCCEEDED) {
11966                cleanUp();
11967            } else {
11968                final int groupOwner;
11969                final String protectedFile;
11970                if (isFwdLocked()) {
11971                    groupOwner = UserHandle.getSharedAppGid(uid);
11972                    protectedFile = RES_FILE_NAME;
11973                } else {
11974                    groupOwner = -1;
11975                    protectedFile = null;
11976                }
11977
11978                if (uid < Process.FIRST_APPLICATION_UID
11979                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11980                    Slog.e(TAG, "Failed to finalize " + cid);
11981                    PackageHelper.destroySdDir(cid);
11982                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11983                }
11984
11985                boolean mounted = PackageHelper.isContainerMounted(cid);
11986                if (!mounted) {
11987                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11988                }
11989            }
11990            return status;
11991        }
11992
11993        private void cleanUp() {
11994            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11995
11996            // Destroy secure container
11997            PackageHelper.destroySdDir(cid);
11998        }
11999
12000        private List<String> getAllCodePaths() {
12001            final File codeFile = new File(getCodePath());
12002            if (codeFile != null && codeFile.exists()) {
12003                try {
12004                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12005                    return pkg.getAllCodePaths();
12006                } catch (PackageParserException e) {
12007                    // Ignored; we tried our best
12008                }
12009            }
12010            return Collections.EMPTY_LIST;
12011        }
12012
12013        void cleanUpResourcesLI() {
12014            // Enumerate all code paths before deleting
12015            cleanUpResourcesLI(getAllCodePaths());
12016        }
12017
12018        private void cleanUpResourcesLI(List<String> allCodePaths) {
12019            cleanUp();
12020            removeDexFiles(allCodePaths, instructionSets);
12021        }
12022
12023        String getPackageName() {
12024            return getAsecPackageName(cid);
12025        }
12026
12027        boolean doPostDeleteLI(boolean delete) {
12028            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12029            final List<String> allCodePaths = getAllCodePaths();
12030            boolean mounted = PackageHelper.isContainerMounted(cid);
12031            if (mounted) {
12032                // Unmount first
12033                if (PackageHelper.unMountSdDir(cid)) {
12034                    mounted = false;
12035                }
12036            }
12037            if (!mounted && delete) {
12038                cleanUpResourcesLI(allCodePaths);
12039            }
12040            return !mounted;
12041        }
12042
12043        @Override
12044        int doPreCopy() {
12045            if (isFwdLocked()) {
12046                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12047                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12048                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12049                }
12050            }
12051
12052            return PackageManager.INSTALL_SUCCEEDED;
12053        }
12054
12055        @Override
12056        int doPostCopy(int uid) {
12057            if (isFwdLocked()) {
12058                if (uid < Process.FIRST_APPLICATION_UID
12059                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12060                                RES_FILE_NAME)) {
12061                    Slog.e(TAG, "Failed to finalize " + cid);
12062                    PackageHelper.destroySdDir(cid);
12063                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12064                }
12065            }
12066
12067            return PackageManager.INSTALL_SUCCEEDED;
12068        }
12069    }
12070
12071    /**
12072     * Logic to handle movement of existing installed applications.
12073     */
12074    class MoveInstallArgs extends InstallArgs {
12075        private File codeFile;
12076        private File resourceFile;
12077
12078        /** New install */
12079        MoveInstallArgs(InstallParams params) {
12080            super(params.origin, params.move, params.observer, params.installFlags,
12081                    params.installerPackageName, params.volumeUuid,
12082                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12083                    params.grantedRuntimePermissions,
12084                    params.traceMethod, params.traceCookie);
12085        }
12086
12087        int copyApk(IMediaContainerService imcs, boolean temp) {
12088            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12089                    + move.fromUuid + " to " + move.toUuid);
12090            synchronized (mInstaller) {
12091                try {
12092                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12093                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12094                } catch (InstallerException e) {
12095                    Slog.w(TAG, "Failed to move app", e);
12096                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12097                }
12098            }
12099
12100            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12101            resourceFile = codeFile;
12102            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12103
12104            return PackageManager.INSTALL_SUCCEEDED;
12105        }
12106
12107        int doPreInstall(int status) {
12108            if (status != PackageManager.INSTALL_SUCCEEDED) {
12109                cleanUp(move.toUuid);
12110            }
12111            return status;
12112        }
12113
12114        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12115            if (status != PackageManager.INSTALL_SUCCEEDED) {
12116                cleanUp(move.toUuid);
12117                return false;
12118            }
12119
12120            // Reflect the move in app info
12121            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12122            pkg.applicationInfo.setCodePath(pkg.codePath);
12123            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12124            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12125            pkg.applicationInfo.setResourcePath(pkg.codePath);
12126            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12127            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12128
12129            return true;
12130        }
12131
12132        int doPostInstall(int status, int uid) {
12133            if (status == PackageManager.INSTALL_SUCCEEDED) {
12134                cleanUp(move.fromUuid);
12135            } else {
12136                cleanUp(move.toUuid);
12137            }
12138            return status;
12139        }
12140
12141        @Override
12142        String getCodePath() {
12143            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12144        }
12145
12146        @Override
12147        String getResourcePath() {
12148            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12149        }
12150
12151        private boolean cleanUp(String volumeUuid) {
12152            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12153                    move.dataAppName);
12154            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12155            synchronized (mInstallLock) {
12156                // Clean up both app data and code
12157                removeDataDirsLI(volumeUuid, move.packageName);
12158                removeCodePathLI(codeFile);
12159            }
12160            return true;
12161        }
12162
12163        void cleanUpResourcesLI() {
12164            throw new UnsupportedOperationException();
12165        }
12166
12167        boolean doPostDeleteLI(boolean delete) {
12168            throw new UnsupportedOperationException();
12169        }
12170    }
12171
12172    static String getAsecPackageName(String packageCid) {
12173        int idx = packageCid.lastIndexOf("-");
12174        if (idx == -1) {
12175            return packageCid;
12176        }
12177        return packageCid.substring(0, idx);
12178    }
12179
12180    // Utility method used to create code paths based on package name and available index.
12181    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12182        String idxStr = "";
12183        int idx = 1;
12184        // Fall back to default value of idx=1 if prefix is not
12185        // part of oldCodePath
12186        if (oldCodePath != null) {
12187            String subStr = oldCodePath;
12188            // Drop the suffix right away
12189            if (suffix != null && subStr.endsWith(suffix)) {
12190                subStr = subStr.substring(0, subStr.length() - suffix.length());
12191            }
12192            // If oldCodePath already contains prefix find out the
12193            // ending index to either increment or decrement.
12194            int sidx = subStr.lastIndexOf(prefix);
12195            if (sidx != -1) {
12196                subStr = subStr.substring(sidx + prefix.length());
12197                if (subStr != null) {
12198                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12199                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12200                    }
12201                    try {
12202                        idx = Integer.parseInt(subStr);
12203                        if (idx <= 1) {
12204                            idx++;
12205                        } else {
12206                            idx--;
12207                        }
12208                    } catch(NumberFormatException e) {
12209                    }
12210                }
12211            }
12212        }
12213        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12214        return prefix + idxStr;
12215    }
12216
12217    private File getNextCodePath(File targetDir, String packageName) {
12218        int suffix = 1;
12219        File result;
12220        do {
12221            result = new File(targetDir, packageName + "-" + suffix);
12222            suffix++;
12223        } while (result.exists());
12224        return result;
12225    }
12226
12227    // Utility method that returns the relative package path with respect
12228    // to the installation directory. Like say for /data/data/com.test-1.apk
12229    // string com.test-1 is returned.
12230    static String deriveCodePathName(String codePath) {
12231        if (codePath == null) {
12232            return null;
12233        }
12234        final File codeFile = new File(codePath);
12235        final String name = codeFile.getName();
12236        if (codeFile.isDirectory()) {
12237            return name;
12238        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12239            final int lastDot = name.lastIndexOf('.');
12240            return name.substring(0, lastDot);
12241        } else {
12242            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12243            return null;
12244        }
12245    }
12246
12247    static class PackageInstalledInfo {
12248        String name;
12249        int uid;
12250        // The set of users that originally had this package installed.
12251        int[] origUsers;
12252        // The set of users that now have this package installed.
12253        int[] newUsers;
12254        PackageParser.Package pkg;
12255        int returnCode;
12256        String returnMsg;
12257        PackageRemovedInfo removedInfo;
12258
12259        public void setError(int code, String msg) {
12260            returnCode = code;
12261            returnMsg = msg;
12262            Slog.w(TAG, msg);
12263        }
12264
12265        public void setError(String msg, PackageParserException e) {
12266            returnCode = e.error;
12267            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12268            Slog.w(TAG, msg, e);
12269        }
12270
12271        public void setError(String msg, PackageManagerException e) {
12272            returnCode = e.error;
12273            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12274            Slog.w(TAG, msg, e);
12275        }
12276
12277        // In some error cases we want to convey more info back to the observer
12278        String origPackage;
12279        String origPermission;
12280    }
12281
12282    /*
12283     * Install a non-existing package.
12284     */
12285    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12286            UserHandle user, String installerPackageName, String volumeUuid,
12287            PackageInstalledInfo res) {
12288        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12289
12290        // Remember this for later, in case we need to rollback this install
12291        String pkgName = pkg.packageName;
12292
12293        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12294        // TODO: b/23350563
12295        final boolean dataDirExists = Environment
12296                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12297
12298        synchronized(mPackages) {
12299            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12300                // A package with the same name is already installed, though
12301                // it has been renamed to an older name.  The package we
12302                // are trying to install should be installed as an update to
12303                // the existing one, but that has not been requested, so bail.
12304                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12305                        + " without first uninstalling package running as "
12306                        + mSettings.mRenamedPackages.get(pkgName));
12307                return;
12308            }
12309            if (mPackages.containsKey(pkgName)) {
12310                // Don't allow installation over an existing package with the same name.
12311                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12312                        + " without first uninstalling.");
12313                return;
12314            }
12315        }
12316
12317        try {
12318            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12319                    System.currentTimeMillis(), user);
12320
12321            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12322            prepareAppDataAfterInstall(newPackage);
12323
12324            // delete the partially installed application. the data directory will have to be
12325            // restored if it was already existing
12326            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12327                // remove package from internal structures.  Note that we want deletePackageX to
12328                // delete the package data and cache directories that it created in
12329                // scanPackageLocked, unless those directories existed before we even tried to
12330                // install.
12331                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12332                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12333                                res.removedInfo, true);
12334            }
12335
12336        } catch (PackageManagerException e) {
12337            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12338        }
12339
12340        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12341    }
12342
12343    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12344        // Can't rotate keys during boot or if sharedUser.
12345        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12346                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12347            return false;
12348        }
12349        // app is using upgradeKeySets; make sure all are valid
12350        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12351        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12352        for (int i = 0; i < upgradeKeySets.length; i++) {
12353            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12354                Slog.wtf(TAG, "Package "
12355                         + (oldPs.name != null ? oldPs.name : "<null>")
12356                         + " contains upgrade-key-set reference to unknown key-set: "
12357                         + upgradeKeySets[i]
12358                         + " reverting to signatures check.");
12359                return false;
12360            }
12361        }
12362        return true;
12363    }
12364
12365    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12366        // Upgrade keysets are being used.  Determine if new package has a superset of the
12367        // required keys.
12368        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12369        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12370        for (int i = 0; i < upgradeKeySets.length; i++) {
12371            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12372            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12373                return true;
12374            }
12375        }
12376        return false;
12377    }
12378
12379    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12380            UserHandle user, String installerPackageName, String volumeUuid,
12381            PackageInstalledInfo res) {
12382        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12383
12384        final PackageParser.Package oldPackage;
12385        final String pkgName = pkg.packageName;
12386        final int[] allUsers;
12387        final boolean[] perUserInstalled;
12388
12389        // First find the old package info and check signatures
12390        synchronized(mPackages) {
12391            oldPackage = mPackages.get(pkgName);
12392            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12393            if (isEphemeral && !oldIsEphemeral) {
12394                // can't downgrade from full to ephemeral
12395                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12396                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12397                return;
12398            }
12399            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12400            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12401            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12402                if(!checkUpgradeKeySetLP(ps, pkg)) {
12403                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12404                            "New package not signed by keys specified by upgrade-keysets: "
12405                            + pkgName);
12406                    return;
12407                }
12408            } else {
12409                // default to original signature matching
12410                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12411                    != PackageManager.SIGNATURE_MATCH) {
12412                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12413                            "New package has a different signature: " + pkgName);
12414                    return;
12415                }
12416            }
12417
12418            // In case of rollback, remember per-user/profile install state
12419            allUsers = sUserManager.getUserIds();
12420            perUserInstalled = new boolean[allUsers.length];
12421            for (int i = 0; i < allUsers.length; i++) {
12422                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12423            }
12424        }
12425
12426        boolean sysPkg = (isSystemApp(oldPackage));
12427        if (sysPkg) {
12428            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12429                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12430        } else {
12431            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12432                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12433        }
12434    }
12435
12436    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12437            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12438            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12439            String volumeUuid, PackageInstalledInfo res) {
12440        String pkgName = deletedPackage.packageName;
12441        boolean deletedPkg = true;
12442        boolean updatedSettings = false;
12443
12444        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12445                + deletedPackage);
12446        long origUpdateTime;
12447        if (pkg.mExtras != null) {
12448            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12449        } else {
12450            origUpdateTime = 0;
12451        }
12452
12453        // First delete the existing package while retaining the data directory
12454        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12455                res.removedInfo, true)) {
12456            // If the existing package wasn't successfully deleted
12457            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12458            deletedPkg = false;
12459        } else {
12460            // Successfully deleted the old package; proceed with replace.
12461
12462            // If deleted package lived in a container, give users a chance to
12463            // relinquish resources before killing.
12464            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12465                if (DEBUG_INSTALL) {
12466                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12467                }
12468                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12469                final ArrayList<String> pkgList = new ArrayList<String>(1);
12470                pkgList.add(deletedPackage.applicationInfo.packageName);
12471                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12472            }
12473
12474            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12475            try {
12476                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12477                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12478                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12479                        perUserInstalled, res, user);
12480                prepareAppDataAfterInstall(newPackage);
12481                updatedSettings = true;
12482            } catch (PackageManagerException e) {
12483                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12484            }
12485        }
12486
12487        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12488            // remove package from internal structures.  Note that we want deletePackageX to
12489            // delete the package data and cache directories that it created in
12490            // scanPackageLocked, unless those directories existed before we even tried to
12491            // install.
12492            if(updatedSettings) {
12493                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12494                deletePackageLI(
12495                        pkgName, null, true, allUsers, perUserInstalled,
12496                        PackageManager.DELETE_KEEP_DATA,
12497                                res.removedInfo, true);
12498            }
12499            // Since we failed to install the new package we need to restore the old
12500            // package that we deleted.
12501            if (deletedPkg) {
12502                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12503                File restoreFile = new File(deletedPackage.codePath);
12504                // Parse old package
12505                boolean oldExternal = isExternal(deletedPackage);
12506                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12507                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12508                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12509                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12510                try {
12511                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12512                            null);
12513                } catch (PackageManagerException e) {
12514                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12515                            + e.getMessage());
12516                    return;
12517                }
12518                // Restore of old package succeeded. Update permissions.
12519                // writer
12520                synchronized (mPackages) {
12521                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12522                            UPDATE_PERMISSIONS_ALL);
12523                    // can downgrade to reader
12524                    mSettings.writeLPr();
12525                }
12526                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12527            }
12528        }
12529    }
12530
12531    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12532            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12533            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12534            String volumeUuid, PackageInstalledInfo res) {
12535        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12536                + ", old=" + deletedPackage);
12537        boolean disabledSystem = false;
12538        boolean updatedSettings = false;
12539        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12540        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12541                != 0) {
12542            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12543        }
12544        String packageName = deletedPackage.packageName;
12545        if (packageName == null) {
12546            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12547                    "Attempt to delete null packageName.");
12548            return;
12549        }
12550        PackageParser.Package oldPkg;
12551        PackageSetting oldPkgSetting;
12552        // reader
12553        synchronized (mPackages) {
12554            oldPkg = mPackages.get(packageName);
12555            oldPkgSetting = mSettings.mPackages.get(packageName);
12556            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12557                    (oldPkgSetting == null)) {
12558                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12559                        "Couldn't find package " + packageName + " information");
12560                return;
12561            }
12562        }
12563
12564        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12565
12566        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12567        res.removedInfo.removedPackage = packageName;
12568        // Remove existing system package
12569        removePackageLI(oldPkgSetting, true);
12570        // writer
12571        synchronized (mPackages) {
12572            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12573            if (!disabledSystem && deletedPackage != null) {
12574                // We didn't need to disable the .apk as a current system package,
12575                // which means we are replacing another update that is already
12576                // installed.  We need to make sure to delete the older one's .apk.
12577                res.removedInfo.args = createInstallArgsForExisting(0,
12578                        deletedPackage.applicationInfo.getCodePath(),
12579                        deletedPackage.applicationInfo.getResourcePath(),
12580                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12581            } else {
12582                res.removedInfo.args = null;
12583            }
12584        }
12585
12586        // Successfully disabled the old package. Now proceed with re-installation
12587        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12588
12589        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12590        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12591
12592        PackageParser.Package newPackage = null;
12593        try {
12594            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12595            if (newPackage.mExtras != null) {
12596                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12597                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12598                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12599
12600                // is the update attempting to change shared user? that isn't going to work...
12601                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12602                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12603                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12604                            + " to " + newPkgSetting.sharedUser);
12605                    updatedSettings = true;
12606                }
12607            }
12608
12609            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12610                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12611                        perUserInstalled, res, user);
12612                prepareAppDataAfterInstall(newPackage);
12613                updatedSettings = true;
12614            }
12615
12616        } catch (PackageManagerException e) {
12617            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12618        }
12619
12620        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12621            // Re installation failed. Restore old information
12622            // Remove new pkg information
12623            if (newPackage != null) {
12624                removeInstalledPackageLI(newPackage, true);
12625            }
12626            // Add back the old system package
12627            try {
12628                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12629            } catch (PackageManagerException e) {
12630                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12631            }
12632            // Restore the old system information in Settings
12633            synchronized (mPackages) {
12634                if (disabledSystem) {
12635                    mSettings.enableSystemPackageLPw(packageName);
12636                }
12637                if (updatedSettings) {
12638                    mSettings.setInstallerPackageName(packageName,
12639                            oldPkgSetting.installerPackageName);
12640                }
12641                mSettings.writeLPr();
12642            }
12643        }
12644    }
12645
12646    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12647        // Collect all used permissions in the UID
12648        ArraySet<String> usedPermissions = new ArraySet<>();
12649        final int packageCount = su.packages.size();
12650        for (int i = 0; i < packageCount; i++) {
12651            PackageSetting ps = su.packages.valueAt(i);
12652            if (ps.pkg == null) {
12653                continue;
12654            }
12655            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12656            for (int j = 0; j < requestedPermCount; j++) {
12657                String permission = ps.pkg.requestedPermissions.get(j);
12658                BasePermission bp = mSettings.mPermissions.get(permission);
12659                if (bp != null) {
12660                    usedPermissions.add(permission);
12661                }
12662            }
12663        }
12664
12665        PermissionsState permissionsState = su.getPermissionsState();
12666        // Prune install permissions
12667        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12668        final int installPermCount = installPermStates.size();
12669        for (int i = installPermCount - 1; i >= 0;  i--) {
12670            PermissionState permissionState = installPermStates.get(i);
12671            if (!usedPermissions.contains(permissionState.getName())) {
12672                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12673                if (bp != null) {
12674                    permissionsState.revokeInstallPermission(bp);
12675                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12676                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12677                }
12678            }
12679        }
12680
12681        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12682
12683        // Prune runtime permissions
12684        for (int userId : allUserIds) {
12685            List<PermissionState> runtimePermStates = permissionsState
12686                    .getRuntimePermissionStates(userId);
12687            final int runtimePermCount = runtimePermStates.size();
12688            for (int i = runtimePermCount - 1; i >= 0; i--) {
12689                PermissionState permissionState = runtimePermStates.get(i);
12690                if (!usedPermissions.contains(permissionState.getName())) {
12691                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12692                    if (bp != null) {
12693                        permissionsState.revokeRuntimePermission(bp, userId);
12694                        permissionsState.updatePermissionFlags(bp, userId,
12695                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12696                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12697                                runtimePermissionChangedUserIds, userId);
12698                    }
12699                }
12700            }
12701        }
12702
12703        return runtimePermissionChangedUserIds;
12704    }
12705
12706    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12707            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12708            UserHandle user) {
12709        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12710
12711        String pkgName = newPackage.packageName;
12712        synchronized (mPackages) {
12713            //write settings. the installStatus will be incomplete at this stage.
12714            //note that the new package setting would have already been
12715            //added to mPackages. It hasn't been persisted yet.
12716            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12717            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12718            mSettings.writeLPr();
12719            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12720        }
12721
12722        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12723        synchronized (mPackages) {
12724            updatePermissionsLPw(newPackage.packageName, newPackage,
12725                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12726                            ? UPDATE_PERMISSIONS_ALL : 0));
12727            // For system-bundled packages, we assume that installing an upgraded version
12728            // of the package implies that the user actually wants to run that new code,
12729            // so we enable the package.
12730            PackageSetting ps = mSettings.mPackages.get(pkgName);
12731            if (ps != null) {
12732                if (isSystemApp(newPackage)) {
12733                    // NB: implicit assumption that system package upgrades apply to all users
12734                    if (DEBUG_INSTALL) {
12735                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12736                    }
12737                    if (res.origUsers != null) {
12738                        for (int userHandle : res.origUsers) {
12739                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12740                                    userHandle, installerPackageName);
12741                        }
12742                    }
12743                    // Also convey the prior install/uninstall state
12744                    if (allUsers != null && perUserInstalled != null) {
12745                        for (int i = 0; i < allUsers.length; i++) {
12746                            if (DEBUG_INSTALL) {
12747                                Slog.d(TAG, "    user " + allUsers[i]
12748                                        + " => " + perUserInstalled[i]);
12749                            }
12750                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12751                        }
12752                        // these install state changes will be persisted in the
12753                        // upcoming call to mSettings.writeLPr().
12754                    }
12755                }
12756                // It's implied that when a user requests installation, they want the app to be
12757                // installed and enabled.
12758                int userId = user.getIdentifier();
12759                if (userId != UserHandle.USER_ALL) {
12760                    ps.setInstalled(true, userId);
12761                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12762                }
12763            }
12764            res.name = pkgName;
12765            res.uid = newPackage.applicationInfo.uid;
12766            res.pkg = newPackage;
12767            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12768            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12769            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12770            //to update install status
12771            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12772            mSettings.writeLPr();
12773            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12774        }
12775
12776        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12777    }
12778
12779    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12780        try {
12781            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12782            installPackageLI(args, res);
12783        } finally {
12784            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12785        }
12786    }
12787
12788    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12789        final int installFlags = args.installFlags;
12790        final String installerPackageName = args.installerPackageName;
12791        final String volumeUuid = args.volumeUuid;
12792        final File tmpPackageFile = new File(args.getCodePath());
12793        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12794        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12795                || (args.volumeUuid != null));
12796        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12797        boolean replace = false;
12798        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12799        if (args.move != null) {
12800            // moving a complete application; perfom an initial scan on the new install location
12801            scanFlags |= SCAN_INITIAL;
12802        }
12803        // Result object to be returned
12804        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12805
12806        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12807
12808        // Sanity check
12809        if (ephemeral && (forwardLocked || onExternal)) {
12810            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12811                    + " external=" + onExternal);
12812            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12813            return;
12814        }
12815
12816        // Retrieve PackageSettings and parse package
12817        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12818                | PackageParser.PARSE_ENFORCE_CODE
12819                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12820                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12821                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12822        PackageParser pp = new PackageParser();
12823        pp.setSeparateProcesses(mSeparateProcesses);
12824        pp.setDisplayMetrics(mMetrics);
12825
12826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12827        final PackageParser.Package pkg;
12828        try {
12829            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12830        } catch (PackageParserException e) {
12831            res.setError("Failed parse during installPackageLI", e);
12832            return;
12833        } finally {
12834            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12835        }
12836
12837        // Mark that we have an install time CPU ABI override.
12838        pkg.cpuAbiOverride = args.abiOverride;
12839
12840        String pkgName = res.name = pkg.packageName;
12841        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12842            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12843                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12844                return;
12845            }
12846        }
12847
12848        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12849        try {
12850            pp.collectCertificates(pkg, parseFlags);
12851        } catch (PackageParserException e) {
12852            res.setError("Failed collect during installPackageLI", e);
12853            return;
12854        } finally {
12855            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12856        }
12857
12858        // Get rid of all references to package scan path via parser.
12859        pp = null;
12860        String oldCodePath = null;
12861        boolean systemApp = false;
12862        synchronized (mPackages) {
12863            // Check if installing already existing package
12864            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12865                String oldName = mSettings.mRenamedPackages.get(pkgName);
12866                if (pkg.mOriginalPackages != null
12867                        && pkg.mOriginalPackages.contains(oldName)
12868                        && mPackages.containsKey(oldName)) {
12869                    // This package is derived from an original package,
12870                    // and this device has been updating from that original
12871                    // name.  We must continue using the original name, so
12872                    // rename the new package here.
12873                    pkg.setPackageName(oldName);
12874                    pkgName = pkg.packageName;
12875                    replace = true;
12876                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12877                            + oldName + " pkgName=" + pkgName);
12878                } else if (mPackages.containsKey(pkgName)) {
12879                    // This package, under its official name, already exists
12880                    // on the device; we should replace it.
12881                    replace = true;
12882                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12883                }
12884
12885                // Prevent apps opting out from runtime permissions
12886                if (replace) {
12887                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12888                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12889                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12890                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12891                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12892                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12893                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12894                                        + " doesn't support runtime permissions but the old"
12895                                        + " target SDK " + oldTargetSdk + " does.");
12896                        return;
12897                    }
12898                }
12899            }
12900
12901            PackageSetting ps = mSettings.mPackages.get(pkgName);
12902            if (ps != null) {
12903                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12904
12905                // Quick sanity check that we're signed correctly if updating;
12906                // we'll check this again later when scanning, but we want to
12907                // bail early here before tripping over redefined permissions.
12908                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12909                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12910                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12911                                + pkg.packageName + " upgrade keys do not match the "
12912                                + "previously installed version");
12913                        return;
12914                    }
12915                } else {
12916                    try {
12917                        verifySignaturesLP(ps, pkg);
12918                    } catch (PackageManagerException e) {
12919                        res.setError(e.error, e.getMessage());
12920                        return;
12921                    }
12922                }
12923
12924                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12925                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12926                    systemApp = (ps.pkg.applicationInfo.flags &
12927                            ApplicationInfo.FLAG_SYSTEM) != 0;
12928                }
12929                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12930            }
12931
12932            // Check whether the newly-scanned package wants to define an already-defined perm
12933            int N = pkg.permissions.size();
12934            for (int i = N-1; i >= 0; i--) {
12935                PackageParser.Permission perm = pkg.permissions.get(i);
12936                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12937                if (bp != null) {
12938                    // If the defining package is signed with our cert, it's okay.  This
12939                    // also includes the "updating the same package" case, of course.
12940                    // "updating same package" could also involve key-rotation.
12941                    final boolean sigsOk;
12942                    if (bp.sourcePackage.equals(pkg.packageName)
12943                            && (bp.packageSetting instanceof PackageSetting)
12944                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12945                                    scanFlags))) {
12946                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12947                    } else {
12948                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12949                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12950                    }
12951                    if (!sigsOk) {
12952                        // If the owning package is the system itself, we log but allow
12953                        // install to proceed; we fail the install on all other permission
12954                        // redefinitions.
12955                        if (!bp.sourcePackage.equals("android")) {
12956                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12957                                    + pkg.packageName + " attempting to redeclare permission "
12958                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12959                            res.origPermission = perm.info.name;
12960                            res.origPackage = bp.sourcePackage;
12961                            return;
12962                        } else {
12963                            Slog.w(TAG, "Package " + pkg.packageName
12964                                    + " attempting to redeclare system permission "
12965                                    + perm.info.name + "; ignoring new declaration");
12966                            pkg.permissions.remove(i);
12967                        }
12968                    }
12969                }
12970            }
12971
12972        }
12973
12974        if (systemApp) {
12975            if (onExternal) {
12976                // Abort update; system app can't be replaced with app on sdcard
12977                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12978                        "Cannot install updates to system apps on sdcard");
12979                return;
12980            } else if (ephemeral) {
12981                // Abort update; system app can't be replaced with an ephemeral app
12982                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12983                        "Cannot update a system app with an ephemeral app");
12984                return;
12985            }
12986        }
12987
12988        if (args.move != null) {
12989            // We did an in-place move, so dex is ready to roll
12990            scanFlags |= SCAN_NO_DEX;
12991            scanFlags |= SCAN_MOVE;
12992
12993            synchronized (mPackages) {
12994                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12995                if (ps == null) {
12996                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12997                            "Missing settings for moved package " + pkgName);
12998                }
12999
13000                // We moved the entire application as-is, so bring over the
13001                // previously derived ABI information.
13002                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13003                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13004            }
13005
13006        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13007            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13008            scanFlags |= SCAN_NO_DEX;
13009
13010            try {
13011                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13012                        true /* extract libs */);
13013            } catch (PackageManagerException pme) {
13014                Slog.e(TAG, "Error deriving application ABI", pme);
13015                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13016                return;
13017            }
13018
13019            // Extract package to save the VM unzipping the APK in memory during
13020            // launch. Only do this if profile-guided compilation is enabled because
13021            // otherwise BackgroundDexOptService will not dexopt the package later.
13022            if (mUseJitProfiles) {
13023                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13024                // Do not run PackageDexOptimizer through the local performDexOpt
13025                // method because `pkg` is not in `mPackages` yet.
13026                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13027                        false /* inclDependencies */, false /* useProfiles */,
13028                        true /* extractOnly */);
13029                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13030                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13031                    String msg = "Extracking package failed for " + pkgName;
13032                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13033                    return;
13034                }
13035            }
13036        }
13037
13038        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13039            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13040            return;
13041        }
13042
13043        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13044
13045        if (replace) {
13046            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13047                    installerPackageName, volumeUuid, res);
13048        } else {
13049            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13050                    args.user, installerPackageName, volumeUuid, res);
13051        }
13052        synchronized (mPackages) {
13053            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13054            if (ps != null) {
13055                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13056            }
13057        }
13058    }
13059
13060    private void startIntentFilterVerifications(int userId, boolean replacing,
13061            PackageParser.Package pkg) {
13062        if (mIntentFilterVerifierComponent == null) {
13063            Slog.w(TAG, "No IntentFilter verification will not be done as "
13064                    + "there is no IntentFilterVerifier available!");
13065            return;
13066        }
13067
13068        final int verifierUid = getPackageUid(
13069                mIntentFilterVerifierComponent.getPackageName(),
13070                MATCH_DEBUG_TRIAGED_MISSING,
13071                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13072
13073        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13074        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13075        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13076        mHandler.sendMessage(msg);
13077    }
13078
13079    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13080            PackageParser.Package pkg) {
13081        int size = pkg.activities.size();
13082        if (size == 0) {
13083            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13084                    "No activity, so no need to verify any IntentFilter!");
13085            return;
13086        }
13087
13088        final boolean hasDomainURLs = hasDomainURLs(pkg);
13089        if (!hasDomainURLs) {
13090            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13091                    "No domain URLs, so no need to verify any IntentFilter!");
13092            return;
13093        }
13094
13095        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13096                + " if any IntentFilter from the " + size
13097                + " Activities needs verification ...");
13098
13099        int count = 0;
13100        final String packageName = pkg.packageName;
13101
13102        synchronized (mPackages) {
13103            // If this is a new install and we see that we've already run verification for this
13104            // package, we have nothing to do: it means the state was restored from backup.
13105            if (!replacing) {
13106                IntentFilterVerificationInfo ivi =
13107                        mSettings.getIntentFilterVerificationLPr(packageName);
13108                if (ivi != null) {
13109                    if (DEBUG_DOMAIN_VERIFICATION) {
13110                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13111                                + ivi.getStatusString());
13112                    }
13113                    return;
13114                }
13115            }
13116
13117            // If any filters need to be verified, then all need to be.
13118            boolean needToVerify = false;
13119            for (PackageParser.Activity a : pkg.activities) {
13120                for (ActivityIntentInfo filter : a.intents) {
13121                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13122                        if (DEBUG_DOMAIN_VERIFICATION) {
13123                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13124                        }
13125                        needToVerify = true;
13126                        break;
13127                    }
13128                }
13129            }
13130
13131            if (needToVerify) {
13132                final int verificationId = mIntentFilterVerificationToken++;
13133                for (PackageParser.Activity a : pkg.activities) {
13134                    for (ActivityIntentInfo filter : a.intents) {
13135                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13136                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13137                                    "Verification needed for IntentFilter:" + filter.toString());
13138                            mIntentFilterVerifier.addOneIntentFilterVerification(
13139                                    verifierUid, userId, verificationId, filter, packageName);
13140                            count++;
13141                        }
13142                    }
13143                }
13144            }
13145        }
13146
13147        if (count > 0) {
13148            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13149                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13150                    +  " for userId:" + userId);
13151            mIntentFilterVerifier.startVerifications(userId);
13152        } else {
13153            if (DEBUG_DOMAIN_VERIFICATION) {
13154                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13155            }
13156        }
13157    }
13158
13159    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13160        final ComponentName cn  = filter.activity.getComponentName();
13161        final String packageName = cn.getPackageName();
13162
13163        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13164                packageName);
13165        if (ivi == null) {
13166            return true;
13167        }
13168        int status = ivi.getStatus();
13169        switch (status) {
13170            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13171            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13172                return true;
13173
13174            default:
13175                // Nothing to do
13176                return false;
13177        }
13178    }
13179
13180    private static boolean isMultiArch(ApplicationInfo info) {
13181        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13182    }
13183
13184    private static boolean isExternal(PackageParser.Package pkg) {
13185        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13186    }
13187
13188    private static boolean isExternal(PackageSetting ps) {
13189        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13190    }
13191
13192    private static boolean isEphemeral(PackageParser.Package pkg) {
13193        return pkg.applicationInfo.isEphemeralApp();
13194    }
13195
13196    private static boolean isEphemeral(PackageSetting ps) {
13197        return ps.pkg != null && isEphemeral(ps.pkg);
13198    }
13199
13200    private static boolean isSystemApp(PackageParser.Package pkg) {
13201        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13202    }
13203
13204    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13205        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13206    }
13207
13208    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13209        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13210    }
13211
13212    private static boolean isSystemApp(PackageSetting ps) {
13213        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13214    }
13215
13216    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13217        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13218    }
13219
13220    private int packageFlagsToInstallFlags(PackageSetting ps) {
13221        int installFlags = 0;
13222        if (isEphemeral(ps)) {
13223            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13224        }
13225        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13226            // This existing package was an external ASEC install when we have
13227            // the external flag without a UUID
13228            installFlags |= PackageManager.INSTALL_EXTERNAL;
13229        }
13230        if (ps.isForwardLocked()) {
13231            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13232        }
13233        return installFlags;
13234    }
13235
13236    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13237        if (isExternal(pkg)) {
13238            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13239                return StorageManager.UUID_PRIMARY_PHYSICAL;
13240            } else {
13241                return pkg.volumeUuid;
13242            }
13243        } else {
13244            return StorageManager.UUID_PRIVATE_INTERNAL;
13245        }
13246    }
13247
13248    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13249        if (isExternal(pkg)) {
13250            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13251                return mSettings.getExternalVersion();
13252            } else {
13253                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13254            }
13255        } else {
13256            return mSettings.getInternalVersion();
13257        }
13258    }
13259
13260    private void deleteTempPackageFiles() {
13261        final FilenameFilter filter = new FilenameFilter() {
13262            public boolean accept(File dir, String name) {
13263                return name.startsWith("vmdl") && name.endsWith(".tmp");
13264            }
13265        };
13266        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13267            file.delete();
13268        }
13269    }
13270
13271    @Override
13272    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13273            int flags) {
13274        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13275                flags);
13276    }
13277
13278    @Override
13279    public void deletePackage(final String packageName,
13280            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13281        mContext.enforceCallingOrSelfPermission(
13282                android.Manifest.permission.DELETE_PACKAGES, null);
13283        Preconditions.checkNotNull(packageName);
13284        Preconditions.checkNotNull(observer);
13285        final int uid = Binder.getCallingUid();
13286        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13287        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13288        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13289            mContext.enforceCallingOrSelfPermission(
13290                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13291                    "deletePackage for user " + userId);
13292        }
13293
13294        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13295            try {
13296                observer.onPackageDeleted(packageName,
13297                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13298            } catch (RemoteException re) {
13299            }
13300            return;
13301        }
13302
13303        for (int currentUserId : users) {
13304            if (getBlockUninstallForUser(packageName, currentUserId)) {
13305                try {
13306                    observer.onPackageDeleted(packageName,
13307                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13308                } catch (RemoteException re) {
13309                }
13310                return;
13311            }
13312        }
13313
13314        if (DEBUG_REMOVE) {
13315            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13316        }
13317        // Queue up an async operation since the package deletion may take a little while.
13318        mHandler.post(new Runnable() {
13319            public void run() {
13320                mHandler.removeCallbacks(this);
13321                final int returnCode = deletePackageX(packageName, userId, flags);
13322                try {
13323                    observer.onPackageDeleted(packageName, returnCode, null);
13324                } catch (RemoteException e) {
13325                    Log.i(TAG, "Observer no longer exists.");
13326                } //end catch
13327            } //end run
13328        });
13329    }
13330
13331    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13332        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13333                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13334        try {
13335            if (dpm != null) {
13336                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13337                        /* callingUserOnly =*/ false);
13338                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13339                        : deviceOwnerComponentName.getPackageName();
13340                // Does the package contains the device owner?
13341                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13342                // this check is probably not needed, since DO should be registered as a device
13343                // admin on some user too. (Original bug for this: b/17657954)
13344                if (packageName.equals(deviceOwnerPackageName)) {
13345                    return true;
13346                }
13347                // Does it contain a device admin for any user?
13348                int[] users;
13349                if (userId == UserHandle.USER_ALL) {
13350                    users = sUserManager.getUserIds();
13351                } else {
13352                    users = new int[]{userId};
13353                }
13354                for (int i = 0; i < users.length; ++i) {
13355                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13356                        return true;
13357                    }
13358                }
13359            }
13360        } catch (RemoteException e) {
13361        }
13362        return false;
13363    }
13364
13365    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13366        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13367    }
13368
13369    /**
13370     *  This method is an internal method that could be get invoked either
13371     *  to delete an installed package or to clean up a failed installation.
13372     *  After deleting an installed package, a broadcast is sent to notify any
13373     *  listeners that the package has been installed. For cleaning up a failed
13374     *  installation, the broadcast is not necessary since the package's
13375     *  installation wouldn't have sent the initial broadcast either
13376     *  The key steps in deleting a package are
13377     *  deleting the package information in internal structures like mPackages,
13378     *  deleting the packages base directories through installd
13379     *  updating mSettings to reflect current status
13380     *  persisting settings for later use
13381     *  sending a broadcast if necessary
13382     */
13383    private int deletePackageX(String packageName, int userId, int flags) {
13384        final PackageRemovedInfo info = new PackageRemovedInfo();
13385        final boolean res;
13386
13387        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13388                ? UserHandle.ALL : new UserHandle(userId);
13389
13390        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13391            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13392            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13393        }
13394
13395        boolean removedForAllUsers = false;
13396        boolean systemUpdate = false;
13397
13398        PackageParser.Package uninstalledPkg;
13399
13400        // for the uninstall-updates case and restricted profiles, remember the per-
13401        // userhandle installed state
13402        int[] allUsers;
13403        boolean[] perUserInstalled;
13404        synchronized (mPackages) {
13405            uninstalledPkg = mPackages.get(packageName);
13406            PackageSetting ps = mSettings.mPackages.get(packageName);
13407            allUsers = sUserManager.getUserIds();
13408            perUserInstalled = new boolean[allUsers.length];
13409            for (int i = 0; i < allUsers.length; i++) {
13410                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13411            }
13412        }
13413
13414        synchronized (mInstallLock) {
13415            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13416            res = deletePackageLI(packageName, removeForUser,
13417                    true, allUsers, perUserInstalled,
13418                    flags | REMOVE_CHATTY, info, true);
13419            systemUpdate = info.isRemovedPackageSystemUpdate;
13420            synchronized (mPackages) {
13421                if (res) {
13422                    if (!systemUpdate && mPackages.get(packageName) == null) {
13423                        removedForAllUsers = true;
13424                    }
13425                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13426                }
13427            }
13428            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13429                    + " removedForAllUsers=" + removedForAllUsers);
13430        }
13431
13432        if (res) {
13433            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13434
13435            // If the removed package was a system update, the old system package
13436            // was re-enabled; we need to broadcast this information
13437            if (systemUpdate) {
13438                Bundle extras = new Bundle(1);
13439                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13440                        ? info.removedAppId : info.uid);
13441                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13442
13443                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13444                        extras, 0, null, null, null);
13445                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13446                        extras, 0, null, null, null);
13447                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13448                        null, 0, packageName, null, null);
13449            }
13450        }
13451        // Force a gc here.
13452        Runtime.getRuntime().gc();
13453        // Delete the resources here after sending the broadcast to let
13454        // other processes clean up before deleting resources.
13455        if (info.args != null) {
13456            synchronized (mInstallLock) {
13457                info.args.doPostDeleteLI(true);
13458            }
13459        }
13460
13461        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13462    }
13463
13464    class PackageRemovedInfo {
13465        String removedPackage;
13466        int uid = -1;
13467        int removedAppId = -1;
13468        int[] removedUsers = null;
13469        boolean isRemovedPackageSystemUpdate = false;
13470        // Clean up resources deleted packages.
13471        InstallArgs args = null;
13472
13473        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13474            Bundle extras = new Bundle(1);
13475            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13476            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13477            if (replacing) {
13478                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13479            }
13480            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13481            if (removedPackage != null) {
13482                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13483                        extras, 0, null, null, removedUsers);
13484                if (fullRemove && !replacing) {
13485                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13486                            extras, 0, null, null, removedUsers);
13487                }
13488            }
13489            if (removedAppId >= 0) {
13490                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13491                        removedUsers);
13492            }
13493        }
13494    }
13495
13496    /*
13497     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13498     * flag is not set, the data directory is removed as well.
13499     * make sure this flag is set for partially installed apps. If not its meaningless to
13500     * delete a partially installed application.
13501     */
13502    private void removePackageDataLI(PackageSetting ps,
13503            int[] allUserHandles, boolean[] perUserInstalled,
13504            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13505        String packageName = ps.name;
13506        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13507        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13508        // Retrieve object to delete permissions for shared user later on
13509        final PackageSetting deletedPs;
13510        // reader
13511        synchronized (mPackages) {
13512            deletedPs = mSettings.mPackages.get(packageName);
13513            if (outInfo != null) {
13514                outInfo.removedPackage = packageName;
13515                outInfo.removedUsers = deletedPs != null
13516                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13517                        : null;
13518            }
13519        }
13520        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13521            removeDataDirsLI(ps.volumeUuid, packageName);
13522            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13523        }
13524        // writer
13525        synchronized (mPackages) {
13526            if (deletedPs != null) {
13527                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13528                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13529                    clearDefaultBrowserIfNeeded(packageName);
13530                    if (outInfo != null) {
13531                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13532                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13533                    }
13534                    updatePermissionsLPw(deletedPs.name, null, 0);
13535                    if (deletedPs.sharedUser != null) {
13536                        // Remove permissions associated with package. Since runtime
13537                        // permissions are per user we have to kill the removed package
13538                        // or packages running under the shared user of the removed
13539                        // package if revoking the permissions requested only by the removed
13540                        // package is successful and this causes a change in gids.
13541                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13542                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13543                                    userId);
13544                            if (userIdToKill == UserHandle.USER_ALL
13545                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13546                                // If gids changed for this user, kill all affected packages.
13547                                mHandler.post(new Runnable() {
13548                                    @Override
13549                                    public void run() {
13550                                        // This has to happen with no lock held.
13551                                        killApplication(deletedPs.name, deletedPs.appId,
13552                                                KILL_APP_REASON_GIDS_CHANGED);
13553                                    }
13554                                });
13555                                break;
13556                            }
13557                        }
13558                    }
13559                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13560                }
13561                // make sure to preserve per-user disabled state if this removal was just
13562                // a downgrade of a system app to the factory package
13563                if (allUserHandles != null && perUserInstalled != null) {
13564                    if (DEBUG_REMOVE) {
13565                        Slog.d(TAG, "Propagating install state across downgrade");
13566                    }
13567                    for (int i = 0; i < allUserHandles.length; i++) {
13568                        if (DEBUG_REMOVE) {
13569                            Slog.d(TAG, "    user " + allUserHandles[i]
13570                                    + " => " + perUserInstalled[i]);
13571                        }
13572                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13573                    }
13574                }
13575            }
13576            // can downgrade to reader
13577            if (writeSettings) {
13578                // Save settings now
13579                mSettings.writeLPr();
13580            }
13581        }
13582        if (outInfo != null) {
13583            // A user ID was deleted here. Go through all users and remove it
13584            // from KeyStore.
13585            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13586        }
13587    }
13588
13589    static boolean locationIsPrivileged(File path) {
13590        try {
13591            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13592                    .getCanonicalPath();
13593            return path.getCanonicalPath().startsWith(privilegedAppDir);
13594        } catch (IOException e) {
13595            Slog.e(TAG, "Unable to access code path " + path);
13596        }
13597        return false;
13598    }
13599
13600    /*
13601     * Tries to delete system package.
13602     */
13603    private boolean deleteSystemPackageLI(PackageSetting newPs,
13604            int[] allUserHandles, boolean[] perUserInstalled,
13605            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13606        final boolean applyUserRestrictions
13607                = (allUserHandles != null) && (perUserInstalled != null);
13608        PackageSetting disabledPs = null;
13609        // Confirm if the system package has been updated
13610        // An updated system app can be deleted. This will also have to restore
13611        // the system pkg from system partition
13612        // reader
13613        synchronized (mPackages) {
13614            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13615        }
13616        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13617                + " disabledPs=" + disabledPs);
13618        if (disabledPs == null) {
13619            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13620            return false;
13621        } else if (DEBUG_REMOVE) {
13622            Slog.d(TAG, "Deleting system pkg from data partition");
13623        }
13624        if (DEBUG_REMOVE) {
13625            if (applyUserRestrictions) {
13626                Slog.d(TAG, "Remembering install states:");
13627                for (int i = 0; i < allUserHandles.length; i++) {
13628                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13629                }
13630            }
13631        }
13632        // Delete the updated package
13633        outInfo.isRemovedPackageSystemUpdate = true;
13634        if (disabledPs.versionCode < newPs.versionCode) {
13635            // Delete data for downgrades
13636            flags &= ~PackageManager.DELETE_KEEP_DATA;
13637        } else {
13638            // Preserve data by setting flag
13639            flags |= PackageManager.DELETE_KEEP_DATA;
13640        }
13641        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13642                allUserHandles, perUserInstalled, outInfo, writeSettings);
13643        if (!ret) {
13644            return false;
13645        }
13646        // writer
13647        synchronized (mPackages) {
13648            // Reinstate the old system package
13649            mSettings.enableSystemPackageLPw(newPs.name);
13650            // Remove any native libraries from the upgraded package.
13651            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13652        }
13653        // Install the system package
13654        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13655        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13656        if (locationIsPrivileged(disabledPs.codePath)) {
13657            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13658        }
13659
13660        final PackageParser.Package newPkg;
13661        try {
13662            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13663        } catch (PackageManagerException e) {
13664            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13665            return false;
13666        }
13667
13668        prepareAppDataAfterInstall(newPkg);
13669
13670        // writer
13671        synchronized (mPackages) {
13672            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13673
13674            // Propagate the permissions state as we do not want to drop on the floor
13675            // runtime permissions. The update permissions method below will take
13676            // care of removing obsolete permissions and grant install permissions.
13677            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13678            updatePermissionsLPw(newPkg.packageName, newPkg,
13679                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13680
13681            if (applyUserRestrictions) {
13682                if (DEBUG_REMOVE) {
13683                    Slog.d(TAG, "Propagating install state across reinstall");
13684                }
13685                for (int i = 0; i < allUserHandles.length; i++) {
13686                    if (DEBUG_REMOVE) {
13687                        Slog.d(TAG, "    user " + allUserHandles[i]
13688                                + " => " + perUserInstalled[i]);
13689                    }
13690                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13691
13692                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13693                }
13694                // Regardless of writeSettings we need to ensure that this restriction
13695                // state propagation is persisted
13696                mSettings.writeAllUsersPackageRestrictionsLPr();
13697            }
13698            // can downgrade to reader here
13699            if (writeSettings) {
13700                mSettings.writeLPr();
13701            }
13702        }
13703        return true;
13704    }
13705
13706    private boolean deleteInstalledPackageLI(PackageSetting ps,
13707            boolean deleteCodeAndResources, int flags,
13708            int[] allUserHandles, boolean[] perUserInstalled,
13709            PackageRemovedInfo outInfo, boolean writeSettings) {
13710        if (outInfo != null) {
13711            outInfo.uid = ps.appId;
13712        }
13713
13714        // Delete package data from internal structures and also remove data if flag is set
13715        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13716
13717        // Delete application code and resources
13718        if (deleteCodeAndResources && (outInfo != null)) {
13719            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13720                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13721            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13722        }
13723        return true;
13724    }
13725
13726    @Override
13727    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13728            int userId) {
13729        mContext.enforceCallingOrSelfPermission(
13730                android.Manifest.permission.DELETE_PACKAGES, null);
13731        synchronized (mPackages) {
13732            PackageSetting ps = mSettings.mPackages.get(packageName);
13733            if (ps == null) {
13734                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13735                return false;
13736            }
13737            if (!ps.getInstalled(userId)) {
13738                // Can't block uninstall for an app that is not installed or enabled.
13739                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13740                return false;
13741            }
13742            ps.setBlockUninstall(blockUninstall, userId);
13743            mSettings.writePackageRestrictionsLPr(userId);
13744        }
13745        return true;
13746    }
13747
13748    @Override
13749    public boolean getBlockUninstallForUser(String packageName, int userId) {
13750        synchronized (mPackages) {
13751            PackageSetting ps = mSettings.mPackages.get(packageName);
13752            if (ps == null) {
13753                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13754                return false;
13755            }
13756            return ps.getBlockUninstall(userId);
13757        }
13758    }
13759
13760    @Override
13761    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13762        int callingUid = Binder.getCallingUid();
13763        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13764            throw new SecurityException(
13765                    "setRequiredForSystemUser can only be run by the system or root");
13766        }
13767        synchronized (mPackages) {
13768            PackageSetting ps = mSettings.mPackages.get(packageName);
13769            if (ps == null) {
13770                Log.w(TAG, "Package doesn't exist: " + packageName);
13771                return false;
13772            }
13773            if (systemUserApp) {
13774                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13775            } else {
13776                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13777            }
13778            mSettings.writeLPr();
13779        }
13780        return true;
13781    }
13782
13783    /*
13784     * This method handles package deletion in general
13785     */
13786    private boolean deletePackageLI(String packageName, UserHandle user,
13787            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13788            int flags, PackageRemovedInfo outInfo,
13789            boolean writeSettings) {
13790        if (packageName == null) {
13791            Slog.w(TAG, "Attempt to delete null packageName.");
13792            return false;
13793        }
13794        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13795        PackageSetting ps;
13796        boolean dataOnly = false;
13797        int removeUser = -1;
13798        int appId = -1;
13799        synchronized (mPackages) {
13800            ps = mSettings.mPackages.get(packageName);
13801            if (ps == null) {
13802                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13803                return false;
13804            }
13805            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13806                    && user.getIdentifier() != UserHandle.USER_ALL) {
13807                // The caller is asking that the package only be deleted for a single
13808                // user.  To do this, we just mark its uninstalled state and delete
13809                // its data.  If this is a system app, we only allow this to happen if
13810                // they have set the special DELETE_SYSTEM_APP which requests different
13811                // semantics than normal for uninstalling system apps.
13812                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13813                final int userId = user.getIdentifier();
13814                ps.setUserState(userId,
13815                        COMPONENT_ENABLED_STATE_DEFAULT,
13816                        false, //installed
13817                        true,  //stopped
13818                        true,  //notLaunched
13819                        false, //hidden
13820                        false, //suspended
13821                        null, null, null,
13822                        false, // blockUninstall
13823                        ps.readUserState(userId).domainVerificationStatus, 0);
13824                if (!isSystemApp(ps)) {
13825                    // Do not uninstall the APK if an app should be cached
13826                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13827                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13828                        // Other user still have this package installed, so all
13829                        // we need to do is clear this user's data and save that
13830                        // it is uninstalled.
13831                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13832                        removeUser = user.getIdentifier();
13833                        appId = ps.appId;
13834                        scheduleWritePackageRestrictionsLocked(removeUser);
13835                    } else {
13836                        // We need to set it back to 'installed' so the uninstall
13837                        // broadcasts will be sent correctly.
13838                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13839                        ps.setInstalled(true, user.getIdentifier());
13840                    }
13841                } else {
13842                    // This is a system app, so we assume that the
13843                    // other users still have this package installed, so all
13844                    // we need to do is clear this user's data and save that
13845                    // it is uninstalled.
13846                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13847                    removeUser = user.getIdentifier();
13848                    appId = ps.appId;
13849                    scheduleWritePackageRestrictionsLocked(removeUser);
13850                }
13851            }
13852        }
13853
13854        if (removeUser >= 0) {
13855            // From above, we determined that we are deleting this only
13856            // for a single user.  Continue the work here.
13857            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13858            if (outInfo != null) {
13859                outInfo.removedPackage = packageName;
13860                outInfo.removedAppId = appId;
13861                outInfo.removedUsers = new int[] {removeUser};
13862            }
13863            // TODO: triage flags as part of 26466827
13864            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13865            try {
13866                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13867            } catch (InstallerException e) {
13868                Slog.w(TAG, "Failed to delete app data", e);
13869            }
13870            removeKeystoreDataIfNeeded(removeUser, appId);
13871            schedulePackageCleaning(packageName, removeUser, false);
13872            synchronized (mPackages) {
13873                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13874                    scheduleWritePackageRestrictionsLocked(removeUser);
13875                }
13876                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13877            }
13878            return true;
13879        }
13880
13881        if (dataOnly) {
13882            // Delete application data first
13883            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13884            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13885            return true;
13886        }
13887
13888        boolean ret = false;
13889        if (isSystemApp(ps)) {
13890            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13891            // When an updated system application is deleted we delete the existing resources as well and
13892            // fall back to existing code in system partition
13893            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13894                    flags, outInfo, writeSettings);
13895        } else {
13896            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13897            // Kill application pre-emptively especially for apps on sd.
13898            killApplication(packageName, ps.appId, "uninstall pkg");
13899            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13900                    allUserHandles, perUserInstalled,
13901                    outInfo, writeSettings);
13902        }
13903
13904        return ret;
13905    }
13906
13907    private final static class ClearStorageConnection implements ServiceConnection {
13908        IMediaContainerService mContainerService;
13909
13910        @Override
13911        public void onServiceConnected(ComponentName name, IBinder service) {
13912            synchronized (this) {
13913                mContainerService = IMediaContainerService.Stub.asInterface(service);
13914                notifyAll();
13915            }
13916        }
13917
13918        @Override
13919        public void onServiceDisconnected(ComponentName name) {
13920        }
13921    }
13922
13923    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13924        final boolean mounted;
13925        if (Environment.isExternalStorageEmulated()) {
13926            mounted = true;
13927        } else {
13928            final String status = Environment.getExternalStorageState();
13929
13930            mounted = status.equals(Environment.MEDIA_MOUNTED)
13931                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13932        }
13933
13934        if (!mounted) {
13935            return;
13936        }
13937
13938        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13939        int[] users;
13940        if (userId == UserHandle.USER_ALL) {
13941            users = sUserManager.getUserIds();
13942        } else {
13943            users = new int[] { userId };
13944        }
13945        final ClearStorageConnection conn = new ClearStorageConnection();
13946        if (mContext.bindServiceAsUser(
13947                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13948            try {
13949                for (int curUser : users) {
13950                    long timeout = SystemClock.uptimeMillis() + 5000;
13951                    synchronized (conn) {
13952                        long now = SystemClock.uptimeMillis();
13953                        while (conn.mContainerService == null && now < timeout) {
13954                            try {
13955                                conn.wait(timeout - now);
13956                            } catch (InterruptedException e) {
13957                            }
13958                        }
13959                    }
13960                    if (conn.mContainerService == null) {
13961                        return;
13962                    }
13963
13964                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13965                    clearDirectory(conn.mContainerService,
13966                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13967                    if (allData) {
13968                        clearDirectory(conn.mContainerService,
13969                                userEnv.buildExternalStorageAppDataDirs(packageName));
13970                        clearDirectory(conn.mContainerService,
13971                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13972                    }
13973                }
13974            } finally {
13975                mContext.unbindService(conn);
13976            }
13977        }
13978    }
13979
13980    @Override
13981    public void clearApplicationUserData(final String packageName,
13982            final IPackageDataObserver observer, final int userId) {
13983        mContext.enforceCallingOrSelfPermission(
13984                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13985        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13986        // Queue up an async operation since the package deletion may take a little while.
13987        mHandler.post(new Runnable() {
13988            public void run() {
13989                mHandler.removeCallbacks(this);
13990                final boolean succeeded;
13991                synchronized (mInstallLock) {
13992                    succeeded = clearApplicationUserDataLI(packageName, userId);
13993                }
13994                clearExternalStorageDataSync(packageName, userId, true);
13995                if (succeeded) {
13996                    // invoke DeviceStorageMonitor's update method to clear any notifications
13997                    DeviceStorageMonitorInternal
13998                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13999                    if (dsm != null) {
14000                        dsm.checkMemory();
14001                    }
14002                }
14003                if(observer != null) {
14004                    try {
14005                        observer.onRemoveCompleted(packageName, succeeded);
14006                    } catch (RemoteException e) {
14007                        Log.i(TAG, "Observer no longer exists.");
14008                    }
14009                } //end if observer
14010            } //end run
14011        });
14012    }
14013
14014    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14015        if (packageName == null) {
14016            Slog.w(TAG, "Attempt to delete null packageName.");
14017            return false;
14018        }
14019
14020        // Try finding details about the requested package
14021        PackageParser.Package pkg;
14022        synchronized (mPackages) {
14023            pkg = mPackages.get(packageName);
14024            if (pkg == null) {
14025                final PackageSetting ps = mSettings.mPackages.get(packageName);
14026                if (ps != null) {
14027                    pkg = ps.pkg;
14028                }
14029            }
14030
14031            if (pkg == null) {
14032                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14033                return false;
14034            }
14035
14036            PackageSetting ps = (PackageSetting) pkg.mExtras;
14037            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14038        }
14039
14040        // Always delete data directories for package, even if we found no other
14041        // record of app. This helps users recover from UID mismatches without
14042        // resorting to a full data wipe.
14043        // TODO: triage flags as part of 26466827
14044        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14045        try {
14046            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14047        } catch (InstallerException e) {
14048            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14049            return false;
14050        }
14051
14052        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14053        removeKeystoreDataIfNeeded(userId, appId);
14054
14055        // Create a native library symlink only if we have native libraries
14056        // and if the native libraries are 32 bit libraries. We do not provide
14057        // this symlink for 64 bit libraries.
14058        if (pkg.applicationInfo.primaryCpuAbi != null &&
14059                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14060            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14061            try {
14062                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14063                        nativeLibPath, userId);
14064            } catch (InstallerException e) {
14065                Slog.w(TAG, "Failed linking native library dir", e);
14066                return false;
14067            }
14068        }
14069
14070        return true;
14071    }
14072
14073    /**
14074     * Reverts user permission state changes (permissions and flags) in
14075     * all packages for a given user.
14076     *
14077     * @param userId The device user for which to do a reset.
14078     */
14079    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14080        final int packageCount = mPackages.size();
14081        for (int i = 0; i < packageCount; i++) {
14082            PackageParser.Package pkg = mPackages.valueAt(i);
14083            PackageSetting ps = (PackageSetting) pkg.mExtras;
14084            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14085        }
14086    }
14087
14088    /**
14089     * Reverts user permission state changes (permissions and flags).
14090     *
14091     * @param ps The package for which to reset.
14092     * @param userId The device user for which to do a reset.
14093     */
14094    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14095            final PackageSetting ps, final int userId) {
14096        if (ps.pkg == null) {
14097            return;
14098        }
14099
14100        // These are flags that can change base on user actions.
14101        final int userSettableMask = FLAG_PERMISSION_USER_SET
14102                | FLAG_PERMISSION_USER_FIXED
14103                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14104                | FLAG_PERMISSION_REVIEW_REQUIRED;
14105
14106        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14107                | FLAG_PERMISSION_POLICY_FIXED;
14108
14109        boolean writeInstallPermissions = false;
14110        boolean writeRuntimePermissions = false;
14111
14112        final int permissionCount = ps.pkg.requestedPermissions.size();
14113        for (int i = 0; i < permissionCount; i++) {
14114            String permission = ps.pkg.requestedPermissions.get(i);
14115
14116            BasePermission bp = mSettings.mPermissions.get(permission);
14117            if (bp == null) {
14118                continue;
14119            }
14120
14121            // If shared user we just reset the state to which only this app contributed.
14122            if (ps.sharedUser != null) {
14123                boolean used = false;
14124                final int packageCount = ps.sharedUser.packages.size();
14125                for (int j = 0; j < packageCount; j++) {
14126                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14127                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14128                            && pkg.pkg.requestedPermissions.contains(permission)) {
14129                        used = true;
14130                        break;
14131                    }
14132                }
14133                if (used) {
14134                    continue;
14135                }
14136            }
14137
14138            PermissionsState permissionsState = ps.getPermissionsState();
14139
14140            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14141
14142            // Always clear the user settable flags.
14143            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14144                    bp.name) != null;
14145            // If permission review is enabled and this is a legacy app, mark the
14146            // permission as requiring a review as this is the initial state.
14147            int flags = 0;
14148            if (Build.PERMISSIONS_REVIEW_REQUIRED
14149                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14150                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14151            }
14152            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14153                if (hasInstallState) {
14154                    writeInstallPermissions = true;
14155                } else {
14156                    writeRuntimePermissions = true;
14157                }
14158            }
14159
14160            // Below is only runtime permission handling.
14161            if (!bp.isRuntime()) {
14162                continue;
14163            }
14164
14165            // Never clobber system or policy.
14166            if ((oldFlags & policyOrSystemFlags) != 0) {
14167                continue;
14168            }
14169
14170            // If this permission was granted by default, make sure it is.
14171            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14172                if (permissionsState.grantRuntimePermission(bp, userId)
14173                        != PERMISSION_OPERATION_FAILURE) {
14174                    writeRuntimePermissions = true;
14175                }
14176            // If permission review is enabled the permissions for a legacy apps
14177            // are represented as constantly granted runtime ones, so don't revoke.
14178            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14179                // Otherwise, reset the permission.
14180                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14181                switch (revokeResult) {
14182                    case PERMISSION_OPERATION_SUCCESS: {
14183                        writeRuntimePermissions = true;
14184                    } break;
14185
14186                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14187                        writeRuntimePermissions = true;
14188                        final int appId = ps.appId;
14189                        mHandler.post(new Runnable() {
14190                            @Override
14191                            public void run() {
14192                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14193                            }
14194                        });
14195                    } break;
14196                }
14197            }
14198        }
14199
14200        // Synchronously write as we are taking permissions away.
14201        if (writeRuntimePermissions) {
14202            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14203        }
14204
14205        // Synchronously write as we are taking permissions away.
14206        if (writeInstallPermissions) {
14207            mSettings.writeLPr();
14208        }
14209    }
14210
14211    /**
14212     * Remove entries from the keystore daemon. Will only remove it if the
14213     * {@code appId} is valid.
14214     */
14215    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14216        if (appId < 0) {
14217            return;
14218        }
14219
14220        final KeyStore keyStore = KeyStore.getInstance();
14221        if (keyStore != null) {
14222            if (userId == UserHandle.USER_ALL) {
14223                for (final int individual : sUserManager.getUserIds()) {
14224                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14225                }
14226            } else {
14227                keyStore.clearUid(UserHandle.getUid(userId, appId));
14228            }
14229        } else {
14230            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14231        }
14232    }
14233
14234    @Override
14235    public void deleteApplicationCacheFiles(final String packageName,
14236            final IPackageDataObserver observer) {
14237        mContext.enforceCallingOrSelfPermission(
14238                android.Manifest.permission.DELETE_CACHE_FILES, null);
14239        // Queue up an async operation since the package deletion may take a little while.
14240        final int userId = UserHandle.getCallingUserId();
14241        mHandler.post(new Runnable() {
14242            public void run() {
14243                mHandler.removeCallbacks(this);
14244                final boolean succeded;
14245                synchronized (mInstallLock) {
14246                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14247                }
14248                clearExternalStorageDataSync(packageName, userId, false);
14249                if (observer != null) {
14250                    try {
14251                        observer.onRemoveCompleted(packageName, succeded);
14252                    } catch (RemoteException e) {
14253                        Log.i(TAG, "Observer no longer exists.");
14254                    }
14255                } //end if observer
14256            } //end run
14257        });
14258    }
14259
14260    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14261        if (packageName == null) {
14262            Slog.w(TAG, "Attempt to delete null packageName.");
14263            return false;
14264        }
14265        PackageParser.Package p;
14266        synchronized (mPackages) {
14267            p = mPackages.get(packageName);
14268        }
14269        if (p == null) {
14270            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14271            return false;
14272        }
14273        final ApplicationInfo applicationInfo = p.applicationInfo;
14274        if (applicationInfo == null) {
14275            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14276            return false;
14277        }
14278        // TODO: triage flags as part of 26466827
14279        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14280        try {
14281            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14282                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14283        } catch (InstallerException e) {
14284            Slog.w(TAG, "Couldn't remove cache files for package "
14285                    + packageName + " u" + userId, e);
14286            return false;
14287        }
14288        return true;
14289    }
14290
14291    @Override
14292    public void getPackageSizeInfo(final String packageName, int userHandle,
14293            final IPackageStatsObserver observer) {
14294        mContext.enforceCallingOrSelfPermission(
14295                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14296        if (packageName == null) {
14297            throw new IllegalArgumentException("Attempt to get size of null packageName");
14298        }
14299
14300        PackageStats stats = new PackageStats(packageName, userHandle);
14301
14302        /*
14303         * Queue up an async operation since the package measurement may take a
14304         * little while.
14305         */
14306        Message msg = mHandler.obtainMessage(INIT_COPY);
14307        msg.obj = new MeasureParams(stats, observer);
14308        mHandler.sendMessage(msg);
14309    }
14310
14311    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14312            PackageStats pStats) {
14313        if (packageName == null) {
14314            Slog.w(TAG, "Attempt to get size of null packageName.");
14315            return false;
14316        }
14317        PackageParser.Package p;
14318        boolean dataOnly = false;
14319        String libDirRoot = null;
14320        String asecPath = null;
14321        PackageSetting ps = null;
14322        synchronized (mPackages) {
14323            p = mPackages.get(packageName);
14324            ps = mSettings.mPackages.get(packageName);
14325            if(p == null) {
14326                dataOnly = true;
14327                if((ps == null) || (ps.pkg == null)) {
14328                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14329                    return false;
14330                }
14331                p = ps.pkg;
14332            }
14333            if (ps != null) {
14334                libDirRoot = ps.legacyNativeLibraryPathString;
14335            }
14336            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14337                final long token = Binder.clearCallingIdentity();
14338                try {
14339                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14340                    if (secureContainerId != null) {
14341                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14342                    }
14343                } finally {
14344                    Binder.restoreCallingIdentity(token);
14345                }
14346            }
14347        }
14348        String publicSrcDir = null;
14349        if(!dataOnly) {
14350            final ApplicationInfo applicationInfo = p.applicationInfo;
14351            if (applicationInfo == null) {
14352                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14353                return false;
14354            }
14355            if (p.isForwardLocked()) {
14356                publicSrcDir = applicationInfo.getBaseResourcePath();
14357            }
14358        }
14359        // TODO: extend to measure size of split APKs
14360        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14361        // not just the first level.
14362        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14363        // just the primary.
14364        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14365
14366        String apkPath;
14367        File packageDir = new File(p.codePath);
14368
14369        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14370            apkPath = packageDir.getAbsolutePath();
14371            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14372            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14373                libDirRoot = null;
14374            }
14375        } else {
14376            apkPath = p.baseCodePath;
14377        }
14378
14379        // TODO: triage flags as part of 26466827
14380        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14381        try {
14382            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14383                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14384        } catch (InstallerException e) {
14385            return false;
14386        }
14387
14388        // Fix-up for forward-locked applications in ASEC containers.
14389        if (!isExternal(p)) {
14390            pStats.codeSize += pStats.externalCodeSize;
14391            pStats.externalCodeSize = 0L;
14392        }
14393
14394        return true;
14395    }
14396
14397
14398    @Override
14399    public void addPackageToPreferred(String packageName) {
14400        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14401    }
14402
14403    @Override
14404    public void removePackageFromPreferred(String packageName) {
14405        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14406    }
14407
14408    @Override
14409    public List<PackageInfo> getPreferredPackages(int flags) {
14410        return new ArrayList<PackageInfo>();
14411    }
14412
14413    private int getUidTargetSdkVersionLockedLPr(int uid) {
14414        Object obj = mSettings.getUserIdLPr(uid);
14415        if (obj instanceof SharedUserSetting) {
14416            final SharedUserSetting sus = (SharedUserSetting) obj;
14417            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14418            final Iterator<PackageSetting> it = sus.packages.iterator();
14419            while (it.hasNext()) {
14420                final PackageSetting ps = it.next();
14421                if (ps.pkg != null) {
14422                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14423                    if (v < vers) vers = v;
14424                }
14425            }
14426            return vers;
14427        } else if (obj instanceof PackageSetting) {
14428            final PackageSetting ps = (PackageSetting) obj;
14429            if (ps.pkg != null) {
14430                return ps.pkg.applicationInfo.targetSdkVersion;
14431            }
14432        }
14433        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14434    }
14435
14436    @Override
14437    public void addPreferredActivity(IntentFilter filter, int match,
14438            ComponentName[] set, ComponentName activity, int userId) {
14439        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14440                "Adding preferred");
14441    }
14442
14443    private void addPreferredActivityInternal(IntentFilter filter, int match,
14444            ComponentName[] set, ComponentName activity, boolean always, int userId,
14445            String opname) {
14446        // writer
14447        int callingUid = Binder.getCallingUid();
14448        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14449        if (filter.countActions() == 0) {
14450            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14451            return;
14452        }
14453        synchronized (mPackages) {
14454            if (mContext.checkCallingOrSelfPermission(
14455                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14456                    != PackageManager.PERMISSION_GRANTED) {
14457                if (getUidTargetSdkVersionLockedLPr(callingUid)
14458                        < Build.VERSION_CODES.FROYO) {
14459                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14460                            + callingUid);
14461                    return;
14462                }
14463                mContext.enforceCallingOrSelfPermission(
14464                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14465            }
14466
14467            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14468            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14469                    + userId + ":");
14470            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14471            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14472            scheduleWritePackageRestrictionsLocked(userId);
14473        }
14474    }
14475
14476    @Override
14477    public void replacePreferredActivity(IntentFilter filter, int match,
14478            ComponentName[] set, ComponentName activity, int userId) {
14479        if (filter.countActions() != 1) {
14480            throw new IllegalArgumentException(
14481                    "replacePreferredActivity expects filter to have only 1 action.");
14482        }
14483        if (filter.countDataAuthorities() != 0
14484                || filter.countDataPaths() != 0
14485                || filter.countDataSchemes() > 1
14486                || filter.countDataTypes() != 0) {
14487            throw new IllegalArgumentException(
14488                    "replacePreferredActivity expects filter to have no data authorities, " +
14489                    "paths, or types; and at most one scheme.");
14490        }
14491
14492        final int callingUid = Binder.getCallingUid();
14493        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14494        synchronized (mPackages) {
14495            if (mContext.checkCallingOrSelfPermission(
14496                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14497                    != PackageManager.PERMISSION_GRANTED) {
14498                if (getUidTargetSdkVersionLockedLPr(callingUid)
14499                        < Build.VERSION_CODES.FROYO) {
14500                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14501                            + Binder.getCallingUid());
14502                    return;
14503                }
14504                mContext.enforceCallingOrSelfPermission(
14505                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14506            }
14507
14508            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14509            if (pir != null) {
14510                // Get all of the existing entries that exactly match this filter.
14511                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14512                if (existing != null && existing.size() == 1) {
14513                    PreferredActivity cur = existing.get(0);
14514                    if (DEBUG_PREFERRED) {
14515                        Slog.i(TAG, "Checking replace of preferred:");
14516                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14517                        if (!cur.mPref.mAlways) {
14518                            Slog.i(TAG, "  -- CUR; not mAlways!");
14519                        } else {
14520                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14521                            Slog.i(TAG, "  -- CUR: mSet="
14522                                    + Arrays.toString(cur.mPref.mSetComponents));
14523                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14524                            Slog.i(TAG, "  -- NEW: mMatch="
14525                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14526                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14527                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14528                        }
14529                    }
14530                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14531                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14532                            && cur.mPref.sameSet(set)) {
14533                        // Setting the preferred activity to what it happens to be already
14534                        if (DEBUG_PREFERRED) {
14535                            Slog.i(TAG, "Replacing with same preferred activity "
14536                                    + cur.mPref.mShortComponent + " for user "
14537                                    + userId + ":");
14538                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14539                        }
14540                        return;
14541                    }
14542                }
14543
14544                if (existing != null) {
14545                    if (DEBUG_PREFERRED) {
14546                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14547                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14548                    }
14549                    for (int i = 0; i < existing.size(); i++) {
14550                        PreferredActivity pa = existing.get(i);
14551                        if (DEBUG_PREFERRED) {
14552                            Slog.i(TAG, "Removing existing preferred activity "
14553                                    + pa.mPref.mComponent + ":");
14554                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14555                        }
14556                        pir.removeFilter(pa);
14557                    }
14558                }
14559            }
14560            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14561                    "Replacing preferred");
14562        }
14563    }
14564
14565    @Override
14566    public void clearPackagePreferredActivities(String packageName) {
14567        final int uid = Binder.getCallingUid();
14568        // writer
14569        synchronized (mPackages) {
14570            PackageParser.Package pkg = mPackages.get(packageName);
14571            if (pkg == null || pkg.applicationInfo.uid != uid) {
14572                if (mContext.checkCallingOrSelfPermission(
14573                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14574                        != PackageManager.PERMISSION_GRANTED) {
14575                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14576                            < Build.VERSION_CODES.FROYO) {
14577                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14578                                + Binder.getCallingUid());
14579                        return;
14580                    }
14581                    mContext.enforceCallingOrSelfPermission(
14582                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14583                }
14584            }
14585
14586            int user = UserHandle.getCallingUserId();
14587            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14588                scheduleWritePackageRestrictionsLocked(user);
14589            }
14590        }
14591    }
14592
14593    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14594    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14595        ArrayList<PreferredActivity> removed = null;
14596        boolean changed = false;
14597        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14598            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14599            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14600            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14601                continue;
14602            }
14603            Iterator<PreferredActivity> it = pir.filterIterator();
14604            while (it.hasNext()) {
14605                PreferredActivity pa = it.next();
14606                // Mark entry for removal only if it matches the package name
14607                // and the entry is of type "always".
14608                if (packageName == null ||
14609                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14610                                && pa.mPref.mAlways)) {
14611                    if (removed == null) {
14612                        removed = new ArrayList<PreferredActivity>();
14613                    }
14614                    removed.add(pa);
14615                }
14616            }
14617            if (removed != null) {
14618                for (int j=0; j<removed.size(); j++) {
14619                    PreferredActivity pa = removed.get(j);
14620                    pir.removeFilter(pa);
14621                }
14622                changed = true;
14623            }
14624        }
14625        return changed;
14626    }
14627
14628    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14629    private void clearIntentFilterVerificationsLPw(int userId) {
14630        final int packageCount = mPackages.size();
14631        for (int i = 0; i < packageCount; i++) {
14632            PackageParser.Package pkg = mPackages.valueAt(i);
14633            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14634        }
14635    }
14636
14637    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14638    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14639        if (userId == UserHandle.USER_ALL) {
14640            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14641                    sUserManager.getUserIds())) {
14642                for (int oneUserId : sUserManager.getUserIds()) {
14643                    scheduleWritePackageRestrictionsLocked(oneUserId);
14644                }
14645            }
14646        } else {
14647            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14648                scheduleWritePackageRestrictionsLocked(userId);
14649            }
14650        }
14651    }
14652
14653    void clearDefaultBrowserIfNeeded(String packageName) {
14654        for (int oneUserId : sUserManager.getUserIds()) {
14655            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14656            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14657            if (packageName.equals(defaultBrowserPackageName)) {
14658                setDefaultBrowserPackageName(null, oneUserId);
14659            }
14660        }
14661    }
14662
14663    @Override
14664    public void resetApplicationPreferences(int userId) {
14665        mContext.enforceCallingOrSelfPermission(
14666                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14667        // writer
14668        synchronized (mPackages) {
14669            final long identity = Binder.clearCallingIdentity();
14670            try {
14671                clearPackagePreferredActivitiesLPw(null, userId);
14672                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14673                // TODO: We have to reset the default SMS and Phone. This requires
14674                // significant refactoring to keep all default apps in the package
14675                // manager (cleaner but more work) or have the services provide
14676                // callbacks to the package manager to request a default app reset.
14677                applyFactoryDefaultBrowserLPw(userId);
14678                clearIntentFilterVerificationsLPw(userId);
14679                primeDomainVerificationsLPw(userId);
14680                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14681                scheduleWritePackageRestrictionsLocked(userId);
14682            } finally {
14683                Binder.restoreCallingIdentity(identity);
14684            }
14685        }
14686    }
14687
14688    @Override
14689    public int getPreferredActivities(List<IntentFilter> outFilters,
14690            List<ComponentName> outActivities, String packageName) {
14691
14692        int num = 0;
14693        final int userId = UserHandle.getCallingUserId();
14694        // reader
14695        synchronized (mPackages) {
14696            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14697            if (pir != null) {
14698                final Iterator<PreferredActivity> it = pir.filterIterator();
14699                while (it.hasNext()) {
14700                    final PreferredActivity pa = it.next();
14701                    if (packageName == null
14702                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14703                                    && pa.mPref.mAlways)) {
14704                        if (outFilters != null) {
14705                            outFilters.add(new IntentFilter(pa));
14706                        }
14707                        if (outActivities != null) {
14708                            outActivities.add(pa.mPref.mComponent);
14709                        }
14710                    }
14711                }
14712            }
14713        }
14714
14715        return num;
14716    }
14717
14718    @Override
14719    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14720            int userId) {
14721        int callingUid = Binder.getCallingUid();
14722        if (callingUid != Process.SYSTEM_UID) {
14723            throw new SecurityException(
14724                    "addPersistentPreferredActivity can only be run by the system");
14725        }
14726        if (filter.countActions() == 0) {
14727            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14728            return;
14729        }
14730        synchronized (mPackages) {
14731            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14732                    ":");
14733            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14734            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14735                    new PersistentPreferredActivity(filter, activity));
14736            scheduleWritePackageRestrictionsLocked(userId);
14737        }
14738    }
14739
14740    @Override
14741    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14742        int callingUid = Binder.getCallingUid();
14743        if (callingUid != Process.SYSTEM_UID) {
14744            throw new SecurityException(
14745                    "clearPackagePersistentPreferredActivities can only be run by the system");
14746        }
14747        ArrayList<PersistentPreferredActivity> removed = null;
14748        boolean changed = false;
14749        synchronized (mPackages) {
14750            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14751                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14752                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14753                        .valueAt(i);
14754                if (userId != thisUserId) {
14755                    continue;
14756                }
14757                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14758                while (it.hasNext()) {
14759                    PersistentPreferredActivity ppa = it.next();
14760                    // Mark entry for removal only if it matches the package name.
14761                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14762                        if (removed == null) {
14763                            removed = new ArrayList<PersistentPreferredActivity>();
14764                        }
14765                        removed.add(ppa);
14766                    }
14767                }
14768                if (removed != null) {
14769                    for (int j=0; j<removed.size(); j++) {
14770                        PersistentPreferredActivity ppa = removed.get(j);
14771                        ppir.removeFilter(ppa);
14772                    }
14773                    changed = true;
14774                }
14775            }
14776
14777            if (changed) {
14778                scheduleWritePackageRestrictionsLocked(userId);
14779            }
14780        }
14781    }
14782
14783    /**
14784     * Common machinery for picking apart a restored XML blob and passing
14785     * it to a caller-supplied functor to be applied to the running system.
14786     */
14787    private void restoreFromXml(XmlPullParser parser, int userId,
14788            String expectedStartTag, BlobXmlRestorer functor)
14789            throws IOException, XmlPullParserException {
14790        int type;
14791        while ((type = parser.next()) != XmlPullParser.START_TAG
14792                && type != XmlPullParser.END_DOCUMENT) {
14793        }
14794        if (type != XmlPullParser.START_TAG) {
14795            // oops didn't find a start tag?!
14796            if (DEBUG_BACKUP) {
14797                Slog.e(TAG, "Didn't find start tag during restore");
14798            }
14799            return;
14800        }
14801Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14802        // this is supposed to be TAG_PREFERRED_BACKUP
14803        if (!expectedStartTag.equals(parser.getName())) {
14804            if (DEBUG_BACKUP) {
14805                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14806            }
14807            return;
14808        }
14809
14810        // skip interfering stuff, then we're aligned with the backing implementation
14811        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14812Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14813        functor.apply(parser, userId);
14814    }
14815
14816    private interface BlobXmlRestorer {
14817        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14818    }
14819
14820    /**
14821     * Non-Binder method, support for the backup/restore mechanism: write the
14822     * full set of preferred activities in its canonical XML format.  Returns the
14823     * XML output as a byte array, or null if there is none.
14824     */
14825    @Override
14826    public byte[] getPreferredActivityBackup(int userId) {
14827        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14828            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14829        }
14830
14831        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14832        try {
14833            final XmlSerializer serializer = new FastXmlSerializer();
14834            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14835            serializer.startDocument(null, true);
14836            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14837
14838            synchronized (mPackages) {
14839                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14840            }
14841
14842            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14843            serializer.endDocument();
14844            serializer.flush();
14845        } catch (Exception e) {
14846            if (DEBUG_BACKUP) {
14847                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14848            }
14849            return null;
14850        }
14851
14852        return dataStream.toByteArray();
14853    }
14854
14855    @Override
14856    public void restorePreferredActivities(byte[] backup, int userId) {
14857        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14858            throw new SecurityException("Only the system may call restorePreferredActivities()");
14859        }
14860
14861        try {
14862            final XmlPullParser parser = Xml.newPullParser();
14863            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14864            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14865                    new BlobXmlRestorer() {
14866                        @Override
14867                        public void apply(XmlPullParser parser, int userId)
14868                                throws XmlPullParserException, IOException {
14869                            synchronized (mPackages) {
14870                                mSettings.readPreferredActivitiesLPw(parser, userId);
14871                            }
14872                        }
14873                    } );
14874        } catch (Exception e) {
14875            if (DEBUG_BACKUP) {
14876                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14877            }
14878        }
14879    }
14880
14881    /**
14882     * Non-Binder method, support for the backup/restore mechanism: write the
14883     * default browser (etc) settings in its canonical XML format.  Returns the default
14884     * browser XML representation as a byte array, or null if there is none.
14885     */
14886    @Override
14887    public byte[] getDefaultAppsBackup(int userId) {
14888        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14889            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14890        }
14891
14892        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14893        try {
14894            final XmlSerializer serializer = new FastXmlSerializer();
14895            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14896            serializer.startDocument(null, true);
14897            serializer.startTag(null, TAG_DEFAULT_APPS);
14898
14899            synchronized (mPackages) {
14900                mSettings.writeDefaultAppsLPr(serializer, userId);
14901            }
14902
14903            serializer.endTag(null, TAG_DEFAULT_APPS);
14904            serializer.endDocument();
14905            serializer.flush();
14906        } catch (Exception e) {
14907            if (DEBUG_BACKUP) {
14908                Slog.e(TAG, "Unable to write default apps for backup", e);
14909            }
14910            return null;
14911        }
14912
14913        return dataStream.toByteArray();
14914    }
14915
14916    @Override
14917    public void restoreDefaultApps(byte[] backup, int userId) {
14918        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14919            throw new SecurityException("Only the system may call restoreDefaultApps()");
14920        }
14921
14922        try {
14923            final XmlPullParser parser = Xml.newPullParser();
14924            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14925            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14926                    new BlobXmlRestorer() {
14927                        @Override
14928                        public void apply(XmlPullParser parser, int userId)
14929                                throws XmlPullParserException, IOException {
14930                            synchronized (mPackages) {
14931                                mSettings.readDefaultAppsLPw(parser, userId);
14932                            }
14933                        }
14934                    } );
14935        } catch (Exception e) {
14936            if (DEBUG_BACKUP) {
14937                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14938            }
14939        }
14940    }
14941
14942    @Override
14943    public byte[] getIntentFilterVerificationBackup(int userId) {
14944        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14945            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14946        }
14947
14948        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14949        try {
14950            final XmlSerializer serializer = new FastXmlSerializer();
14951            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14952            serializer.startDocument(null, true);
14953            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14954
14955            synchronized (mPackages) {
14956                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14957            }
14958
14959            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14960            serializer.endDocument();
14961            serializer.flush();
14962        } catch (Exception e) {
14963            if (DEBUG_BACKUP) {
14964                Slog.e(TAG, "Unable to write default apps for backup", e);
14965            }
14966            return null;
14967        }
14968
14969        return dataStream.toByteArray();
14970    }
14971
14972    @Override
14973    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14974        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14975            throw new SecurityException("Only the system may call restorePreferredActivities()");
14976        }
14977
14978        try {
14979            final XmlPullParser parser = Xml.newPullParser();
14980            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14981            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14982                    new BlobXmlRestorer() {
14983                        @Override
14984                        public void apply(XmlPullParser parser, int userId)
14985                                throws XmlPullParserException, IOException {
14986                            synchronized (mPackages) {
14987                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14988                                mSettings.writeLPr();
14989                            }
14990                        }
14991                    } );
14992        } catch (Exception e) {
14993            if (DEBUG_BACKUP) {
14994                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14995            }
14996        }
14997    }
14998
14999    @Override
15000    public byte[] getPermissionGrantBackup(int userId) {
15001        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15002            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15003        }
15004
15005        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15006        try {
15007            final XmlSerializer serializer = new FastXmlSerializer();
15008            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15009            serializer.startDocument(null, true);
15010            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15011
15012            synchronized (mPackages) {
15013                serializeRuntimePermissionGrantsLPr(serializer, userId);
15014            }
15015
15016            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15017            serializer.endDocument();
15018            serializer.flush();
15019        } catch (Exception e) {
15020            if (DEBUG_BACKUP) {
15021                Slog.e(TAG, "Unable to write default apps for backup", e);
15022            }
15023            return null;
15024        }
15025
15026        return dataStream.toByteArray();
15027    }
15028
15029    @Override
15030    public void restorePermissionGrants(byte[] backup, int userId) {
15031        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15032            throw new SecurityException("Only the system may call restorePermissionGrants()");
15033        }
15034
15035        try {
15036            final XmlPullParser parser = Xml.newPullParser();
15037            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15038            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15039                    new BlobXmlRestorer() {
15040                        @Override
15041                        public void apply(XmlPullParser parser, int userId)
15042                                throws XmlPullParserException, IOException {
15043                            synchronized (mPackages) {
15044                                processRestoredPermissionGrantsLPr(parser, userId);
15045                            }
15046                        }
15047                    } );
15048        } catch (Exception e) {
15049            if (DEBUG_BACKUP) {
15050                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15051            }
15052        }
15053    }
15054
15055    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15056            throws IOException {
15057        serializer.startTag(null, TAG_ALL_GRANTS);
15058
15059        final int N = mSettings.mPackages.size();
15060        for (int i = 0; i < N; i++) {
15061            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15062            boolean pkgGrantsKnown = false;
15063
15064            PermissionsState packagePerms = ps.getPermissionsState();
15065
15066            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15067                final int grantFlags = state.getFlags();
15068                // only look at grants that are not system/policy fixed
15069                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15070                    final boolean isGranted = state.isGranted();
15071                    // And only back up the user-twiddled state bits
15072                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15073                        final String packageName = mSettings.mPackages.keyAt(i);
15074                        if (!pkgGrantsKnown) {
15075                            serializer.startTag(null, TAG_GRANT);
15076                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15077                            pkgGrantsKnown = true;
15078                        }
15079
15080                        final boolean userSet =
15081                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15082                        final boolean userFixed =
15083                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15084                        final boolean revoke =
15085                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15086
15087                        serializer.startTag(null, TAG_PERMISSION);
15088                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15089                        if (isGranted) {
15090                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15091                        }
15092                        if (userSet) {
15093                            serializer.attribute(null, ATTR_USER_SET, "true");
15094                        }
15095                        if (userFixed) {
15096                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15097                        }
15098                        if (revoke) {
15099                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15100                        }
15101                        serializer.endTag(null, TAG_PERMISSION);
15102                    }
15103                }
15104            }
15105
15106            if (pkgGrantsKnown) {
15107                serializer.endTag(null, TAG_GRANT);
15108            }
15109        }
15110
15111        serializer.endTag(null, TAG_ALL_GRANTS);
15112    }
15113
15114    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15115            throws XmlPullParserException, IOException {
15116        String pkgName = null;
15117        int outerDepth = parser.getDepth();
15118        int type;
15119        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15120                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15121            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15122                continue;
15123            }
15124
15125            final String tagName = parser.getName();
15126            if (tagName.equals(TAG_GRANT)) {
15127                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15128                if (DEBUG_BACKUP) {
15129                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15130                }
15131            } else if (tagName.equals(TAG_PERMISSION)) {
15132
15133                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15134                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15135
15136                int newFlagSet = 0;
15137                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15138                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15139                }
15140                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15141                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15142                }
15143                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15144                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15145                }
15146                if (DEBUG_BACKUP) {
15147                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15148                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15149                }
15150                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15151                if (ps != null) {
15152                    // Already installed so we apply the grant immediately
15153                    if (DEBUG_BACKUP) {
15154                        Slog.v(TAG, "        + already installed; applying");
15155                    }
15156                    PermissionsState perms = ps.getPermissionsState();
15157                    BasePermission bp = mSettings.mPermissions.get(permName);
15158                    if (bp != null) {
15159                        if (isGranted) {
15160                            perms.grantRuntimePermission(bp, userId);
15161                        }
15162                        if (newFlagSet != 0) {
15163                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15164                        }
15165                    }
15166                } else {
15167                    // Need to wait for post-restore install to apply the grant
15168                    if (DEBUG_BACKUP) {
15169                        Slog.v(TAG, "        - not yet installed; saving for later");
15170                    }
15171                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15172                            isGranted, newFlagSet, userId);
15173                }
15174            } else {
15175                PackageManagerService.reportSettingsProblem(Log.WARN,
15176                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15177                XmlUtils.skipCurrentTag(parser);
15178            }
15179        }
15180
15181        scheduleWriteSettingsLocked();
15182        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15183    }
15184
15185    @Override
15186    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15187            int sourceUserId, int targetUserId, int flags) {
15188        mContext.enforceCallingOrSelfPermission(
15189                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15190        int callingUid = Binder.getCallingUid();
15191        enforceOwnerRights(ownerPackage, callingUid);
15192        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15193        if (intentFilter.countActions() == 0) {
15194            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15195            return;
15196        }
15197        synchronized (mPackages) {
15198            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15199                    ownerPackage, targetUserId, flags);
15200            CrossProfileIntentResolver resolver =
15201                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15202            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15203            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15204            if (existing != null) {
15205                int size = existing.size();
15206                for (int i = 0; i < size; i++) {
15207                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15208                        return;
15209                    }
15210                }
15211            }
15212            resolver.addFilter(newFilter);
15213            scheduleWritePackageRestrictionsLocked(sourceUserId);
15214        }
15215    }
15216
15217    @Override
15218    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15219        mContext.enforceCallingOrSelfPermission(
15220                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15221        int callingUid = Binder.getCallingUid();
15222        enforceOwnerRights(ownerPackage, callingUid);
15223        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15224        synchronized (mPackages) {
15225            CrossProfileIntentResolver resolver =
15226                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15227            ArraySet<CrossProfileIntentFilter> set =
15228                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15229            for (CrossProfileIntentFilter filter : set) {
15230                if (filter.getOwnerPackage().equals(ownerPackage)) {
15231                    resolver.removeFilter(filter);
15232                }
15233            }
15234            scheduleWritePackageRestrictionsLocked(sourceUserId);
15235        }
15236    }
15237
15238    // Enforcing that callingUid is owning pkg on userId
15239    private void enforceOwnerRights(String pkg, int callingUid) {
15240        // The system owns everything.
15241        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15242            return;
15243        }
15244        int callingUserId = UserHandle.getUserId(callingUid);
15245        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15246        if (pi == null) {
15247            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15248                    + callingUserId);
15249        }
15250        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15251            throw new SecurityException("Calling uid " + callingUid
15252                    + " does not own package " + pkg);
15253        }
15254    }
15255
15256    @Override
15257    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15258        Intent intent = new Intent(Intent.ACTION_MAIN);
15259        intent.addCategory(Intent.CATEGORY_HOME);
15260
15261        final int callingUserId = UserHandle.getCallingUserId();
15262        List<ResolveInfo> list = queryIntentActivities(intent, null,
15263                PackageManager.GET_META_DATA, callingUserId);
15264        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15265                true, false, false, callingUserId);
15266
15267        allHomeCandidates.clear();
15268        if (list != null) {
15269            for (ResolveInfo ri : list) {
15270                allHomeCandidates.add(ri);
15271            }
15272        }
15273        return (preferred == null || preferred.activityInfo == null)
15274                ? null
15275                : new ComponentName(preferred.activityInfo.packageName,
15276                        preferred.activityInfo.name);
15277    }
15278
15279    @Override
15280    public void setApplicationEnabledSetting(String appPackageName,
15281            int newState, int flags, int userId, String callingPackage) {
15282        if (!sUserManager.exists(userId)) return;
15283        if (callingPackage == null) {
15284            callingPackage = Integer.toString(Binder.getCallingUid());
15285        }
15286        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15287    }
15288
15289    @Override
15290    public void setComponentEnabledSetting(ComponentName componentName,
15291            int newState, int flags, int userId) {
15292        if (!sUserManager.exists(userId)) return;
15293        setEnabledSetting(componentName.getPackageName(),
15294                componentName.getClassName(), newState, flags, userId, null);
15295    }
15296
15297    private void setEnabledSetting(final String packageName, String className, int newState,
15298            final int flags, int userId, String callingPackage) {
15299        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15300              || newState == COMPONENT_ENABLED_STATE_ENABLED
15301              || newState == COMPONENT_ENABLED_STATE_DISABLED
15302              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15303              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15304            throw new IllegalArgumentException("Invalid new component state: "
15305                    + newState);
15306        }
15307        PackageSetting pkgSetting;
15308        final int uid = Binder.getCallingUid();
15309        final int permission = mContext.checkCallingOrSelfPermission(
15310                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15311        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15312        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15313        boolean sendNow = false;
15314        boolean isApp = (className == null);
15315        String componentName = isApp ? packageName : className;
15316        int packageUid = -1;
15317        ArrayList<String> components;
15318
15319        // writer
15320        synchronized (mPackages) {
15321            pkgSetting = mSettings.mPackages.get(packageName);
15322            if (pkgSetting == null) {
15323                if (className == null) {
15324                    throw new IllegalArgumentException("Unknown package: " + packageName);
15325                }
15326                throw new IllegalArgumentException(
15327                        "Unknown component: " + packageName + "/" + className);
15328            }
15329            // Allow root and verify that userId is not being specified by a different user
15330            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15331                throw new SecurityException(
15332                        "Permission Denial: attempt to change component state from pid="
15333                        + Binder.getCallingPid()
15334                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15335            }
15336            if (className == null) {
15337                // We're dealing with an application/package level state change
15338                if (pkgSetting.getEnabled(userId) == newState) {
15339                    // Nothing to do
15340                    return;
15341                }
15342                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15343                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15344                    // Don't care about who enables an app.
15345                    callingPackage = null;
15346                }
15347                pkgSetting.setEnabled(newState, userId, callingPackage);
15348                // pkgSetting.pkg.mSetEnabled = newState;
15349            } else {
15350                // We're dealing with a component level state change
15351                // First, verify that this is a valid class name.
15352                PackageParser.Package pkg = pkgSetting.pkg;
15353                if (pkg == null || !pkg.hasComponentClassName(className)) {
15354                    if (pkg != null &&
15355                            pkg.applicationInfo.targetSdkVersion >=
15356                                    Build.VERSION_CODES.JELLY_BEAN) {
15357                        throw new IllegalArgumentException("Component class " + className
15358                                + " does not exist in " + packageName);
15359                    } else {
15360                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15361                                + className + " does not exist in " + packageName);
15362                    }
15363                }
15364                switch (newState) {
15365                case COMPONENT_ENABLED_STATE_ENABLED:
15366                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15367                        return;
15368                    }
15369                    break;
15370                case COMPONENT_ENABLED_STATE_DISABLED:
15371                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15372                        return;
15373                    }
15374                    break;
15375                case COMPONENT_ENABLED_STATE_DEFAULT:
15376                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15377                        return;
15378                    }
15379                    break;
15380                default:
15381                    Slog.e(TAG, "Invalid new component state: " + newState);
15382                    return;
15383                }
15384            }
15385            scheduleWritePackageRestrictionsLocked(userId);
15386            components = mPendingBroadcasts.get(userId, packageName);
15387            final boolean newPackage = components == null;
15388            if (newPackage) {
15389                components = new ArrayList<String>();
15390            }
15391            if (!components.contains(componentName)) {
15392                components.add(componentName);
15393            }
15394            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15395                sendNow = true;
15396                // Purge entry from pending broadcast list if another one exists already
15397                // since we are sending one right away.
15398                mPendingBroadcasts.remove(userId, packageName);
15399            } else {
15400                if (newPackage) {
15401                    mPendingBroadcasts.put(userId, packageName, components);
15402                }
15403                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15404                    // Schedule a message
15405                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15406                }
15407            }
15408        }
15409
15410        long callingId = Binder.clearCallingIdentity();
15411        try {
15412            if (sendNow) {
15413                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15414                sendPackageChangedBroadcast(packageName,
15415                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15416            }
15417        } finally {
15418            Binder.restoreCallingIdentity(callingId);
15419        }
15420    }
15421
15422    private void sendPackageChangedBroadcast(String packageName,
15423            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15424        if (DEBUG_INSTALL)
15425            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15426                    + componentNames);
15427        Bundle extras = new Bundle(4);
15428        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15429        String nameList[] = new String[componentNames.size()];
15430        componentNames.toArray(nameList);
15431        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15432        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15433        extras.putInt(Intent.EXTRA_UID, packageUid);
15434        // If this is not reporting a change of the overall package, then only send it
15435        // to registered receivers.  We don't want to launch a swath of apps for every
15436        // little component state change.
15437        final int flags = !componentNames.contains(packageName)
15438                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15439        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15440                new int[] {UserHandle.getUserId(packageUid)});
15441    }
15442
15443    @Override
15444    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15445        if (!sUserManager.exists(userId)) return;
15446        final int uid = Binder.getCallingUid();
15447        final int permission = mContext.checkCallingOrSelfPermission(
15448                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15449        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15450        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15451        // writer
15452        synchronized (mPackages) {
15453            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15454                    allowedByPermission, uid, userId)) {
15455                scheduleWritePackageRestrictionsLocked(userId);
15456            }
15457        }
15458    }
15459
15460    @Override
15461    public String getInstallerPackageName(String packageName) {
15462        // reader
15463        synchronized (mPackages) {
15464            return mSettings.getInstallerPackageNameLPr(packageName);
15465        }
15466    }
15467
15468    @Override
15469    public int getApplicationEnabledSetting(String packageName, int userId) {
15470        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15471        int uid = Binder.getCallingUid();
15472        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15473        // reader
15474        synchronized (mPackages) {
15475            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15476        }
15477    }
15478
15479    @Override
15480    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15481        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15482        int uid = Binder.getCallingUid();
15483        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15484        // reader
15485        synchronized (mPackages) {
15486            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15487        }
15488    }
15489
15490    @Override
15491    public void enterSafeMode() {
15492        enforceSystemOrRoot("Only the system can request entering safe mode");
15493
15494        if (!mSystemReady) {
15495            mSafeMode = true;
15496        }
15497    }
15498
15499    @Override
15500    public void systemReady() {
15501        mSystemReady = true;
15502
15503        // Read the compatibilty setting when the system is ready.
15504        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15505                mContext.getContentResolver(),
15506                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15507        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15508        if (DEBUG_SETTINGS) {
15509            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15510        }
15511
15512        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15513
15514        synchronized (mPackages) {
15515            // Verify that all of the preferred activity components actually
15516            // exist.  It is possible for applications to be updated and at
15517            // that point remove a previously declared activity component that
15518            // had been set as a preferred activity.  We try to clean this up
15519            // the next time we encounter that preferred activity, but it is
15520            // possible for the user flow to never be able to return to that
15521            // situation so here we do a sanity check to make sure we haven't
15522            // left any junk around.
15523            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15524            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15525                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15526                removed.clear();
15527                for (PreferredActivity pa : pir.filterSet()) {
15528                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15529                        removed.add(pa);
15530                    }
15531                }
15532                if (removed.size() > 0) {
15533                    for (int r=0; r<removed.size(); r++) {
15534                        PreferredActivity pa = removed.get(r);
15535                        Slog.w(TAG, "Removing dangling preferred activity: "
15536                                + pa.mPref.mComponent);
15537                        pir.removeFilter(pa);
15538                    }
15539                    mSettings.writePackageRestrictionsLPr(
15540                            mSettings.mPreferredActivities.keyAt(i));
15541                }
15542            }
15543
15544            for (int userId : UserManagerService.getInstance().getUserIds()) {
15545                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15546                    grantPermissionsUserIds = ArrayUtils.appendInt(
15547                            grantPermissionsUserIds, userId);
15548                }
15549            }
15550        }
15551        sUserManager.systemReady();
15552
15553        // If we upgraded grant all default permissions before kicking off.
15554        for (int userId : grantPermissionsUserIds) {
15555            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15556        }
15557
15558        // Kick off any messages waiting for system ready
15559        if (mPostSystemReadyMessages != null) {
15560            for (Message msg : mPostSystemReadyMessages) {
15561                msg.sendToTarget();
15562            }
15563            mPostSystemReadyMessages = null;
15564        }
15565
15566        // Watch for external volumes that come and go over time
15567        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15568        storage.registerListener(mStorageListener);
15569
15570        mInstallerService.systemReady();
15571        mPackageDexOptimizer.systemReady();
15572
15573        MountServiceInternal mountServiceInternal = LocalServices.getService(
15574                MountServiceInternal.class);
15575        mountServiceInternal.addExternalStoragePolicy(
15576                new MountServiceInternal.ExternalStorageMountPolicy() {
15577            @Override
15578            public int getMountMode(int uid, String packageName) {
15579                if (Process.isIsolated(uid)) {
15580                    return Zygote.MOUNT_EXTERNAL_NONE;
15581                }
15582                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15583                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15584                }
15585                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15586                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15587                }
15588                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15589                    return Zygote.MOUNT_EXTERNAL_READ;
15590                }
15591                return Zygote.MOUNT_EXTERNAL_WRITE;
15592            }
15593
15594            @Override
15595            public boolean hasExternalStorage(int uid, String packageName) {
15596                return true;
15597            }
15598        });
15599    }
15600
15601    @Override
15602    public boolean isSafeMode() {
15603        return mSafeMode;
15604    }
15605
15606    @Override
15607    public boolean hasSystemUidErrors() {
15608        return mHasSystemUidErrors;
15609    }
15610
15611    static String arrayToString(int[] array) {
15612        StringBuffer buf = new StringBuffer(128);
15613        buf.append('[');
15614        if (array != null) {
15615            for (int i=0; i<array.length; i++) {
15616                if (i > 0) buf.append(", ");
15617                buf.append(array[i]);
15618            }
15619        }
15620        buf.append(']');
15621        return buf.toString();
15622    }
15623
15624    static class DumpState {
15625        public static final int DUMP_LIBS = 1 << 0;
15626        public static final int DUMP_FEATURES = 1 << 1;
15627        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15628        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15629        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15630        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15631        public static final int DUMP_PERMISSIONS = 1 << 6;
15632        public static final int DUMP_PACKAGES = 1 << 7;
15633        public static final int DUMP_SHARED_USERS = 1 << 8;
15634        public static final int DUMP_MESSAGES = 1 << 9;
15635        public static final int DUMP_PROVIDERS = 1 << 10;
15636        public static final int DUMP_VERIFIERS = 1 << 11;
15637        public static final int DUMP_PREFERRED = 1 << 12;
15638        public static final int DUMP_PREFERRED_XML = 1 << 13;
15639        public static final int DUMP_KEYSETS = 1 << 14;
15640        public static final int DUMP_VERSION = 1 << 15;
15641        public static final int DUMP_INSTALLS = 1 << 16;
15642        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15643        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15644
15645        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15646
15647        private int mTypes;
15648
15649        private int mOptions;
15650
15651        private boolean mTitlePrinted;
15652
15653        private SharedUserSetting mSharedUser;
15654
15655        public boolean isDumping(int type) {
15656            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15657                return true;
15658            }
15659
15660            return (mTypes & type) != 0;
15661        }
15662
15663        public void setDump(int type) {
15664            mTypes |= type;
15665        }
15666
15667        public boolean isOptionEnabled(int option) {
15668            return (mOptions & option) != 0;
15669        }
15670
15671        public void setOptionEnabled(int option) {
15672            mOptions |= option;
15673        }
15674
15675        public boolean onTitlePrinted() {
15676            final boolean printed = mTitlePrinted;
15677            mTitlePrinted = true;
15678            return printed;
15679        }
15680
15681        public boolean getTitlePrinted() {
15682            return mTitlePrinted;
15683        }
15684
15685        public void setTitlePrinted(boolean enabled) {
15686            mTitlePrinted = enabled;
15687        }
15688
15689        public SharedUserSetting getSharedUser() {
15690            return mSharedUser;
15691        }
15692
15693        public void setSharedUser(SharedUserSetting user) {
15694            mSharedUser = user;
15695        }
15696    }
15697
15698    @Override
15699    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15700            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15701        (new PackageManagerShellCommand(this)).exec(
15702                this, in, out, err, args, resultReceiver);
15703    }
15704
15705    @Override
15706    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15707        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15708                != PackageManager.PERMISSION_GRANTED) {
15709            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15710                    + Binder.getCallingPid()
15711                    + ", uid=" + Binder.getCallingUid()
15712                    + " without permission "
15713                    + android.Manifest.permission.DUMP);
15714            return;
15715        }
15716
15717        DumpState dumpState = new DumpState();
15718        boolean fullPreferred = false;
15719        boolean checkin = false;
15720
15721        String packageName = null;
15722        ArraySet<String> permissionNames = null;
15723
15724        int opti = 0;
15725        while (opti < args.length) {
15726            String opt = args[opti];
15727            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15728                break;
15729            }
15730            opti++;
15731
15732            if ("-a".equals(opt)) {
15733                // Right now we only know how to print all.
15734            } else if ("-h".equals(opt)) {
15735                pw.println("Package manager dump options:");
15736                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15737                pw.println("    --checkin: dump for a checkin");
15738                pw.println("    -f: print details of intent filters");
15739                pw.println("    -h: print this help");
15740                pw.println("  cmd may be one of:");
15741                pw.println("    l[ibraries]: list known shared libraries");
15742                pw.println("    f[eatures]: list device features");
15743                pw.println("    k[eysets]: print known keysets");
15744                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15745                pw.println("    perm[issions]: dump permissions");
15746                pw.println("    permission [name ...]: dump declaration and use of given permission");
15747                pw.println("    pref[erred]: print preferred package settings");
15748                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15749                pw.println("    prov[iders]: dump content providers");
15750                pw.println("    p[ackages]: dump installed packages");
15751                pw.println("    s[hared-users]: dump shared user IDs");
15752                pw.println("    m[essages]: print collected runtime messages");
15753                pw.println("    v[erifiers]: print package verifier info");
15754                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15755                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15756                pw.println("    version: print database version info");
15757                pw.println("    write: write current settings now");
15758                pw.println("    installs: details about install sessions");
15759                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15760                pw.println("    <package.name>: info about given package");
15761                return;
15762            } else if ("--checkin".equals(opt)) {
15763                checkin = true;
15764            } else if ("-f".equals(opt)) {
15765                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15766            } else {
15767                pw.println("Unknown argument: " + opt + "; use -h for help");
15768            }
15769        }
15770
15771        // Is the caller requesting to dump a particular piece of data?
15772        if (opti < args.length) {
15773            String cmd = args[opti];
15774            opti++;
15775            // Is this a package name?
15776            if ("android".equals(cmd) || cmd.contains(".")) {
15777                packageName = cmd;
15778                // When dumping a single package, we always dump all of its
15779                // filter information since the amount of data will be reasonable.
15780                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15781            } else if ("check-permission".equals(cmd)) {
15782                if (opti >= args.length) {
15783                    pw.println("Error: check-permission missing permission argument");
15784                    return;
15785                }
15786                String perm = args[opti];
15787                opti++;
15788                if (opti >= args.length) {
15789                    pw.println("Error: check-permission missing package argument");
15790                    return;
15791                }
15792                String pkg = args[opti];
15793                opti++;
15794                int user = UserHandle.getUserId(Binder.getCallingUid());
15795                if (opti < args.length) {
15796                    try {
15797                        user = Integer.parseInt(args[opti]);
15798                    } catch (NumberFormatException e) {
15799                        pw.println("Error: check-permission user argument is not a number: "
15800                                + args[opti]);
15801                        return;
15802                    }
15803                }
15804                pw.println(checkPermission(perm, pkg, user));
15805                return;
15806            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15807                dumpState.setDump(DumpState.DUMP_LIBS);
15808            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15809                dumpState.setDump(DumpState.DUMP_FEATURES);
15810            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15811                if (opti >= args.length) {
15812                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15813                            | DumpState.DUMP_SERVICE_RESOLVERS
15814                            | DumpState.DUMP_RECEIVER_RESOLVERS
15815                            | DumpState.DUMP_CONTENT_RESOLVERS);
15816                } else {
15817                    while (opti < args.length) {
15818                        String name = args[opti];
15819                        if ("a".equals(name) || "activity".equals(name)) {
15820                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15821                        } else if ("s".equals(name) || "service".equals(name)) {
15822                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15823                        } else if ("r".equals(name) || "receiver".equals(name)) {
15824                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15825                        } else if ("c".equals(name) || "content".equals(name)) {
15826                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15827                        } else {
15828                            pw.println("Error: unknown resolver table type: " + name);
15829                            return;
15830                        }
15831                        opti++;
15832                    }
15833                }
15834            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15835                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15836            } else if ("permission".equals(cmd)) {
15837                if (opti >= args.length) {
15838                    pw.println("Error: permission requires permission name");
15839                    return;
15840                }
15841                permissionNames = new ArraySet<>();
15842                while (opti < args.length) {
15843                    permissionNames.add(args[opti]);
15844                    opti++;
15845                }
15846                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15847                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15848            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15849                dumpState.setDump(DumpState.DUMP_PREFERRED);
15850            } else if ("preferred-xml".equals(cmd)) {
15851                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15852                if (opti < args.length && "--full".equals(args[opti])) {
15853                    fullPreferred = true;
15854                    opti++;
15855                }
15856            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15857                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15858            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15859                dumpState.setDump(DumpState.DUMP_PACKAGES);
15860            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15861                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15862            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15863                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15864            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15865                dumpState.setDump(DumpState.DUMP_MESSAGES);
15866            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15867                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15868            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15869                    || "intent-filter-verifiers".equals(cmd)) {
15870                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15871            } else if ("version".equals(cmd)) {
15872                dumpState.setDump(DumpState.DUMP_VERSION);
15873            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15874                dumpState.setDump(DumpState.DUMP_KEYSETS);
15875            } else if ("installs".equals(cmd)) {
15876                dumpState.setDump(DumpState.DUMP_INSTALLS);
15877            } else if ("write".equals(cmd)) {
15878                synchronized (mPackages) {
15879                    mSettings.writeLPr();
15880                    pw.println("Settings written.");
15881                    return;
15882                }
15883            }
15884        }
15885
15886        if (checkin) {
15887            pw.println("vers,1");
15888        }
15889
15890        // reader
15891        synchronized (mPackages) {
15892            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15893                if (!checkin) {
15894                    if (dumpState.onTitlePrinted())
15895                        pw.println();
15896                    pw.println("Database versions:");
15897                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15898                }
15899            }
15900
15901            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15902                if (!checkin) {
15903                    if (dumpState.onTitlePrinted())
15904                        pw.println();
15905                    pw.println("Verifiers:");
15906                    pw.print("  Required: ");
15907                    pw.print(mRequiredVerifierPackage);
15908                    pw.print(" (uid=");
15909                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15910                            UserHandle.USER_SYSTEM));
15911                    pw.println(")");
15912                } else if (mRequiredVerifierPackage != null) {
15913                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15914                    pw.print(",");
15915                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15916                            UserHandle.USER_SYSTEM));
15917                }
15918            }
15919
15920            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15921                    packageName == null) {
15922                if (mIntentFilterVerifierComponent != null) {
15923                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15924                    if (!checkin) {
15925                        if (dumpState.onTitlePrinted())
15926                            pw.println();
15927                        pw.println("Intent Filter Verifier:");
15928                        pw.print("  Using: ");
15929                        pw.print(verifierPackageName);
15930                        pw.print(" (uid=");
15931                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15932                                UserHandle.USER_SYSTEM));
15933                        pw.println(")");
15934                    } else if (verifierPackageName != null) {
15935                        pw.print("ifv,"); pw.print(verifierPackageName);
15936                        pw.print(",");
15937                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15938                                UserHandle.USER_SYSTEM));
15939                    }
15940                } else {
15941                    pw.println();
15942                    pw.println("No Intent Filter Verifier available!");
15943                }
15944            }
15945
15946            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15947                boolean printedHeader = false;
15948                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15949                while (it.hasNext()) {
15950                    String name = it.next();
15951                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15952                    if (!checkin) {
15953                        if (!printedHeader) {
15954                            if (dumpState.onTitlePrinted())
15955                                pw.println();
15956                            pw.println("Libraries:");
15957                            printedHeader = true;
15958                        }
15959                        pw.print("  ");
15960                    } else {
15961                        pw.print("lib,");
15962                    }
15963                    pw.print(name);
15964                    if (!checkin) {
15965                        pw.print(" -> ");
15966                    }
15967                    if (ent.path != null) {
15968                        if (!checkin) {
15969                            pw.print("(jar) ");
15970                            pw.print(ent.path);
15971                        } else {
15972                            pw.print(",jar,");
15973                            pw.print(ent.path);
15974                        }
15975                    } else {
15976                        if (!checkin) {
15977                            pw.print("(apk) ");
15978                            pw.print(ent.apk);
15979                        } else {
15980                            pw.print(",apk,");
15981                            pw.print(ent.apk);
15982                        }
15983                    }
15984                    pw.println();
15985                }
15986            }
15987
15988            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15989                if (dumpState.onTitlePrinted())
15990                    pw.println();
15991                if (!checkin) {
15992                    pw.println("Features:");
15993                }
15994                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15995                while (it.hasNext()) {
15996                    String name = it.next();
15997                    if (!checkin) {
15998                        pw.print("  ");
15999                    } else {
16000                        pw.print("feat,");
16001                    }
16002                    pw.println(name);
16003                }
16004            }
16005
16006            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16007                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16008                        : "Activity Resolver Table:", "  ", packageName,
16009                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16010                    dumpState.setTitlePrinted(true);
16011                }
16012            }
16013            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16014                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16015                        : "Receiver Resolver Table:", "  ", packageName,
16016                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16017                    dumpState.setTitlePrinted(true);
16018                }
16019            }
16020            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16021                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16022                        : "Service Resolver Table:", "  ", packageName,
16023                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16024                    dumpState.setTitlePrinted(true);
16025                }
16026            }
16027            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16028                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16029                        : "Provider Resolver Table:", "  ", packageName,
16030                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16031                    dumpState.setTitlePrinted(true);
16032                }
16033            }
16034
16035            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16036                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16037                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16038                    int user = mSettings.mPreferredActivities.keyAt(i);
16039                    if (pir.dump(pw,
16040                            dumpState.getTitlePrinted()
16041                                ? "\nPreferred Activities User " + user + ":"
16042                                : "Preferred Activities User " + user + ":", "  ",
16043                            packageName, true, false)) {
16044                        dumpState.setTitlePrinted(true);
16045                    }
16046                }
16047            }
16048
16049            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16050                pw.flush();
16051                FileOutputStream fout = new FileOutputStream(fd);
16052                BufferedOutputStream str = new BufferedOutputStream(fout);
16053                XmlSerializer serializer = new FastXmlSerializer();
16054                try {
16055                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16056                    serializer.startDocument(null, true);
16057                    serializer.setFeature(
16058                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16059                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16060                    serializer.endDocument();
16061                    serializer.flush();
16062                } catch (IllegalArgumentException e) {
16063                    pw.println("Failed writing: " + e);
16064                } catch (IllegalStateException e) {
16065                    pw.println("Failed writing: " + e);
16066                } catch (IOException e) {
16067                    pw.println("Failed writing: " + e);
16068                }
16069            }
16070
16071            if (!checkin
16072                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16073                    && packageName == null) {
16074                pw.println();
16075                int count = mSettings.mPackages.size();
16076                if (count == 0) {
16077                    pw.println("No applications!");
16078                    pw.println();
16079                } else {
16080                    final String prefix = "  ";
16081                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16082                    if (allPackageSettings.size() == 0) {
16083                        pw.println("No domain preferred apps!");
16084                        pw.println();
16085                    } else {
16086                        pw.println("App verification status:");
16087                        pw.println();
16088                        count = 0;
16089                        for (PackageSetting ps : allPackageSettings) {
16090                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16091                            if (ivi == null || ivi.getPackageName() == null) continue;
16092                            pw.println(prefix + "Package: " + ivi.getPackageName());
16093                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16094                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16095                            pw.println();
16096                            count++;
16097                        }
16098                        if (count == 0) {
16099                            pw.println(prefix + "No app verification established.");
16100                            pw.println();
16101                        }
16102                        for (int userId : sUserManager.getUserIds()) {
16103                            pw.println("App linkages for user " + userId + ":");
16104                            pw.println();
16105                            count = 0;
16106                            for (PackageSetting ps : allPackageSettings) {
16107                                final long status = ps.getDomainVerificationStatusForUser(userId);
16108                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16109                                    continue;
16110                                }
16111                                pw.println(prefix + "Package: " + ps.name);
16112                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16113                                String statusStr = IntentFilterVerificationInfo.
16114                                        getStatusStringFromValue(status);
16115                                pw.println(prefix + "Status:  " + statusStr);
16116                                pw.println();
16117                                count++;
16118                            }
16119                            if (count == 0) {
16120                                pw.println(prefix + "No configured app linkages.");
16121                                pw.println();
16122                            }
16123                        }
16124                    }
16125                }
16126            }
16127
16128            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16129                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16130                if (packageName == null && permissionNames == null) {
16131                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16132                        if (iperm == 0) {
16133                            if (dumpState.onTitlePrinted())
16134                                pw.println();
16135                            pw.println("AppOp Permissions:");
16136                        }
16137                        pw.print("  AppOp Permission ");
16138                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16139                        pw.println(":");
16140                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16141                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16142                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16143                        }
16144                    }
16145                }
16146            }
16147
16148            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16149                boolean printedSomething = false;
16150                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16151                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16152                        continue;
16153                    }
16154                    if (!printedSomething) {
16155                        if (dumpState.onTitlePrinted())
16156                            pw.println();
16157                        pw.println("Registered ContentProviders:");
16158                        printedSomething = true;
16159                    }
16160                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16161                    pw.print("    "); pw.println(p.toString());
16162                }
16163                printedSomething = false;
16164                for (Map.Entry<String, PackageParser.Provider> entry :
16165                        mProvidersByAuthority.entrySet()) {
16166                    PackageParser.Provider p = entry.getValue();
16167                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16168                        continue;
16169                    }
16170                    if (!printedSomething) {
16171                        if (dumpState.onTitlePrinted())
16172                            pw.println();
16173                        pw.println("ContentProvider Authorities:");
16174                        printedSomething = true;
16175                    }
16176                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16177                    pw.print("    "); pw.println(p.toString());
16178                    if (p.info != null && p.info.applicationInfo != null) {
16179                        final String appInfo = p.info.applicationInfo.toString();
16180                        pw.print("      applicationInfo="); pw.println(appInfo);
16181                    }
16182                }
16183            }
16184
16185            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16186                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16187            }
16188
16189            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16190                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16191            }
16192
16193            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16194                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16195            }
16196
16197            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16198                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16199            }
16200
16201            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16202                // XXX should handle packageName != null by dumping only install data that
16203                // the given package is involved with.
16204                if (dumpState.onTitlePrinted()) pw.println();
16205                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16206            }
16207
16208            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16209                if (dumpState.onTitlePrinted()) pw.println();
16210                mSettings.dumpReadMessagesLPr(pw, dumpState);
16211
16212                pw.println();
16213                pw.println("Package warning messages:");
16214                BufferedReader in = null;
16215                String line = null;
16216                try {
16217                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16218                    while ((line = in.readLine()) != null) {
16219                        if (line.contains("ignored: updated version")) continue;
16220                        pw.println(line);
16221                    }
16222                } catch (IOException ignored) {
16223                } finally {
16224                    IoUtils.closeQuietly(in);
16225                }
16226            }
16227
16228            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16229                BufferedReader in = null;
16230                String line = null;
16231                try {
16232                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16233                    while ((line = in.readLine()) != null) {
16234                        if (line.contains("ignored: updated version")) continue;
16235                        pw.print("msg,");
16236                        pw.println(line);
16237                    }
16238                } catch (IOException ignored) {
16239                } finally {
16240                    IoUtils.closeQuietly(in);
16241                }
16242            }
16243        }
16244    }
16245
16246    private String dumpDomainString(String packageName) {
16247        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16248        List<IntentFilter> filters = getAllIntentFilters(packageName);
16249
16250        ArraySet<String> result = new ArraySet<>();
16251        if (iviList.size() > 0) {
16252            for (IntentFilterVerificationInfo ivi : iviList) {
16253                for (String host : ivi.getDomains()) {
16254                    result.add(host);
16255                }
16256            }
16257        }
16258        if (filters != null && filters.size() > 0) {
16259            for (IntentFilter filter : filters) {
16260                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16261                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16262                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16263                    result.addAll(filter.getHostsList());
16264                }
16265            }
16266        }
16267
16268        StringBuilder sb = new StringBuilder(result.size() * 16);
16269        for (String domain : result) {
16270            if (sb.length() > 0) sb.append(" ");
16271            sb.append(domain);
16272        }
16273        return sb.toString();
16274    }
16275
16276    // ------- apps on sdcard specific code -------
16277    static final boolean DEBUG_SD_INSTALL = false;
16278
16279    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16280
16281    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16282
16283    private boolean mMediaMounted = false;
16284
16285    static String getEncryptKey() {
16286        try {
16287            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16288                    SD_ENCRYPTION_KEYSTORE_NAME);
16289            if (sdEncKey == null) {
16290                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16291                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16292                if (sdEncKey == null) {
16293                    Slog.e(TAG, "Failed to create encryption keys");
16294                    return null;
16295                }
16296            }
16297            return sdEncKey;
16298        } catch (NoSuchAlgorithmException nsae) {
16299            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16300            return null;
16301        } catch (IOException ioe) {
16302            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16303            return null;
16304        }
16305    }
16306
16307    /*
16308     * Update media status on PackageManager.
16309     */
16310    @Override
16311    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16312        int callingUid = Binder.getCallingUid();
16313        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16314            throw new SecurityException("Media status can only be updated by the system");
16315        }
16316        // reader; this apparently protects mMediaMounted, but should probably
16317        // be a different lock in that case.
16318        synchronized (mPackages) {
16319            Log.i(TAG, "Updating external media status from "
16320                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16321                    + (mediaStatus ? "mounted" : "unmounted"));
16322            if (DEBUG_SD_INSTALL)
16323                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16324                        + ", mMediaMounted=" + mMediaMounted);
16325            if (mediaStatus == mMediaMounted) {
16326                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16327                        : 0, -1);
16328                mHandler.sendMessage(msg);
16329                return;
16330            }
16331            mMediaMounted = mediaStatus;
16332        }
16333        // Queue up an async operation since the package installation may take a
16334        // little while.
16335        mHandler.post(new Runnable() {
16336            public void run() {
16337                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16338            }
16339        });
16340    }
16341
16342    /**
16343     * Called by MountService when the initial ASECs to scan are available.
16344     * Should block until all the ASEC containers are finished being scanned.
16345     */
16346    public void scanAvailableAsecs() {
16347        updateExternalMediaStatusInner(true, false, false);
16348    }
16349
16350    /*
16351     * Collect information of applications on external media, map them against
16352     * existing containers and update information based on current mount status.
16353     * Please note that we always have to report status if reportStatus has been
16354     * set to true especially when unloading packages.
16355     */
16356    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16357            boolean externalStorage) {
16358        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16359        int[] uidArr = EmptyArray.INT;
16360
16361        final String[] list = PackageHelper.getSecureContainerList();
16362        if (ArrayUtils.isEmpty(list)) {
16363            Log.i(TAG, "No secure containers found");
16364        } else {
16365            // Process list of secure containers and categorize them
16366            // as active or stale based on their package internal state.
16367
16368            // reader
16369            synchronized (mPackages) {
16370                for (String cid : list) {
16371                    // Leave stages untouched for now; installer service owns them
16372                    if (PackageInstallerService.isStageName(cid)) continue;
16373
16374                    if (DEBUG_SD_INSTALL)
16375                        Log.i(TAG, "Processing container " + cid);
16376                    String pkgName = getAsecPackageName(cid);
16377                    if (pkgName == null) {
16378                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16379                        continue;
16380                    }
16381                    if (DEBUG_SD_INSTALL)
16382                        Log.i(TAG, "Looking for pkg : " + pkgName);
16383
16384                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16385                    if (ps == null) {
16386                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16387                        continue;
16388                    }
16389
16390                    /*
16391                     * Skip packages that are not external if we're unmounting
16392                     * external storage.
16393                     */
16394                    if (externalStorage && !isMounted && !isExternal(ps)) {
16395                        continue;
16396                    }
16397
16398                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16399                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16400                    // The package status is changed only if the code path
16401                    // matches between settings and the container id.
16402                    if (ps.codePathString != null
16403                            && ps.codePathString.startsWith(args.getCodePath())) {
16404                        if (DEBUG_SD_INSTALL) {
16405                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16406                                    + " at code path: " + ps.codePathString);
16407                        }
16408
16409                        // We do have a valid package installed on sdcard
16410                        processCids.put(args, ps.codePathString);
16411                        final int uid = ps.appId;
16412                        if (uid != -1) {
16413                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16414                        }
16415                    } else {
16416                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16417                                + ps.codePathString);
16418                    }
16419                }
16420            }
16421
16422            Arrays.sort(uidArr);
16423        }
16424
16425        // Process packages with valid entries.
16426        if (isMounted) {
16427            if (DEBUG_SD_INSTALL)
16428                Log.i(TAG, "Loading packages");
16429            loadMediaPackages(processCids, uidArr, externalStorage);
16430            startCleaningPackages();
16431            mInstallerService.onSecureContainersAvailable();
16432        } else {
16433            if (DEBUG_SD_INSTALL)
16434                Log.i(TAG, "Unloading packages");
16435            unloadMediaPackages(processCids, uidArr, reportStatus);
16436        }
16437    }
16438
16439    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16440            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16441        final int size = infos.size();
16442        final String[] packageNames = new String[size];
16443        final int[] packageUids = new int[size];
16444        for (int i = 0; i < size; i++) {
16445            final ApplicationInfo info = infos.get(i);
16446            packageNames[i] = info.packageName;
16447            packageUids[i] = info.uid;
16448        }
16449        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16450                finishedReceiver);
16451    }
16452
16453    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16454            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16455        sendResourcesChangedBroadcast(mediaStatus, replacing,
16456                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16457    }
16458
16459    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16460            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16461        int size = pkgList.length;
16462        if (size > 0) {
16463            // Send broadcasts here
16464            Bundle extras = new Bundle();
16465            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16466            if (uidArr != null) {
16467                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16468            }
16469            if (replacing) {
16470                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16471            }
16472            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16473                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16474            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16475        }
16476    }
16477
16478   /*
16479     * Look at potentially valid container ids from processCids If package
16480     * information doesn't match the one on record or package scanning fails,
16481     * the cid is added to list of removeCids. We currently don't delete stale
16482     * containers.
16483     */
16484    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16485            boolean externalStorage) {
16486        ArrayList<String> pkgList = new ArrayList<String>();
16487        Set<AsecInstallArgs> keys = processCids.keySet();
16488
16489        for (AsecInstallArgs args : keys) {
16490            String codePath = processCids.get(args);
16491            if (DEBUG_SD_INSTALL)
16492                Log.i(TAG, "Loading container : " + args.cid);
16493            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16494            try {
16495                // Make sure there are no container errors first.
16496                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16497                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16498                            + " when installing from sdcard");
16499                    continue;
16500                }
16501                // Check code path here.
16502                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16503                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16504                            + " does not match one in settings " + codePath);
16505                    continue;
16506                }
16507                // Parse package
16508                int parseFlags = mDefParseFlags;
16509                if (args.isExternalAsec()) {
16510                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16511                }
16512                if (args.isFwdLocked()) {
16513                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16514                }
16515
16516                synchronized (mInstallLock) {
16517                    PackageParser.Package pkg = null;
16518                    try {
16519                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16520                    } catch (PackageManagerException e) {
16521                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16522                    }
16523                    // Scan the package
16524                    if (pkg != null) {
16525                        /*
16526                         * TODO why is the lock being held? doPostInstall is
16527                         * called in other places without the lock. This needs
16528                         * to be straightened out.
16529                         */
16530                        // writer
16531                        synchronized (mPackages) {
16532                            retCode = PackageManager.INSTALL_SUCCEEDED;
16533                            pkgList.add(pkg.packageName);
16534                            // Post process args
16535                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16536                                    pkg.applicationInfo.uid);
16537                        }
16538                    } else {
16539                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16540                    }
16541                }
16542
16543            } finally {
16544                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16545                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16546                }
16547            }
16548        }
16549        // writer
16550        synchronized (mPackages) {
16551            // If the platform SDK has changed since the last time we booted,
16552            // we need to re-grant app permission to catch any new ones that
16553            // appear. This is really a hack, and means that apps can in some
16554            // cases get permissions that the user didn't initially explicitly
16555            // allow... it would be nice to have some better way to handle
16556            // this situation.
16557            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16558                    : mSettings.getInternalVersion();
16559            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16560                    : StorageManager.UUID_PRIVATE_INTERNAL;
16561
16562            int updateFlags = UPDATE_PERMISSIONS_ALL;
16563            if (ver.sdkVersion != mSdkVersion) {
16564                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16565                        + mSdkVersion + "; regranting permissions for external");
16566                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16567            }
16568            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16569
16570            // Yay, everything is now upgraded
16571            ver.forceCurrent();
16572
16573            // can downgrade to reader
16574            // Persist settings
16575            mSettings.writeLPr();
16576        }
16577        // Send a broadcast to let everyone know we are done processing
16578        if (pkgList.size() > 0) {
16579            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16580        }
16581    }
16582
16583   /*
16584     * Utility method to unload a list of specified containers
16585     */
16586    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16587        // Just unmount all valid containers.
16588        for (AsecInstallArgs arg : cidArgs) {
16589            synchronized (mInstallLock) {
16590                arg.doPostDeleteLI(false);
16591           }
16592       }
16593   }
16594
16595    /*
16596     * Unload packages mounted on external media. This involves deleting package
16597     * data from internal structures, sending broadcasts about diabled packages,
16598     * gc'ing to free up references, unmounting all secure containers
16599     * corresponding to packages on external media, and posting a
16600     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16601     * that we always have to post this message if status has been requested no
16602     * matter what.
16603     */
16604    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16605            final boolean reportStatus) {
16606        if (DEBUG_SD_INSTALL)
16607            Log.i(TAG, "unloading media packages");
16608        ArrayList<String> pkgList = new ArrayList<String>();
16609        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16610        final Set<AsecInstallArgs> keys = processCids.keySet();
16611        for (AsecInstallArgs args : keys) {
16612            String pkgName = args.getPackageName();
16613            if (DEBUG_SD_INSTALL)
16614                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16615            // Delete package internally
16616            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16617            synchronized (mInstallLock) {
16618                boolean res = deletePackageLI(pkgName, null, false, null, null,
16619                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16620                if (res) {
16621                    pkgList.add(pkgName);
16622                } else {
16623                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16624                    failedList.add(args);
16625                }
16626            }
16627        }
16628
16629        // reader
16630        synchronized (mPackages) {
16631            // We didn't update the settings after removing each package;
16632            // write them now for all packages.
16633            mSettings.writeLPr();
16634        }
16635
16636        // We have to absolutely send UPDATED_MEDIA_STATUS only
16637        // after confirming that all the receivers processed the ordered
16638        // broadcast when packages get disabled, force a gc to clean things up.
16639        // and unload all the containers.
16640        if (pkgList.size() > 0) {
16641            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16642                    new IIntentReceiver.Stub() {
16643                public void performReceive(Intent intent, int resultCode, String data,
16644                        Bundle extras, boolean ordered, boolean sticky,
16645                        int sendingUser) throws RemoteException {
16646                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16647                            reportStatus ? 1 : 0, 1, keys);
16648                    mHandler.sendMessage(msg);
16649                }
16650            });
16651        } else {
16652            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16653                    keys);
16654            mHandler.sendMessage(msg);
16655        }
16656    }
16657
16658    private void loadPrivatePackages(final VolumeInfo vol) {
16659        mHandler.post(new Runnable() {
16660            @Override
16661            public void run() {
16662                loadPrivatePackagesInner(vol);
16663            }
16664        });
16665    }
16666
16667    private void loadPrivatePackagesInner(VolumeInfo vol) {
16668        final String volumeUuid = vol.fsUuid;
16669        if (TextUtils.isEmpty(volumeUuid)) {
16670            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16671            return;
16672        }
16673
16674        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16675        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16676
16677        final VersionInfo ver;
16678        final List<PackageSetting> packages;
16679        synchronized (mPackages) {
16680            ver = mSettings.findOrCreateVersion(volumeUuid);
16681            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16682        }
16683
16684        // TODO: introduce a new concept similar to "frozen" to prevent these
16685        // apps from being launched until after data has been fully reconciled
16686        for (PackageSetting ps : packages) {
16687            synchronized (mInstallLock) {
16688                final PackageParser.Package pkg;
16689                try {
16690                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16691                    loaded.add(pkg.applicationInfo);
16692
16693                } catch (PackageManagerException e) {
16694                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16695                }
16696
16697                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16698                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16699                }
16700            }
16701        }
16702
16703        // Reconcile app data for all started/unlocked users
16704        final UserManager um = mContext.getSystemService(UserManager.class);
16705        for (UserInfo user : um.getUsers()) {
16706            if (um.isUserUnlocked(user.id)) {
16707                reconcileAppsData(volumeUuid, user.id,
16708                        Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE);
16709            } else if (um.isUserRunning(user.id)) {
16710                reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE);
16711            } else {
16712                continue;
16713            }
16714        }
16715
16716        synchronized (mPackages) {
16717            int updateFlags = UPDATE_PERMISSIONS_ALL;
16718            if (ver.sdkVersion != mSdkVersion) {
16719                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16720                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16721                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16722            }
16723            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16724
16725            // Yay, everything is now upgraded
16726            ver.forceCurrent();
16727
16728            mSettings.writeLPr();
16729        }
16730
16731        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16732        sendResourcesChangedBroadcast(true, false, loaded, null);
16733    }
16734
16735    private void unloadPrivatePackages(final VolumeInfo vol) {
16736        mHandler.post(new Runnable() {
16737            @Override
16738            public void run() {
16739                unloadPrivatePackagesInner(vol);
16740            }
16741        });
16742    }
16743
16744    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16745        final String volumeUuid = vol.fsUuid;
16746        if (TextUtils.isEmpty(volumeUuid)) {
16747            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16748            return;
16749        }
16750
16751        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16752        synchronized (mInstallLock) {
16753        synchronized (mPackages) {
16754            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16755            for (PackageSetting ps : packages) {
16756                if (ps.pkg == null) continue;
16757
16758                final ApplicationInfo info = ps.pkg.applicationInfo;
16759                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16760                if (deletePackageLI(ps.name, null, false, null, null,
16761                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16762                    unloaded.add(info);
16763                } else {
16764                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16765                }
16766            }
16767
16768            mSettings.writeLPr();
16769        }
16770        }
16771
16772        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16773        sendResourcesChangedBroadcast(false, false, unloaded, null);
16774    }
16775
16776    /**
16777     * Examine all users present on given mounted volume, and destroy data
16778     * belonging to users that are no longer valid, or whose user ID has been
16779     * recycled.
16780     */
16781    private void reconcileUsers(String volumeUuid) {
16782        final File[] files = FileUtils
16783                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16784        for (File file : files) {
16785            if (!file.isDirectory()) continue;
16786
16787            final int userId;
16788            final UserInfo info;
16789            try {
16790                userId = Integer.parseInt(file.getName());
16791                info = sUserManager.getUserInfo(userId);
16792            } catch (NumberFormatException e) {
16793                Slog.w(TAG, "Invalid user directory " + file);
16794                continue;
16795            }
16796
16797            boolean destroyUser = false;
16798            if (info == null) {
16799                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16800                        + " because no matching user was found");
16801                destroyUser = true;
16802            } else {
16803                try {
16804                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16805                } catch (IOException e) {
16806                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16807                            + " because we failed to enforce serial number: " + e);
16808                    destroyUser = true;
16809                }
16810            }
16811
16812            if (destroyUser) {
16813                synchronized (mInstallLock) {
16814                    try {
16815                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16816                    } catch (InstallerException e) {
16817                        Slog.w(TAG, "Failed to clean up user dirs", e);
16818                    }
16819                }
16820            }
16821        }
16822
16823        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16824        final UserManager um = mContext.getSystemService(UserManager.class);
16825        for (UserInfo user : um.getUsers()) {
16826            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16827            if (userDir.exists()) continue;
16828
16829            try {
16830                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16831                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16832            } catch (IOException e) {
16833                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16834            }
16835        }
16836    }
16837
16838    private void assertPackageKnown(String volumeUuid, String packageName)
16839            throws PackageManagerException {
16840        synchronized (mPackages) {
16841            final PackageSetting ps = mSettings.mPackages.get(packageName);
16842            if (ps == null) {
16843                throw new PackageManagerException("Package " + packageName + " is unknown");
16844            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16845                throw new PackageManagerException(
16846                        "Package " + packageName + " found on unknown volume " + volumeUuid
16847                                + "; expected volume " + ps.volumeUuid);
16848            }
16849        }
16850    }
16851
16852    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16853            throws PackageManagerException {
16854        synchronized (mPackages) {
16855            final PackageSetting ps = mSettings.mPackages.get(packageName);
16856            if (ps == null) {
16857                throw new PackageManagerException("Package " + packageName + " is unknown");
16858            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16859                throw new PackageManagerException(
16860                        "Package " + packageName + " found on unknown volume " + volumeUuid
16861                                + "; expected volume " + ps.volumeUuid);
16862            } else if (!ps.getInstalled(userId)) {
16863                throw new PackageManagerException(
16864                        "Package " + packageName + " not installed for user " + userId);
16865            }
16866        }
16867    }
16868
16869    /**
16870     * Examine all apps present on given mounted volume, and destroy apps that
16871     * aren't expected, either due to uninstallation or reinstallation on
16872     * another volume.
16873     */
16874    private void reconcileApps(String volumeUuid) {
16875        final File[] files = FileUtils
16876                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16877        for (File file : files) {
16878            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16879                    && !PackageInstallerService.isStageName(file.getName());
16880            if (!isPackage) {
16881                // Ignore entries which are not packages
16882                continue;
16883            }
16884
16885            try {
16886                final PackageLite pkg = PackageParser.parsePackageLite(file,
16887                        PackageParser.PARSE_MUST_BE_APK);
16888                assertPackageKnown(volumeUuid, pkg.packageName);
16889
16890            } catch (PackageParserException | PackageManagerException e) {
16891                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16892                synchronized (mInstallLock) {
16893                    removeCodePathLI(file);
16894                }
16895            }
16896        }
16897    }
16898
16899    /**
16900     * Reconcile all app data for the given user.
16901     * <p>
16902     * Verifies that directories exist and that ownership and labeling is
16903     * correct for all installed apps on all mounted volumes.
16904     */
16905    void reconcileAppsData(int userId, @StorageFlags int flags) {
16906        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16907        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16908            final String volumeUuid = vol.getFsUuid();
16909            reconcileAppsData(volumeUuid, userId, flags);
16910        }
16911    }
16912
16913    /**
16914     * Reconcile all app data on given mounted volume.
16915     * <p>
16916     * Destroys app data that isn't expected, either due to uninstallation or
16917     * reinstallation on another volume.
16918     * <p>
16919     * Verifies that directories exist and that ownership and labeling is
16920     * correct for all installed apps.
16921     */
16922    private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) {
16923        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
16924                + Integer.toHexString(flags));
16925
16926        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
16927        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
16928
16929        boolean restoreconNeeded = false;
16930
16931        // First look for stale data that doesn't belong, and check if things
16932        // have changed since we did our last restorecon
16933        if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16934            if (!isUserKeyUnlocked(userId)) {
16935                throw new RuntimeException(
16936                        "Yikes, someone asked us to reconcile CE storage while " + userId
16937                                + " was still locked; this would have caused massive data loss!");
16938            }
16939
16940            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
16941
16942            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
16943            for (File file : files) {
16944                final String packageName = file.getName();
16945                try {
16946                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16947                } catch (PackageManagerException e) {
16948                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16949                    synchronized (mInstallLock) {
16950                        destroyAppDataLI(volumeUuid, packageName, userId,
16951                                Installer.FLAG_CE_STORAGE);
16952                    }
16953                }
16954            }
16955        }
16956        if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16957            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
16958
16959            final File[] files = FileUtils.listFilesOrEmpty(deDir);
16960            for (File file : files) {
16961                final String packageName = file.getName();
16962                try {
16963                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16964                } catch (PackageManagerException e) {
16965                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16966                    synchronized (mInstallLock) {
16967                        destroyAppDataLI(volumeUuid, packageName, userId,
16968                                Installer.FLAG_DE_STORAGE);
16969                    }
16970                }
16971            }
16972        }
16973
16974        // Ensure that data directories are ready to roll for all packages
16975        // installed for this volume and user
16976        final List<PackageSetting> packages;
16977        synchronized (mPackages) {
16978            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16979        }
16980        int preparedCount = 0;
16981        for (PackageSetting ps : packages) {
16982            final String packageName = ps.name;
16983            if (ps.pkg == null) {
16984                Slog.w(TAG, "Odd, missing scanned package " + packageName);
16985                // TODO: might be due to legacy ASEC apps; we should circle back
16986                // and reconcile again once they're scanned
16987                continue;
16988            }
16989
16990            if (ps.getInstalled(userId)) {
16991                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
16992                preparedCount++;
16993            }
16994        }
16995
16996        if (restoreconNeeded) {
16997            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16998                SELinuxMMAC.setRestoreconDone(ceDir);
16999            }
17000            if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
17001                SELinuxMMAC.setRestoreconDone(deDir);
17002            }
17003        }
17004
17005        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17006                + " packages; restoreconNeeded was " + restoreconNeeded);
17007    }
17008
17009    /**
17010     * Prepare app data for the given app just after it was installed or
17011     * upgraded. This method carefully only touches users that it's installed
17012     * for, and it forces a restorecon to handle any seinfo changes.
17013     * <p>
17014     * Verifies that directories exist and that ownership and labeling is
17015     * correct for all installed apps. If there is an ownership mismatch, it
17016     * will try recovering system apps by wiping data; third-party app data is
17017     * left intact.
17018     */
17019    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17020        final PackageSetting ps;
17021        synchronized (mPackages) {
17022            ps = mSettings.mPackages.get(pkg.packageName);
17023        }
17024
17025        final UserManager um = mContext.getSystemService(UserManager.class);
17026        for (UserInfo user : um.getUsers()) {
17027            final int flags;
17028            if (um.isUserUnlocked(user.id)) {
17029                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
17030            } else if (um.isUserRunning(user.id)) {
17031                flags = Installer.FLAG_DE_STORAGE;
17032            } else {
17033                continue;
17034            }
17035
17036            if (ps.getInstalled(user.id)) {
17037                // Whenever an app changes, force a restorecon of its data
17038                // TODO: when user data is locked, mark that we're still dirty
17039                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17040            }
17041        }
17042    }
17043
17044    /**
17045     * Prepare app data for the given app.
17046     * <p>
17047     * Verifies that directories exist and that ownership and labeling is
17048     * correct for all installed apps. If there is an ownership mismatch, this
17049     * will try recovering system apps by wiping data; third-party app data is
17050     * left intact.
17051     */
17052    private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags,
17053            PackageParser.Package pkg, boolean restoreconNeeded) {
17054        if (DEBUG_APP_DATA) {
17055            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17056                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17057        }
17058
17059        final String packageName = pkg.packageName;
17060        final ApplicationInfo app = pkg.applicationInfo;
17061        final int appId = UserHandle.getAppId(app.uid);
17062
17063        Preconditions.checkNotNull(app.seinfo);
17064
17065        synchronized (mInstallLock) {
17066            try {
17067                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17068                        appId, app.seinfo, app.targetSdkVersion);
17069            } catch (InstallerException e) {
17070                if (app.isSystemApp()) {
17071                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17072                            + ", but trying to recover: " + e);
17073                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17074                    try {
17075                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17076                                appId, app.seinfo, app.targetSdkVersion);
17077                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17078                    } catch (InstallerException e2) {
17079                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17080                    }
17081                } else {
17082                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17083                }
17084            }
17085
17086            if (restoreconNeeded) {
17087                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17088            }
17089
17090            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17091                // Create a native library symlink only if we have native libraries
17092                // and if the native libraries are 32 bit libraries. We do not provide
17093                // this symlink for 64 bit libraries.
17094                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17095                    final String nativeLibPath = app.nativeLibraryDir;
17096                    try {
17097                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17098                                nativeLibPath, userId);
17099                    } catch (InstallerException e) {
17100                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17101                    }
17102                }
17103            }
17104        }
17105    }
17106
17107    private void unfreezePackage(String packageName) {
17108        synchronized (mPackages) {
17109            final PackageSetting ps = mSettings.mPackages.get(packageName);
17110            if (ps != null) {
17111                ps.frozen = false;
17112            }
17113        }
17114    }
17115
17116    @Override
17117    public int movePackage(final String packageName, final String volumeUuid) {
17118        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17119
17120        final int moveId = mNextMoveId.getAndIncrement();
17121        mHandler.post(new Runnable() {
17122            @Override
17123            public void run() {
17124                try {
17125                    movePackageInternal(packageName, volumeUuid, moveId);
17126                } catch (PackageManagerException e) {
17127                    Slog.w(TAG, "Failed to move " + packageName, e);
17128                    mMoveCallbacks.notifyStatusChanged(moveId,
17129                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17130                }
17131            }
17132        });
17133        return moveId;
17134    }
17135
17136    private void movePackageInternal(final String packageName, final String volumeUuid,
17137            final int moveId) throws PackageManagerException {
17138        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17139        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17140        final PackageManager pm = mContext.getPackageManager();
17141
17142        final boolean currentAsec;
17143        final String currentVolumeUuid;
17144        final File codeFile;
17145        final String installerPackageName;
17146        final String packageAbiOverride;
17147        final int appId;
17148        final String seinfo;
17149        final String label;
17150        final int targetSdkVersion;
17151
17152        // reader
17153        synchronized (mPackages) {
17154            final PackageParser.Package pkg = mPackages.get(packageName);
17155            final PackageSetting ps = mSettings.mPackages.get(packageName);
17156            if (pkg == null || ps == null) {
17157                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17158            }
17159
17160            if (pkg.applicationInfo.isSystemApp()) {
17161                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17162                        "Cannot move system application");
17163            }
17164
17165            if (pkg.applicationInfo.isExternalAsec()) {
17166                currentAsec = true;
17167                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17168            } else if (pkg.applicationInfo.isForwardLocked()) {
17169                currentAsec = true;
17170                currentVolumeUuid = "forward_locked";
17171            } else {
17172                currentAsec = false;
17173                currentVolumeUuid = ps.volumeUuid;
17174
17175                final File probe = new File(pkg.codePath);
17176                final File probeOat = new File(probe, "oat");
17177                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17178                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17179                            "Move only supported for modern cluster style installs");
17180                }
17181            }
17182
17183            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17184                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17185                        "Package already moved to " + volumeUuid);
17186            }
17187
17188            if (ps.frozen) {
17189                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17190                        "Failed to move already frozen package");
17191            }
17192            ps.frozen = true;
17193
17194            codeFile = new File(pkg.codePath);
17195            installerPackageName = ps.installerPackageName;
17196            packageAbiOverride = ps.cpuAbiOverrideString;
17197            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17198            seinfo = pkg.applicationInfo.seinfo;
17199            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17200            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17201        }
17202
17203        // Now that we're guarded by frozen state, kill app during move
17204        final long token = Binder.clearCallingIdentity();
17205        try {
17206            killApplication(packageName, appId, "move pkg");
17207        } finally {
17208            Binder.restoreCallingIdentity(token);
17209        }
17210
17211        final Bundle extras = new Bundle();
17212        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17213        extras.putString(Intent.EXTRA_TITLE, label);
17214        mMoveCallbacks.notifyCreated(moveId, extras);
17215
17216        int installFlags;
17217        final boolean moveCompleteApp;
17218        final File measurePath;
17219
17220        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17221            installFlags = INSTALL_INTERNAL;
17222            moveCompleteApp = !currentAsec;
17223            measurePath = Environment.getDataAppDirectory(volumeUuid);
17224        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17225            installFlags = INSTALL_EXTERNAL;
17226            moveCompleteApp = false;
17227            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17228        } else {
17229            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17230            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17231                    || !volume.isMountedWritable()) {
17232                unfreezePackage(packageName);
17233                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17234                        "Move location not mounted private volume");
17235            }
17236
17237            Preconditions.checkState(!currentAsec);
17238
17239            installFlags = INSTALL_INTERNAL;
17240            moveCompleteApp = true;
17241            measurePath = Environment.getDataAppDirectory(volumeUuid);
17242        }
17243
17244        final PackageStats stats = new PackageStats(null, -1);
17245        synchronized (mInstaller) {
17246            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17247                unfreezePackage(packageName);
17248                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17249                        "Failed to measure package size");
17250            }
17251        }
17252
17253        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17254                + stats.dataSize);
17255
17256        final long startFreeBytes = measurePath.getFreeSpace();
17257        final long sizeBytes;
17258        if (moveCompleteApp) {
17259            sizeBytes = stats.codeSize + stats.dataSize;
17260        } else {
17261            sizeBytes = stats.codeSize;
17262        }
17263
17264        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17265            unfreezePackage(packageName);
17266            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17267                    "Not enough free space to move");
17268        }
17269
17270        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17271
17272        final CountDownLatch installedLatch = new CountDownLatch(1);
17273        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17274            @Override
17275            public void onUserActionRequired(Intent intent) throws RemoteException {
17276                throw new IllegalStateException();
17277            }
17278
17279            @Override
17280            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17281                    Bundle extras) throws RemoteException {
17282                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17283                        + PackageManager.installStatusToString(returnCode, msg));
17284
17285                installedLatch.countDown();
17286
17287                // Regardless of success or failure of the move operation,
17288                // always unfreeze the package
17289                unfreezePackage(packageName);
17290
17291                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17292                switch (status) {
17293                    case PackageInstaller.STATUS_SUCCESS:
17294                        mMoveCallbacks.notifyStatusChanged(moveId,
17295                                PackageManager.MOVE_SUCCEEDED);
17296                        break;
17297                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17298                        mMoveCallbacks.notifyStatusChanged(moveId,
17299                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17300                        break;
17301                    default:
17302                        mMoveCallbacks.notifyStatusChanged(moveId,
17303                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17304                        break;
17305                }
17306            }
17307        };
17308
17309        final MoveInfo move;
17310        if (moveCompleteApp) {
17311            // Kick off a thread to report progress estimates
17312            new Thread() {
17313                @Override
17314                public void run() {
17315                    while (true) {
17316                        try {
17317                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17318                                break;
17319                            }
17320                        } catch (InterruptedException ignored) {
17321                        }
17322
17323                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17324                        final int progress = 10 + (int) MathUtils.constrain(
17325                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17326                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17327                    }
17328                }
17329            }.start();
17330
17331            final String dataAppName = codeFile.getName();
17332            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17333                    dataAppName, appId, seinfo, targetSdkVersion);
17334        } else {
17335            move = null;
17336        }
17337
17338        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17339
17340        final Message msg = mHandler.obtainMessage(INIT_COPY);
17341        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17342        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17343                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17344        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17345        msg.obj = params;
17346
17347        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17348                System.identityHashCode(msg.obj));
17349        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17350                System.identityHashCode(msg.obj));
17351
17352        mHandler.sendMessage(msg);
17353    }
17354
17355    @Override
17356    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17357        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17358
17359        final int realMoveId = mNextMoveId.getAndIncrement();
17360        final Bundle extras = new Bundle();
17361        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17362        mMoveCallbacks.notifyCreated(realMoveId, extras);
17363
17364        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17365            @Override
17366            public void onCreated(int moveId, Bundle extras) {
17367                // Ignored
17368            }
17369
17370            @Override
17371            public void onStatusChanged(int moveId, int status, long estMillis) {
17372                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17373            }
17374        };
17375
17376        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17377        storage.setPrimaryStorageUuid(volumeUuid, callback);
17378        return realMoveId;
17379    }
17380
17381    @Override
17382    public int getMoveStatus(int moveId) {
17383        mContext.enforceCallingOrSelfPermission(
17384                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17385        return mMoveCallbacks.mLastStatus.get(moveId);
17386    }
17387
17388    @Override
17389    public void registerMoveCallback(IPackageMoveObserver callback) {
17390        mContext.enforceCallingOrSelfPermission(
17391                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17392        mMoveCallbacks.register(callback);
17393    }
17394
17395    @Override
17396    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17397        mContext.enforceCallingOrSelfPermission(
17398                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17399        mMoveCallbacks.unregister(callback);
17400    }
17401
17402    @Override
17403    public boolean setInstallLocation(int loc) {
17404        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17405                null);
17406        if (getInstallLocation() == loc) {
17407            return true;
17408        }
17409        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17410                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17411            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17412                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17413            return true;
17414        }
17415        return false;
17416   }
17417
17418    @Override
17419    public int getInstallLocation() {
17420        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17421                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17422                PackageHelper.APP_INSTALL_AUTO);
17423    }
17424
17425    /** Called by UserManagerService */
17426    void cleanUpUser(UserManagerService userManager, int userHandle) {
17427        synchronized (mPackages) {
17428            mDirtyUsers.remove(userHandle);
17429            mUserNeedsBadging.delete(userHandle);
17430            mSettings.removeUserLPw(userHandle);
17431            mPendingBroadcasts.remove(userHandle);
17432            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17433        }
17434        synchronized (mInstallLock) {
17435            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17436            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17437                final String volumeUuid = vol.getFsUuid();
17438                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17439                try {
17440                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17441                } catch (InstallerException e) {
17442                    Slog.w(TAG, "Failed to remove user data", e);
17443                }
17444            }
17445            synchronized (mPackages) {
17446                removeUnusedPackagesLILPw(userManager, userHandle);
17447            }
17448        }
17449    }
17450
17451    /**
17452     * We're removing userHandle and would like to remove any downloaded packages
17453     * that are no longer in use by any other user.
17454     * @param userHandle the user being removed
17455     */
17456    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17457        final boolean DEBUG_CLEAN_APKS = false;
17458        int [] users = userManager.getUserIds();
17459        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17460        while (psit.hasNext()) {
17461            PackageSetting ps = psit.next();
17462            if (ps.pkg == null) {
17463                continue;
17464            }
17465            final String packageName = ps.pkg.packageName;
17466            // Skip over if system app
17467            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17468                continue;
17469            }
17470            if (DEBUG_CLEAN_APKS) {
17471                Slog.i(TAG, "Checking package " + packageName);
17472            }
17473            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17474            if (keep) {
17475                if (DEBUG_CLEAN_APKS) {
17476                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17477                }
17478            } else {
17479                for (int i = 0; i < users.length; i++) {
17480                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17481                        keep = true;
17482                        if (DEBUG_CLEAN_APKS) {
17483                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17484                                    + users[i]);
17485                        }
17486                        break;
17487                    }
17488                }
17489            }
17490            if (!keep) {
17491                if (DEBUG_CLEAN_APKS) {
17492                    Slog.i(TAG, "  Removing package " + packageName);
17493                }
17494                mHandler.post(new Runnable() {
17495                    public void run() {
17496                        deletePackageX(packageName, userHandle, 0);
17497                    } //end run
17498                });
17499            }
17500        }
17501    }
17502
17503    /** Called by UserManagerService */
17504    void createNewUser(int userHandle) {
17505        synchronized (mInstallLock) {
17506            try {
17507                mInstaller.createUserConfig(userHandle);
17508            } catch (InstallerException e) {
17509                Slog.w(TAG, "Failed to create user config", e);
17510            }
17511            mSettings.createNewUserLI(this, mInstaller, userHandle);
17512        }
17513        synchronized (mPackages) {
17514            applyFactoryDefaultBrowserLPw(userHandle);
17515            primeDomainVerificationsLPw(userHandle);
17516        }
17517    }
17518
17519    void newUserCreated(final int userHandle) {
17520        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17521        // If permission review for legacy apps is required, we represent
17522        // dagerous permissions for such apps as always granted runtime
17523        // permissions to keep per user flag state whether review is needed.
17524        // Hence, if a new user is added we have to propagate dangerous
17525        // permission grants for these legacy apps.
17526        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17527            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17528                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17529        }
17530    }
17531
17532    @Override
17533    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17534        mContext.enforceCallingOrSelfPermission(
17535                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17536                "Only package verification agents can read the verifier device identity");
17537
17538        synchronized (mPackages) {
17539            return mSettings.getVerifierDeviceIdentityLPw();
17540        }
17541    }
17542
17543    @Override
17544    public void setPermissionEnforced(String permission, boolean enforced) {
17545        // TODO: Now that we no longer change GID for storage, this should to away.
17546        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17547                "setPermissionEnforced");
17548        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17549            synchronized (mPackages) {
17550                if (mSettings.mReadExternalStorageEnforced == null
17551                        || mSettings.mReadExternalStorageEnforced != enforced) {
17552                    mSettings.mReadExternalStorageEnforced = enforced;
17553                    mSettings.writeLPr();
17554                }
17555            }
17556            // kill any non-foreground processes so we restart them and
17557            // grant/revoke the GID.
17558            final IActivityManager am = ActivityManagerNative.getDefault();
17559            if (am != null) {
17560                final long token = Binder.clearCallingIdentity();
17561                try {
17562                    am.killProcessesBelowForeground("setPermissionEnforcement");
17563                } catch (RemoteException e) {
17564                } finally {
17565                    Binder.restoreCallingIdentity(token);
17566                }
17567            }
17568        } else {
17569            throw new IllegalArgumentException("No selective enforcement for " + permission);
17570        }
17571    }
17572
17573    @Override
17574    @Deprecated
17575    public boolean isPermissionEnforced(String permission) {
17576        return true;
17577    }
17578
17579    @Override
17580    public boolean isStorageLow() {
17581        final long token = Binder.clearCallingIdentity();
17582        try {
17583            final DeviceStorageMonitorInternal
17584                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17585            if (dsm != null) {
17586                return dsm.isMemoryLow();
17587            } else {
17588                return false;
17589            }
17590        } finally {
17591            Binder.restoreCallingIdentity(token);
17592        }
17593    }
17594
17595    @Override
17596    public IPackageInstaller getPackageInstaller() {
17597        return mInstallerService;
17598    }
17599
17600    private boolean userNeedsBadging(int userId) {
17601        int index = mUserNeedsBadging.indexOfKey(userId);
17602        if (index < 0) {
17603            final UserInfo userInfo;
17604            final long token = Binder.clearCallingIdentity();
17605            try {
17606                userInfo = sUserManager.getUserInfo(userId);
17607            } finally {
17608                Binder.restoreCallingIdentity(token);
17609            }
17610            final boolean b;
17611            if (userInfo != null && userInfo.isManagedProfile()) {
17612                b = true;
17613            } else {
17614                b = false;
17615            }
17616            mUserNeedsBadging.put(userId, b);
17617            return b;
17618        }
17619        return mUserNeedsBadging.valueAt(index);
17620    }
17621
17622    @Override
17623    public KeySet getKeySetByAlias(String packageName, String alias) {
17624        if (packageName == null || alias == null) {
17625            return null;
17626        }
17627        synchronized(mPackages) {
17628            final PackageParser.Package pkg = mPackages.get(packageName);
17629            if (pkg == null) {
17630                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17631                throw new IllegalArgumentException("Unknown package: " + packageName);
17632            }
17633            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17634            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17635        }
17636    }
17637
17638    @Override
17639    public KeySet getSigningKeySet(String packageName) {
17640        if (packageName == null) {
17641            return null;
17642        }
17643        synchronized(mPackages) {
17644            final PackageParser.Package pkg = mPackages.get(packageName);
17645            if (pkg == null) {
17646                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17647                throw new IllegalArgumentException("Unknown package: " + packageName);
17648            }
17649            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17650                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17651                throw new SecurityException("May not access signing KeySet of other apps.");
17652            }
17653            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17654            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17655        }
17656    }
17657
17658    @Override
17659    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17660        if (packageName == null || ks == null) {
17661            return false;
17662        }
17663        synchronized(mPackages) {
17664            final PackageParser.Package pkg = mPackages.get(packageName);
17665            if (pkg == null) {
17666                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17667                throw new IllegalArgumentException("Unknown package: " + packageName);
17668            }
17669            IBinder ksh = ks.getToken();
17670            if (ksh instanceof KeySetHandle) {
17671                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17672                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17673            }
17674            return false;
17675        }
17676    }
17677
17678    @Override
17679    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17680        if (packageName == null || ks == null) {
17681            return false;
17682        }
17683        synchronized(mPackages) {
17684            final PackageParser.Package pkg = mPackages.get(packageName);
17685            if (pkg == null) {
17686                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17687                throw new IllegalArgumentException("Unknown package: " + packageName);
17688            }
17689            IBinder ksh = ks.getToken();
17690            if (ksh instanceof KeySetHandle) {
17691                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17692                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17693            }
17694            return false;
17695        }
17696    }
17697
17698    private void deletePackageIfUnusedLPr(final String packageName) {
17699        PackageSetting ps = mSettings.mPackages.get(packageName);
17700        if (ps == null) {
17701            return;
17702        }
17703        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17704            // TODO Implement atomic delete if package is unused
17705            // It is currently possible that the package will be deleted even if it is installed
17706            // after this method returns.
17707            mHandler.post(new Runnable() {
17708                public void run() {
17709                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17710                }
17711            });
17712        }
17713    }
17714
17715    /**
17716     * Check and throw if the given before/after packages would be considered a
17717     * downgrade.
17718     */
17719    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17720            throws PackageManagerException {
17721        if (after.versionCode < before.mVersionCode) {
17722            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17723                    "Update version code " + after.versionCode + " is older than current "
17724                    + before.mVersionCode);
17725        } else if (after.versionCode == before.mVersionCode) {
17726            if (after.baseRevisionCode < before.baseRevisionCode) {
17727                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17728                        "Update base revision code " + after.baseRevisionCode
17729                        + " is older than current " + before.baseRevisionCode);
17730            }
17731
17732            if (!ArrayUtils.isEmpty(after.splitNames)) {
17733                for (int i = 0; i < after.splitNames.length; i++) {
17734                    final String splitName = after.splitNames[i];
17735                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17736                    if (j != -1) {
17737                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17738                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17739                                    "Update split " + splitName + " revision code "
17740                                    + after.splitRevisionCodes[i] + " is older than current "
17741                                    + before.splitRevisionCodes[j]);
17742                        }
17743                    }
17744                }
17745            }
17746        }
17747    }
17748
17749    private static class MoveCallbacks extends Handler {
17750        private static final int MSG_CREATED = 1;
17751        private static final int MSG_STATUS_CHANGED = 2;
17752
17753        private final RemoteCallbackList<IPackageMoveObserver>
17754                mCallbacks = new RemoteCallbackList<>();
17755
17756        private final SparseIntArray mLastStatus = new SparseIntArray();
17757
17758        public MoveCallbacks(Looper looper) {
17759            super(looper);
17760        }
17761
17762        public void register(IPackageMoveObserver callback) {
17763            mCallbacks.register(callback);
17764        }
17765
17766        public void unregister(IPackageMoveObserver callback) {
17767            mCallbacks.unregister(callback);
17768        }
17769
17770        @Override
17771        public void handleMessage(Message msg) {
17772            final SomeArgs args = (SomeArgs) msg.obj;
17773            final int n = mCallbacks.beginBroadcast();
17774            for (int i = 0; i < n; i++) {
17775                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17776                try {
17777                    invokeCallback(callback, msg.what, args);
17778                } catch (RemoteException ignored) {
17779                }
17780            }
17781            mCallbacks.finishBroadcast();
17782            args.recycle();
17783        }
17784
17785        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17786                throws RemoteException {
17787            switch (what) {
17788                case MSG_CREATED: {
17789                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17790                    break;
17791                }
17792                case MSG_STATUS_CHANGED: {
17793                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17794                    break;
17795                }
17796            }
17797        }
17798
17799        private void notifyCreated(int moveId, Bundle extras) {
17800            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17801
17802            final SomeArgs args = SomeArgs.obtain();
17803            args.argi1 = moveId;
17804            args.arg2 = extras;
17805            obtainMessage(MSG_CREATED, args).sendToTarget();
17806        }
17807
17808        private void notifyStatusChanged(int moveId, int status) {
17809            notifyStatusChanged(moveId, status, -1);
17810        }
17811
17812        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17813            Slog.v(TAG, "Move " + moveId + " status " + status);
17814
17815            final SomeArgs args = SomeArgs.obtain();
17816            args.argi1 = moveId;
17817            args.argi2 = status;
17818            args.arg3 = estMillis;
17819            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17820
17821            synchronized (mLastStatus) {
17822                mLastStatus.put(moveId, status);
17823            }
17824        }
17825    }
17826
17827    private final static class OnPermissionChangeListeners extends Handler {
17828        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17829
17830        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17831                new RemoteCallbackList<>();
17832
17833        public OnPermissionChangeListeners(Looper looper) {
17834            super(looper);
17835        }
17836
17837        @Override
17838        public void handleMessage(Message msg) {
17839            switch (msg.what) {
17840                case MSG_ON_PERMISSIONS_CHANGED: {
17841                    final int uid = msg.arg1;
17842                    handleOnPermissionsChanged(uid);
17843                } break;
17844            }
17845        }
17846
17847        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17848            mPermissionListeners.register(listener);
17849
17850        }
17851
17852        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17853            mPermissionListeners.unregister(listener);
17854        }
17855
17856        public void onPermissionsChanged(int uid) {
17857            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17858                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17859            }
17860        }
17861
17862        private void handleOnPermissionsChanged(int uid) {
17863            final int count = mPermissionListeners.beginBroadcast();
17864            try {
17865                for (int i = 0; i < count; i++) {
17866                    IOnPermissionsChangeListener callback = mPermissionListeners
17867                            .getBroadcastItem(i);
17868                    try {
17869                        callback.onPermissionsChanged(uid);
17870                    } catch (RemoteException e) {
17871                        Log.e(TAG, "Permission listener is dead", e);
17872                    }
17873                }
17874            } finally {
17875                mPermissionListeners.finishBroadcast();
17876            }
17877        }
17878    }
17879
17880    private class PackageManagerInternalImpl extends PackageManagerInternal {
17881        @Override
17882        public void setLocationPackagesProvider(PackagesProvider provider) {
17883            synchronized (mPackages) {
17884                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17885            }
17886        }
17887
17888        @Override
17889        public void setImePackagesProvider(PackagesProvider provider) {
17890            synchronized (mPackages) {
17891                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17892            }
17893        }
17894
17895        @Override
17896        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17897            synchronized (mPackages) {
17898                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17899            }
17900        }
17901
17902        @Override
17903        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17904            synchronized (mPackages) {
17905                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17906            }
17907        }
17908
17909        @Override
17910        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17911            synchronized (mPackages) {
17912                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17913            }
17914        }
17915
17916        @Override
17917        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17918            synchronized (mPackages) {
17919                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17920            }
17921        }
17922
17923        @Override
17924        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17925            synchronized (mPackages) {
17926                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17927            }
17928        }
17929
17930        @Override
17931        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17932            synchronized (mPackages) {
17933                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17934                        packageName, userId);
17935            }
17936        }
17937
17938        @Override
17939        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17940            synchronized (mPackages) {
17941                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17942                        packageName, userId);
17943            }
17944        }
17945
17946        @Override
17947        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17948            synchronized (mPackages) {
17949                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17950                        packageName, userId);
17951            }
17952        }
17953
17954        @Override
17955        public void setKeepUninstalledPackages(final List<String> packageList) {
17956            Preconditions.checkNotNull(packageList);
17957            List<String> removedFromList = null;
17958            synchronized (mPackages) {
17959                if (mKeepUninstalledPackages != null) {
17960                    final int packagesCount = mKeepUninstalledPackages.size();
17961                    for (int i = 0; i < packagesCount; i++) {
17962                        String oldPackage = mKeepUninstalledPackages.get(i);
17963                        if (packageList != null && packageList.contains(oldPackage)) {
17964                            continue;
17965                        }
17966                        if (removedFromList == null) {
17967                            removedFromList = new ArrayList<>();
17968                        }
17969                        removedFromList.add(oldPackage);
17970                    }
17971                }
17972                mKeepUninstalledPackages = new ArrayList<>(packageList);
17973                if (removedFromList != null) {
17974                    final int removedCount = removedFromList.size();
17975                    for (int i = 0; i < removedCount; i++) {
17976                        deletePackageIfUnusedLPr(removedFromList.get(i));
17977                    }
17978                }
17979            }
17980        }
17981
17982        @Override
17983        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17984            synchronized (mPackages) {
17985                // If we do not support permission review, done.
17986                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17987                    return false;
17988                }
17989
17990                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17991                if (packageSetting == null) {
17992                    return false;
17993                }
17994
17995                // Permission review applies only to apps not supporting the new permission model.
17996                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17997                    return false;
17998                }
17999
18000                // Legacy apps have the permission and get user consent on launch.
18001                PermissionsState permissionsState = packageSetting.getPermissionsState();
18002                return permissionsState.isPermissionReviewRequired(userId);
18003            }
18004        }
18005    }
18006
18007    @Override
18008    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18009        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18010        synchronized (mPackages) {
18011            final long identity = Binder.clearCallingIdentity();
18012            try {
18013                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18014                        packageNames, userId);
18015            } finally {
18016                Binder.restoreCallingIdentity(identity);
18017            }
18018        }
18019    }
18020
18021    private static void enforceSystemOrPhoneCaller(String tag) {
18022        int callingUid = Binder.getCallingUid();
18023        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18024            throw new SecurityException(
18025                    "Cannot call " + tag + " from UID " + callingUid);
18026        }
18027    }
18028}
18029