PackageManagerService.java revision 47f7108c1270a9e81d9560b6b0570c659bb93a71
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.Package;
143import android.content.pm.PackageParser.PackageLite;
144import android.content.pm.PackageParser.PackageParserException;
145import android.content.pm.PackageStats;
146import android.content.pm.PackageUserState;
147import android.content.pm.ParceledListSlice;
148import android.content.pm.PermissionGroupInfo;
149import android.content.pm.PermissionInfo;
150import android.content.pm.ProviderInfo;
151import android.content.pm.ResolveInfo;
152import android.content.pm.ServiceInfo;
153import android.content.pm.Signature;
154import android.content.pm.UserInfo;
155import android.content.pm.VerificationParams;
156import android.content.pm.VerifierDeviceIdentity;
157import android.content.pm.VerifierInfo;
158import android.content.res.Resources;
159import android.graphics.Bitmap;
160import android.hardware.display.DisplayManager;
161import android.net.Uri;
162import android.os.Binder;
163import android.os.Build;
164import android.os.Bundle;
165import android.os.Debug;
166import android.os.Environment;
167import android.os.Environment.UserEnvironment;
168import android.os.FileUtils;
169import android.os.Handler;
170import android.os.IBinder;
171import android.os.Looper;
172import android.os.Message;
173import android.os.Parcel;
174import android.os.ParcelFileDescriptor;
175import android.os.Process;
176import android.os.RemoteCallbackList;
177import android.os.RemoteException;
178import android.os.ResultReceiver;
179import android.os.SELinux;
180import android.os.ServiceManager;
181import android.os.SystemClock;
182import android.os.SystemProperties;
183import android.os.Trace;
184import android.os.UserHandle;
185import android.os.UserManager;
186import android.os.storage.IMountService;
187import android.os.storage.MountServiceInternal;
188import android.os.storage.StorageEventListener;
189import android.os.storage.StorageManager;
190import android.os.storage.VolumeInfo;
191import android.os.storage.VolumeRecord;
192import android.security.KeyStore;
193import android.security.SystemKeyStore;
194import android.system.ErrnoException;
195import android.system.Os;
196import android.text.TextUtils;
197import android.text.format.DateUtils;
198import android.util.ArrayMap;
199import android.util.ArraySet;
200import android.util.AtomicFile;
201import android.util.DisplayMetrics;
202import android.util.EventLog;
203import android.util.ExceptionUtils;
204import android.util.Log;
205import android.util.LogPrinter;
206import android.util.MathUtils;
207import android.util.PrintStreamPrinter;
208import android.util.Slog;
209import android.util.SparseArray;
210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
212import android.util.Xml;
213import android.view.Display;
214
215import com.android.internal.R;
216import com.android.internal.annotations.GuardedBy;
217import com.android.internal.app.IMediaContainerService;
218import com.android.internal.app.ResolverActivity;
219import com.android.internal.content.NativeLibraryHelper;
220import com.android.internal.content.PackageHelper;
221import com.android.internal.os.IParcelFileDescriptorFactory;
222import com.android.internal.os.InstallerConnection.InstallerException;
223import com.android.internal.os.SomeArgs;
224import com.android.internal.os.Zygote;
225import com.android.internal.util.ArrayUtils;
226import com.android.internal.util.FastPrintWriter;
227import com.android.internal.util.FastXmlSerializer;
228import com.android.internal.util.IndentingPrintWriter;
229import com.android.internal.util.Preconditions;
230import com.android.internal.util.XmlUtils;
231import com.android.server.EventLogTags;
232import com.android.server.FgThread;
233import com.android.server.IntentResolver;
234import com.android.server.LocalServices;
235import com.android.server.ServiceThread;
236import com.android.server.SystemConfig;
237import com.android.server.Watchdog;
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.PrintStream;
267import java.io.PrintWriter;
268import java.nio.charset.StandardCharsets;
269import java.security.MessageDigest;
270import java.security.NoSuchAlgorithmException;
271import java.security.PublicKey;
272import java.security.cert.CertificateEncodingException;
273import java.security.cert.CertificateException;
274import java.text.SimpleDateFormat;
275import java.util.ArrayList;
276import java.util.Arrays;
277import java.util.Collection;
278import java.util.Collections;
279import java.util.Comparator;
280import java.util.Date;
281import java.util.HashSet;
282import java.util.Iterator;
283import java.util.List;
284import java.util.Map;
285import java.util.Objects;
286import java.util.Set;
287import java.util.concurrent.CountDownLatch;
288import java.util.concurrent.TimeUnit;
289import java.util.concurrent.atomic.AtomicBoolean;
290import java.util.concurrent.atomic.AtomicInteger;
291import java.util.concurrent.atomic.AtomicLong;
292
293/**
294 * Keep track of all those .apks everywhere.
295 *
296 * This is very central to the platform's security; please run the unit
297 * tests whenever making modifications here:
298 *
299runtest -c android.content.pm.PackageManagerTests frameworks-core
300 *
301 * {@hide}
302 */
303public class PackageManagerService extends IPackageManager.Stub {
304    static final String TAG = "PackageManager";
305    static final boolean DEBUG_SETTINGS = false;
306    static final boolean DEBUG_PREFERRED = false;
307    static final boolean DEBUG_UPGRADE = false;
308    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
309    private static final boolean DEBUG_BACKUP = false;
310    private static final boolean DEBUG_INSTALL = false;
311    private static final boolean DEBUG_REMOVE = false;
312    private static final boolean DEBUG_BROADCASTS = false;
313    private static final boolean DEBUG_SHOW_INFO = false;
314    private static final boolean DEBUG_PACKAGE_INFO = false;
315    private static final boolean DEBUG_INTENT_MATCHING = false;
316    private static final boolean DEBUG_PACKAGE_SCANNING = false;
317    private static final boolean DEBUG_VERIFY = false;
318
319    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
320    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
321    // user, but by default initialize to this.
322    static final boolean DEBUG_DEXOPT = false;
323
324    private static final boolean DEBUG_ABI_SELECTION = false;
325    private static final boolean DEBUG_EPHEMERAL = false;
326    private static final boolean DEBUG_TRIAGED_MISSING = false;
327    private static final boolean DEBUG_APP_DATA = false;
328
329    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
330
331    private static final boolean DISABLE_EPHEMERAL_APPS = true;
332
333    private static final int RADIO_UID = Process.PHONE_UID;
334    private static final int LOG_UID = Process.LOG_UID;
335    private static final int NFC_UID = Process.NFC_UID;
336    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
337    private static final int SHELL_UID = Process.SHELL_UID;
338
339    // Cap the size of permission trees that 3rd party apps can define
340    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
341
342    // Suffix used during package installation when copying/moving
343    // package apks to install directory.
344    private static final String INSTALL_PACKAGE_SUFFIX = "-";
345
346    static final int SCAN_NO_DEX = 1<<1;
347    static final int SCAN_FORCE_DEX = 1<<2;
348    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
349    static final int SCAN_NEW_INSTALL = 1<<4;
350    static final int SCAN_NO_PATHS = 1<<5;
351    static final int SCAN_UPDATE_TIME = 1<<6;
352    static final int SCAN_DEFER_DEX = 1<<7;
353    static final int SCAN_BOOTING = 1<<8;
354    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
355    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
356    static final int SCAN_REPLACING = 1<<11;
357    static final int SCAN_REQUIRE_KNOWN = 1<<12;
358    static final int SCAN_MOVE = 1<<13;
359    static final int SCAN_INITIAL = 1<<14;
360
361    static final int REMOVE_CHATTY = 1<<16;
362
363    private static final int[] EMPTY_INT_ARRAY = new int[0];
364
365    /**
366     * Timeout (in milliseconds) after which the watchdog should declare that
367     * our handler thread is wedged.  The usual default for such things is one
368     * minute but we sometimes do very lengthy I/O operations on this thread,
369     * such as installing multi-gigabyte applications, so ours needs to be longer.
370     */
371    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
372
373    /**
374     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
375     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
376     * settings entry if available, otherwise we use the hardcoded default.  If it's been
377     * more than this long since the last fstrim, we force one during the boot sequence.
378     *
379     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
380     * one gets run at the next available charging+idle time.  This final mandatory
381     * no-fstrim check kicks in only of the other scheduling criteria is never met.
382     */
383    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
384
385    /**
386     * Whether verification is enabled by default.
387     */
388    private static final boolean DEFAULT_VERIFY_ENABLE = true;
389
390    /**
391     * The default maximum time to wait for the verification agent to return in
392     * milliseconds.
393     */
394    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
395
396    /**
397     * The default response for package verification timeout.
398     *
399     * This can be either PackageManager.VERIFICATION_ALLOW or
400     * PackageManager.VERIFICATION_REJECT.
401     */
402    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
403
404    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
405
406    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
407            DEFAULT_CONTAINER_PACKAGE,
408            "com.android.defcontainer.DefaultContainerService");
409
410    private static final String KILL_APP_REASON_GIDS_CHANGED =
411            "permission grant or revoke changed gids";
412
413    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
414            "permissions revoked";
415
416    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
417
418    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
419
420    /** Permission grant: not grant the permission. */
421    private static final int GRANT_DENIED = 1;
422
423    /** Permission grant: grant the permission as an install permission. */
424    private static final int GRANT_INSTALL = 2;
425
426    /** Permission grant: grant the permission as a runtime one. */
427    private static final int GRANT_RUNTIME = 3;
428
429    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
430    private static final int GRANT_UPGRADE = 4;
431
432    /** Canonical intent used to identify what counts as a "web browser" app */
433    private static final Intent sBrowserIntent;
434    static {
435        sBrowserIntent = new Intent();
436        sBrowserIntent.setAction(Intent.ACTION_VIEW);
437        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
438        sBrowserIntent.setData(Uri.parse("http:"));
439    }
440
441    final ServiceThread mHandlerThread;
442
443    final PackageHandler mHandler;
444
445    /**
446     * Messages for {@link #mHandler} that need to wait for system ready before
447     * being dispatched.
448     */
449    private ArrayList<Message> mPostSystemReadyMessages;
450
451    final int mSdkVersion = Build.VERSION.SDK_INT;
452
453    final Context mContext;
454    final boolean mFactoryTest;
455    final boolean mOnlyCore;
456    final DisplayMetrics mMetrics;
457    final int mDefParseFlags;
458    final String[] mSeparateProcesses;
459    final boolean mIsUpgrade;
460
461    /** The location for ASEC container files on internal storage. */
462    final String mAsecInternalPath;
463
464    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
465    // LOCK HELD.  Can be called with mInstallLock held.
466    @GuardedBy("mInstallLock")
467    final Installer mInstaller;
468
469    /** Directory where installed third-party apps stored */
470    final File mAppInstallDir;
471    final File mEphemeralInstallDir;
472
473    /**
474     * Directory to which applications installed internally have their
475     * 32 bit native libraries copied.
476     */
477    private File mAppLib32InstallDir;
478
479    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
480    // apps.
481    final File mDrmAppPrivateInstallDir;
482
483    // ----------------------------------------------------------------
484
485    // Lock for state used when installing and doing other long running
486    // operations.  Methods that must be called with this lock held have
487    // the suffix "LI".
488    final Object mInstallLock = new Object();
489
490    // ----------------------------------------------------------------
491
492    // Keys are String (package name), values are Package.  This also serves
493    // as the lock for the global state.  Methods that must be called with
494    // this lock held have the prefix "LP".
495    @GuardedBy("mPackages")
496    final ArrayMap<String, PackageParser.Package> mPackages =
497            new ArrayMap<String, PackageParser.Package>();
498
499    // Tracks available target package names -> overlay package paths.
500    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
501        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
502
503    /**
504     * Tracks new system packages [received in an OTA] that we expect to
505     * find updated user-installed versions. Keys are package name, values
506     * are package location.
507     */
508    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
509
510    /**
511     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
512     */
513    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
514    /**
515     * Whether or not system app permissions should be promoted from install to runtime.
516     */
517    boolean mPromoteSystemApps;
518
519    final Settings mSettings;
520    boolean mRestoredSettings;
521
522    // System configuration read by SystemConfig.
523    final int[] mGlobalGids;
524    final SparseArray<ArraySet<String>> mSystemPermissions;
525    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
526
527    // If mac_permissions.xml was found for seinfo labeling.
528    boolean mFoundPolicyFile;
529
530    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
531
532    public static final class SharedLibraryEntry {
533        public final String path;
534        public final String apk;
535
536        SharedLibraryEntry(String _path, String _apk) {
537            path = _path;
538            apk = _apk;
539        }
540    }
541
542    // Currently known shared libraries.
543    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
544            new ArrayMap<String, SharedLibraryEntry>();
545
546    // All available activities, for your resolving pleasure.
547    final ActivityIntentResolver mActivities =
548            new ActivityIntentResolver();
549
550    // All available receivers, for your resolving pleasure.
551    final ActivityIntentResolver mReceivers =
552            new ActivityIntentResolver();
553
554    // All available services, for your resolving pleasure.
555    final ServiceIntentResolver mServices = new ServiceIntentResolver();
556
557    // All available providers, for your resolving pleasure.
558    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
559
560    // Mapping from provider base names (first directory in content URI codePath)
561    // to the provider information.
562    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
563            new ArrayMap<String, PackageParser.Provider>();
564
565    // Mapping from instrumentation class names to info about them.
566    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
567            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
568
569    // Mapping from permission names to info about them.
570    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
571            new ArrayMap<String, PackageParser.PermissionGroup>();
572
573    // Packages whose data we have transfered into another package, thus
574    // should no longer exist.
575    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
576
577    // Broadcast actions that are only available to the system.
578    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
579
580    /** List of packages waiting for verification. */
581    final SparseArray<PackageVerificationState> mPendingVerification
582            = new SparseArray<PackageVerificationState>();
583
584    /** Set of packages associated with each app op permission. */
585    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
586
587    final PackageInstallerService mInstallerService;
588
589    private final PackageDexOptimizer mPackageDexOptimizer;
590
591    private AtomicInteger mNextMoveId = new AtomicInteger();
592    private final MoveCallbacks mMoveCallbacks;
593
594    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
595
596    // Cache of users who need badging.
597    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
598
599    /** Token for keys in mPendingVerification. */
600    private int mPendingVerificationToken = 0;
601
602    volatile boolean mSystemReady;
603    volatile boolean mSafeMode;
604    volatile boolean mHasSystemUidErrors;
605
606    ApplicationInfo mAndroidApplication;
607    final ActivityInfo mResolveActivity = new ActivityInfo();
608    final ResolveInfo mResolveInfo = new ResolveInfo();
609    ComponentName mResolveComponentName;
610    PackageParser.Package mPlatformPackage;
611    ComponentName mCustomResolverComponentName;
612
613    boolean mResolverReplaced = false;
614
615    private final @Nullable ComponentName mIntentFilterVerifierComponent;
616    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
617
618    private int mIntentFilterVerificationToken = 0;
619
620    /** Component that knows whether or not an ephemeral application exists */
621    final ComponentName mEphemeralResolverComponent;
622    /** The service connection to the ephemeral resolver */
623    final EphemeralResolverConnection mEphemeralResolverConnection;
624
625    /** Component used to install ephemeral applications */
626    final ComponentName mEphemeralInstallerComponent;
627    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
628    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
629
630    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
631            = new SparseArray<IntentFilterVerificationState>();
632
633    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
634            new DefaultPermissionGrantPolicy(this);
635
636    // List of packages names to keep cached, even if they are uninstalled for all users
637    private List<String> mKeepUninstalledPackages;
638
639    private boolean mUseJitProfiles =
640            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
641
642    private static class IFVerificationParams {
643        PackageParser.Package pkg;
644        boolean replacing;
645        int userId;
646        int verifierUid;
647
648        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
649                int _userId, int _verifierUid) {
650            pkg = _pkg;
651            replacing = _replacing;
652            userId = _userId;
653            replacing = _replacing;
654            verifierUid = _verifierUid;
655        }
656    }
657
658    private interface IntentFilterVerifier<T extends IntentFilter> {
659        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
660                                               T filter, String packageName);
661        void startVerifications(int userId);
662        void receiveVerificationResponse(int verificationId);
663    }
664
665    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
666        private Context mContext;
667        private ComponentName mIntentFilterVerifierComponent;
668        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
669
670        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
671            mContext = context;
672            mIntentFilterVerifierComponent = verifierComponent;
673        }
674
675        private String getDefaultScheme() {
676            return IntentFilter.SCHEME_HTTPS;
677        }
678
679        @Override
680        public void startVerifications(int userId) {
681            // Launch verifications requests
682            int count = mCurrentIntentFilterVerifications.size();
683            for (int n=0; n<count; n++) {
684                int verificationId = mCurrentIntentFilterVerifications.get(n);
685                final IntentFilterVerificationState ivs =
686                        mIntentFilterVerificationStates.get(verificationId);
687
688                String packageName = ivs.getPackageName();
689
690                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
691                final int filterCount = filters.size();
692                ArraySet<String> domainsSet = new ArraySet<>();
693                for (int m=0; m<filterCount; m++) {
694                    PackageParser.ActivityIntentInfo filter = filters.get(m);
695                    domainsSet.addAll(filter.getHostsList());
696                }
697                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
698                synchronized (mPackages) {
699                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
700                            packageName, domainsList) != null) {
701                        scheduleWriteSettingsLocked();
702                    }
703                }
704                sendVerificationRequest(userId, verificationId, ivs);
705            }
706            mCurrentIntentFilterVerifications.clear();
707        }
708
709        private void sendVerificationRequest(int userId, int verificationId,
710                IntentFilterVerificationState ivs) {
711
712            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
713            verificationIntent.putExtra(
714                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
715                    verificationId);
716            verificationIntent.putExtra(
717                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
718                    getDefaultScheme());
719            verificationIntent.putExtra(
720                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
721                    ivs.getHostsString());
722            verificationIntent.putExtra(
723                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
724                    ivs.getPackageName());
725            verificationIntent.setComponent(mIntentFilterVerifierComponent);
726            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
727
728            UserHandle user = new UserHandle(userId);
729            mContext.sendBroadcastAsUser(verificationIntent, user);
730            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
731                    "Sending IntentFilter verification broadcast");
732        }
733
734        public void receiveVerificationResponse(int verificationId) {
735            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
736
737            final boolean verified = ivs.isVerified();
738
739            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
740            final int count = filters.size();
741            if (DEBUG_DOMAIN_VERIFICATION) {
742                Slog.i(TAG, "Received verification response " + verificationId
743                        + " for " + count + " filters, verified=" + verified);
744            }
745            for (int n=0; n<count; n++) {
746                PackageParser.ActivityIntentInfo filter = filters.get(n);
747                filter.setVerified(verified);
748
749                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
750                        + " verified with result:" + verified + " and hosts:"
751                        + ivs.getHostsString());
752            }
753
754            mIntentFilterVerificationStates.remove(verificationId);
755
756            final String packageName = ivs.getPackageName();
757            IntentFilterVerificationInfo ivi = null;
758
759            synchronized (mPackages) {
760                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
761            }
762            if (ivi == null) {
763                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
764                        + verificationId + " packageName:" + packageName);
765                return;
766            }
767            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
768                    "Updating IntentFilterVerificationInfo for package " + packageName
769                            +" verificationId:" + verificationId);
770
771            synchronized (mPackages) {
772                if (verified) {
773                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
774                } else {
775                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
776                }
777                scheduleWriteSettingsLocked();
778
779                final int userId = ivs.getUserId();
780                if (userId != UserHandle.USER_ALL) {
781                    final int userStatus =
782                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
783
784                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
785                    boolean needUpdate = false;
786
787                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
788                    // already been set by the User thru the Disambiguation dialog
789                    switch (userStatus) {
790                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
791                            if (verified) {
792                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
793                            } else {
794                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
795                            }
796                            needUpdate = true;
797                            break;
798
799                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
800                            if (verified) {
801                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
802                                needUpdate = true;
803                            }
804                            break;
805
806                        default:
807                            // Nothing to do
808                    }
809
810                    if (needUpdate) {
811                        mSettings.updateIntentFilterVerificationStatusLPw(
812                                packageName, updatedStatus, userId);
813                        scheduleWritePackageRestrictionsLocked(userId);
814                    }
815                }
816            }
817        }
818
819        @Override
820        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
821                    ActivityIntentInfo filter, String packageName) {
822            if (!hasValidDomains(filter)) {
823                return false;
824            }
825            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
826            if (ivs == null) {
827                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
828                        packageName);
829            }
830            if (DEBUG_DOMAIN_VERIFICATION) {
831                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
832            }
833            ivs.addFilter(filter);
834            return true;
835        }
836
837        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
838                int userId, int verificationId, String packageName) {
839            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
840                    verifierUid, userId, packageName);
841            ivs.setPendingState();
842            synchronized (mPackages) {
843                mIntentFilterVerificationStates.append(verificationId, ivs);
844                mCurrentIntentFilterVerifications.add(verificationId);
845            }
846            return ivs;
847        }
848    }
849
850    private static boolean hasValidDomains(ActivityIntentInfo filter) {
851        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
852                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
853                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
854    }
855
856    // Set of pending broadcasts for aggregating enable/disable of components.
857    static class PendingPackageBroadcasts {
858        // for each user id, a map of <package name -> components within that package>
859        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
860
861        public PendingPackageBroadcasts() {
862            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
863        }
864
865        public ArrayList<String> get(int userId, String packageName) {
866            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
867            return packages.get(packageName);
868        }
869
870        public void put(int userId, String packageName, ArrayList<String> components) {
871            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
872            packages.put(packageName, components);
873        }
874
875        public void remove(int userId, String packageName) {
876            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
877            if (packages != null) {
878                packages.remove(packageName);
879            }
880        }
881
882        public void remove(int userId) {
883            mUidMap.remove(userId);
884        }
885
886        public int userIdCount() {
887            return mUidMap.size();
888        }
889
890        public int userIdAt(int n) {
891            return mUidMap.keyAt(n);
892        }
893
894        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
895            return mUidMap.get(userId);
896        }
897
898        public int size() {
899            // total number of pending broadcast entries across all userIds
900            int num = 0;
901            for (int i = 0; i< mUidMap.size(); i++) {
902                num += mUidMap.valueAt(i).size();
903            }
904            return num;
905        }
906
907        public void clear() {
908            mUidMap.clear();
909        }
910
911        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
912            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
913            if (map == null) {
914                map = new ArrayMap<String, ArrayList<String>>();
915                mUidMap.put(userId, map);
916            }
917            return map;
918        }
919    }
920    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
921
922    // Service Connection to remote media container service to copy
923    // package uri's from external media onto secure containers
924    // or internal storage.
925    private IMediaContainerService mContainerService = null;
926
927    static final int SEND_PENDING_BROADCAST = 1;
928    static final int MCS_BOUND = 3;
929    static final int END_COPY = 4;
930    static final int INIT_COPY = 5;
931    static final int MCS_UNBIND = 6;
932    static final int START_CLEANING_PACKAGE = 7;
933    static final int FIND_INSTALL_LOC = 8;
934    static final int POST_INSTALL = 9;
935    static final int MCS_RECONNECT = 10;
936    static final int MCS_GIVE_UP = 11;
937    static final int UPDATED_MEDIA_STATUS = 12;
938    static final int WRITE_SETTINGS = 13;
939    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
940    static final int PACKAGE_VERIFIED = 15;
941    static final int CHECK_PENDING_VERIFICATION = 16;
942    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
943    static final int INTENT_FILTER_VERIFIED = 18;
944
945    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
946
947    // Delay time in millisecs
948    static final int BROADCAST_DELAY = 10 * 1000;
949
950    static UserManagerService sUserManager;
951
952    // Stores a list of users whose package restrictions file needs to be updated
953    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
954
955    final private DefaultContainerConnection mDefContainerConn =
956            new DefaultContainerConnection();
957    class DefaultContainerConnection implements ServiceConnection {
958        public void onServiceConnected(ComponentName name, IBinder service) {
959            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
960            IMediaContainerService imcs =
961                IMediaContainerService.Stub.asInterface(service);
962            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
963        }
964
965        public void onServiceDisconnected(ComponentName name) {
966            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
967        }
968    }
969
970    // Recordkeeping of restore-after-install operations that are currently in flight
971    // between the Package Manager and the Backup Manager
972    static class PostInstallData {
973        public InstallArgs args;
974        public PackageInstalledInfo res;
975
976        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
977            args = _a;
978            res = _r;
979        }
980    }
981
982    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
983    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
984
985    // XML tags for backup/restore of various bits of state
986    private static final String TAG_PREFERRED_BACKUP = "pa";
987    private static final String TAG_DEFAULT_APPS = "da";
988    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
989
990    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
991    private static final String TAG_ALL_GRANTS = "rt-grants";
992    private static final String TAG_GRANT = "grant";
993    private static final String ATTR_PACKAGE_NAME = "pkg";
994
995    private static final String TAG_PERMISSION = "perm";
996    private static final String ATTR_PERMISSION_NAME = "name";
997    private static final String ATTR_IS_GRANTED = "g";
998    private static final String ATTR_USER_SET = "set";
999    private static final String ATTR_USER_FIXED = "fixed";
1000    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1001
1002    // System/policy permission grants are not backed up
1003    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1004            FLAG_PERMISSION_POLICY_FIXED
1005            | FLAG_PERMISSION_SYSTEM_FIXED
1006            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1007
1008    // And we back up these user-adjusted states
1009    private static final int USER_RUNTIME_GRANT_MASK =
1010            FLAG_PERMISSION_USER_SET
1011            | FLAG_PERMISSION_USER_FIXED
1012            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1013
1014    final @Nullable String mRequiredVerifierPackage;
1015    final @Nullable String mRequiredInstallerPackage;
1016
1017    private final PackageUsage mPackageUsage = new PackageUsage();
1018
1019    private class PackageUsage {
1020        private static final int WRITE_INTERVAL
1021            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1022
1023        private final Object mFileLock = new Object();
1024        private final AtomicLong mLastWritten = new AtomicLong(0);
1025        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1026
1027        private boolean mIsHistoricalPackageUsageAvailable = true;
1028
1029        boolean isHistoricalPackageUsageAvailable() {
1030            return mIsHistoricalPackageUsageAvailable;
1031        }
1032
1033        void write(boolean force) {
1034            if (force) {
1035                writeInternal();
1036                return;
1037            }
1038            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1039                && !DEBUG_DEXOPT) {
1040                return;
1041            }
1042            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1043                new Thread("PackageUsage_DiskWriter") {
1044                    @Override
1045                    public void run() {
1046                        try {
1047                            writeInternal();
1048                        } finally {
1049                            mBackgroundWriteRunning.set(false);
1050                        }
1051                    }
1052                }.start();
1053            }
1054        }
1055
1056        private void writeInternal() {
1057            synchronized (mPackages) {
1058                synchronized (mFileLock) {
1059                    AtomicFile file = getFile();
1060                    FileOutputStream f = null;
1061                    try {
1062                        f = file.startWrite();
1063                        BufferedOutputStream out = new BufferedOutputStream(f);
1064                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1065                        StringBuilder sb = new StringBuilder();
1066                        for (PackageParser.Package pkg : mPackages.values()) {
1067                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1068                                continue;
1069                            }
1070                            sb.setLength(0);
1071                            sb.append(pkg.packageName);
1072                            sb.append(' ');
1073                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1074                            sb.append('\n');
1075                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1076                        }
1077                        out.flush();
1078                        file.finishWrite(f);
1079                    } catch (IOException e) {
1080                        if (f != null) {
1081                            file.failWrite(f);
1082                        }
1083                        Log.e(TAG, "Failed to write package usage times", e);
1084                    }
1085                }
1086            }
1087            mLastWritten.set(SystemClock.elapsedRealtime());
1088        }
1089
1090        void readLP() {
1091            synchronized (mFileLock) {
1092                AtomicFile file = getFile();
1093                BufferedInputStream in = null;
1094                try {
1095                    in = new BufferedInputStream(file.openRead());
1096                    StringBuffer sb = new StringBuffer();
1097                    while (true) {
1098                        String packageName = readToken(in, sb, ' ');
1099                        if (packageName == null) {
1100                            break;
1101                        }
1102                        String timeInMillisString = readToken(in, sb, '\n');
1103                        if (timeInMillisString == null) {
1104                            throw new IOException("Failed to find last usage time for package "
1105                                                  + packageName);
1106                        }
1107                        PackageParser.Package pkg = mPackages.get(packageName);
1108                        if (pkg == null) {
1109                            continue;
1110                        }
1111                        long timeInMillis;
1112                        try {
1113                            timeInMillis = Long.parseLong(timeInMillisString);
1114                        } catch (NumberFormatException e) {
1115                            throw new IOException("Failed to parse " + timeInMillisString
1116                                                  + " as a long.", e);
1117                        }
1118                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1119                    }
1120                } catch (FileNotFoundException expected) {
1121                    mIsHistoricalPackageUsageAvailable = false;
1122                } catch (IOException e) {
1123                    Log.w(TAG, "Failed to read package usage times", e);
1124                } finally {
1125                    IoUtils.closeQuietly(in);
1126                }
1127            }
1128            mLastWritten.set(SystemClock.elapsedRealtime());
1129        }
1130
1131        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1132                throws IOException {
1133            sb.setLength(0);
1134            while (true) {
1135                int ch = in.read();
1136                if (ch == -1) {
1137                    if (sb.length() == 0) {
1138                        return null;
1139                    }
1140                    throw new IOException("Unexpected EOF");
1141                }
1142                if (ch == endOfToken) {
1143                    return sb.toString();
1144                }
1145                sb.append((char)ch);
1146            }
1147        }
1148
1149        private AtomicFile getFile() {
1150            File dataDir = Environment.getDataDirectory();
1151            File systemDir = new File(dataDir, "system");
1152            File fname = new File(systemDir, "package-usage.list");
1153            return new AtomicFile(fname);
1154        }
1155    }
1156
1157    class PackageHandler extends Handler {
1158        private boolean mBound = false;
1159        final ArrayList<HandlerParams> mPendingInstalls =
1160            new ArrayList<HandlerParams>();
1161
1162        private boolean connectToService() {
1163            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1164                    " DefaultContainerService");
1165            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1166            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1167            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1168                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1169                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1170                mBound = true;
1171                return true;
1172            }
1173            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1174            return false;
1175        }
1176
1177        private void disconnectService() {
1178            mContainerService = null;
1179            mBound = false;
1180            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1181            mContext.unbindService(mDefContainerConn);
1182            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1183        }
1184
1185        PackageHandler(Looper looper) {
1186            super(looper);
1187        }
1188
1189        public void handleMessage(Message msg) {
1190            try {
1191                doHandleMessage(msg);
1192            } finally {
1193                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1194            }
1195        }
1196
1197        void doHandleMessage(Message msg) {
1198            switch (msg.what) {
1199                case INIT_COPY: {
1200                    HandlerParams params = (HandlerParams) msg.obj;
1201                    int idx = mPendingInstalls.size();
1202                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1203                    // If a bind was already initiated we dont really
1204                    // need to do anything. The pending install
1205                    // will be processed later on.
1206                    if (!mBound) {
1207                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1208                                System.identityHashCode(mHandler));
1209                        // If this is the only one pending we might
1210                        // have to bind to the service again.
1211                        if (!connectToService()) {
1212                            Slog.e(TAG, "Failed to bind to media container service");
1213                            params.serviceError();
1214                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1215                                    System.identityHashCode(mHandler));
1216                            if (params.traceMethod != null) {
1217                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1218                                        params.traceCookie);
1219                            }
1220                            return;
1221                        } else {
1222                            // Once we bind to the service, the first
1223                            // pending request will be processed.
1224                            mPendingInstalls.add(idx, params);
1225                        }
1226                    } else {
1227                        mPendingInstalls.add(idx, params);
1228                        // Already bound to the service. Just make
1229                        // sure we trigger off processing the first request.
1230                        if (idx == 0) {
1231                            mHandler.sendEmptyMessage(MCS_BOUND);
1232                        }
1233                    }
1234                    break;
1235                }
1236                case MCS_BOUND: {
1237                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1238                    if (msg.obj != null) {
1239                        mContainerService = (IMediaContainerService) msg.obj;
1240                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1241                                System.identityHashCode(mHandler));
1242                    }
1243                    if (mContainerService == null) {
1244                        if (!mBound) {
1245                            // Something seriously wrong since we are not bound and we are not
1246                            // waiting for connection. Bail out.
1247                            Slog.e(TAG, "Cannot bind to media container service");
1248                            for (HandlerParams params : mPendingInstalls) {
1249                                // Indicate service bind error
1250                                params.serviceError();
1251                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1252                                        System.identityHashCode(params));
1253                                if (params.traceMethod != null) {
1254                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1255                                            params.traceMethod, params.traceCookie);
1256                                }
1257                                return;
1258                            }
1259                            mPendingInstalls.clear();
1260                        } else {
1261                            Slog.w(TAG, "Waiting to connect to media container service");
1262                        }
1263                    } else if (mPendingInstalls.size() > 0) {
1264                        HandlerParams params = mPendingInstalls.get(0);
1265                        if (params != null) {
1266                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1267                                    System.identityHashCode(params));
1268                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1269                            if (params.startCopy()) {
1270                                // We are done...  look for more work or to
1271                                // go idle.
1272                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1273                                        "Checking for more work or unbind...");
1274                                // Delete pending install
1275                                if (mPendingInstalls.size() > 0) {
1276                                    mPendingInstalls.remove(0);
1277                                }
1278                                if (mPendingInstalls.size() == 0) {
1279                                    if (mBound) {
1280                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1281                                                "Posting delayed MCS_UNBIND");
1282                                        removeMessages(MCS_UNBIND);
1283                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1284                                        // Unbind after a little delay, to avoid
1285                                        // continual thrashing.
1286                                        sendMessageDelayed(ubmsg, 10000);
1287                                    }
1288                                } else {
1289                                    // There are more pending requests in queue.
1290                                    // Just post MCS_BOUND message to trigger processing
1291                                    // of next pending install.
1292                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1293                                            "Posting MCS_BOUND for next work");
1294                                    mHandler.sendEmptyMessage(MCS_BOUND);
1295                                }
1296                            }
1297                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1298                        }
1299                    } else {
1300                        // Should never happen ideally.
1301                        Slog.w(TAG, "Empty queue");
1302                    }
1303                    break;
1304                }
1305                case MCS_RECONNECT: {
1306                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1307                    if (mPendingInstalls.size() > 0) {
1308                        if (mBound) {
1309                            disconnectService();
1310                        }
1311                        if (!connectToService()) {
1312                            Slog.e(TAG, "Failed to bind to media container service");
1313                            for (HandlerParams params : mPendingInstalls) {
1314                                // Indicate service bind error
1315                                params.serviceError();
1316                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1317                                        System.identityHashCode(params));
1318                            }
1319                            mPendingInstalls.clear();
1320                        }
1321                    }
1322                    break;
1323                }
1324                case MCS_UNBIND: {
1325                    // If there is no actual work left, then time to unbind.
1326                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1327
1328                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1329                        if (mBound) {
1330                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1331
1332                            disconnectService();
1333                        }
1334                    } else if (mPendingInstalls.size() > 0) {
1335                        // There are more pending requests in queue.
1336                        // Just post MCS_BOUND message to trigger processing
1337                        // of next pending install.
1338                        mHandler.sendEmptyMessage(MCS_BOUND);
1339                    }
1340
1341                    break;
1342                }
1343                case MCS_GIVE_UP: {
1344                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1345                    HandlerParams params = mPendingInstalls.remove(0);
1346                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1347                            System.identityHashCode(params));
1348                    break;
1349                }
1350                case SEND_PENDING_BROADCAST: {
1351                    String packages[];
1352                    ArrayList<String> components[];
1353                    int size = 0;
1354                    int uids[];
1355                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1356                    synchronized (mPackages) {
1357                        if (mPendingBroadcasts == null) {
1358                            return;
1359                        }
1360                        size = mPendingBroadcasts.size();
1361                        if (size <= 0) {
1362                            // Nothing to be done. Just return
1363                            return;
1364                        }
1365                        packages = new String[size];
1366                        components = new ArrayList[size];
1367                        uids = new int[size];
1368                        int i = 0;  // filling out the above arrays
1369
1370                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1371                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1372                            Iterator<Map.Entry<String, ArrayList<String>>> it
1373                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1374                                            .entrySet().iterator();
1375                            while (it.hasNext() && i < size) {
1376                                Map.Entry<String, ArrayList<String>> ent = it.next();
1377                                packages[i] = ent.getKey();
1378                                components[i] = ent.getValue();
1379                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1380                                uids[i] = (ps != null)
1381                                        ? UserHandle.getUid(packageUserId, ps.appId)
1382                                        : -1;
1383                                i++;
1384                            }
1385                        }
1386                        size = i;
1387                        mPendingBroadcasts.clear();
1388                    }
1389                    // Send broadcasts
1390                    for (int i = 0; i < size; i++) {
1391                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1392                    }
1393                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1394                    break;
1395                }
1396                case START_CLEANING_PACKAGE: {
1397                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1398                    final String packageName = (String)msg.obj;
1399                    final int userId = msg.arg1;
1400                    final boolean andCode = msg.arg2 != 0;
1401                    synchronized (mPackages) {
1402                        if (userId == UserHandle.USER_ALL) {
1403                            int[] users = sUserManager.getUserIds();
1404                            for (int user : users) {
1405                                mSettings.addPackageToCleanLPw(
1406                                        new PackageCleanItem(user, packageName, andCode));
1407                            }
1408                        } else {
1409                            mSettings.addPackageToCleanLPw(
1410                                    new PackageCleanItem(userId, packageName, andCode));
1411                        }
1412                    }
1413                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414                    startCleaningPackages();
1415                } break;
1416                case POST_INSTALL: {
1417                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1418
1419                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1420                    mRunningInstalls.delete(msg.arg1);
1421                    boolean deleteOld = false;
1422
1423                    if (data != null) {
1424                        InstallArgs args = data.args;
1425                        PackageInstalledInfo res = data.res;
1426
1427                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1428                            final String packageName = res.pkg.applicationInfo.packageName;
1429                            res.removedInfo.sendBroadcast(false, true, false);
1430                            Bundle extras = new Bundle(1);
1431                            extras.putInt(Intent.EXTRA_UID, res.uid);
1432
1433                            // Now that we successfully installed the package, grant runtime
1434                            // permissions if requested before broadcasting the install.
1435                            if ((args.installFlags
1436                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1437                                    && res.pkg.applicationInfo.targetSdkVersion
1438                                            >= Build.VERSION_CODES.M) {
1439                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1440                                        args.installGrantPermissions);
1441                            }
1442
1443                            synchronized (mPackages) {
1444                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1445                            }
1446
1447                            // Determine the set of users who are adding this
1448                            // package for the first time vs. those who are seeing
1449                            // an update.
1450                            int[] firstUsers;
1451                            int[] updateUsers = new int[0];
1452                            if (res.origUsers == null || res.origUsers.length == 0) {
1453                                firstUsers = res.newUsers;
1454                            } else {
1455                                firstUsers = new int[0];
1456                                for (int i=0; i<res.newUsers.length; i++) {
1457                                    int user = res.newUsers[i];
1458                                    boolean isNew = true;
1459                                    for (int j=0; j<res.origUsers.length; j++) {
1460                                        if (res.origUsers[j] == user) {
1461                                            isNew = false;
1462                                            break;
1463                                        }
1464                                    }
1465                                    if (isNew) {
1466                                        int[] newFirst = new int[firstUsers.length+1];
1467                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1468                                                firstUsers.length);
1469                                        newFirst[firstUsers.length] = user;
1470                                        firstUsers = newFirst;
1471                                    } else {
1472                                        int[] newUpdate = new int[updateUsers.length+1];
1473                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1474                                                updateUsers.length);
1475                                        newUpdate[updateUsers.length] = user;
1476                                        updateUsers = newUpdate;
1477                                    }
1478                                }
1479                            }
1480                            // don't broadcast for ephemeral installs/updates
1481                            final boolean isEphemeral = isEphemeral(res.pkg);
1482                            if (!isEphemeral) {
1483                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1484                                        extras, 0 /*flags*/, null /*targetPackage*/,
1485                                        null /*finishedReceiver*/, firstUsers);
1486                            }
1487                            final boolean update = res.removedInfo.removedPackage != null;
1488                            if (update) {
1489                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1490                            }
1491                            if (!isEphemeral) {
1492                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1493                                        extras, 0 /*flags*/, null /*targetPackage*/,
1494                                        null /*finishedReceiver*/, updateUsers);
1495                            }
1496                            if (update) {
1497                                if (!isEphemeral) {
1498                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1499                                            packageName, extras, 0 /*flags*/,
1500                                            null /*targetPackage*/, null /*finishedReceiver*/,
1501                                            updateUsers);
1502                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1503                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1504                                            packageName /*targetPackage*/,
1505                                            null /*finishedReceiver*/, updateUsers);
1506                                }
1507
1508                                // treat asec-hosted packages like removable media on upgrade
1509                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1510                                    if (DEBUG_INSTALL) {
1511                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1512                                                + " is ASEC-hosted -> AVAILABLE");
1513                                    }
1514                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1515                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1516                                    pkgList.add(packageName);
1517                                    sendResourcesChangedBroadcast(true, true,
1518                                            pkgList,uidArray, null);
1519                                }
1520                            }
1521                            if (res.removedInfo.args != null) {
1522                                // Remove the replaced package's older resources safely now
1523                                deleteOld = true;
1524                            }
1525
1526
1527                            // Work that needs to happen on first install within each user
1528                            if (firstUsers.length > 0) {
1529                                for (int userId : firstUsers) {
1530                                    synchronized (mPackages) {
1531                                        // If this app is a browser and it's newly-installed for
1532                                        // some users, clear any default-browser state in those
1533                                        // users.  The app's nature doesn't depend on the user,
1534                                        // so we can just check its browser nature in any user
1535                                        // and generalize.
1536                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1537                                            mSettings.setDefaultBrowserPackageNameLPw(
1538                                                    null, userId);
1539                                        }
1540
1541                                        // We may also need to apply pending (restored) runtime
1542                                        // permission grants within these users.
1543                                        mSettings.applyPendingPermissionGrantsLPw(
1544                                                packageName, userId);
1545                                    }
1546                                }
1547                            }
1548                            // Log current value of "unknown sources" setting
1549                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1550                                getUnknownSourcesSettings());
1551                        }
1552                        // Force a gc to clear up things
1553                        Runtime.getRuntime().gc();
1554                        // We delete after a gc for applications  on sdcard.
1555                        if (deleteOld) {
1556                            synchronized (mInstallLock) {
1557                                res.removedInfo.args.doPostDeleteLI(true);
1558                            }
1559                        }
1560                        if (args.observer != null) {
1561                            try {
1562                                Bundle extras = extrasForInstallResult(res);
1563                                args.observer.onPackageInstalled(res.name, res.returnCode,
1564                                        res.returnMsg, extras);
1565                            } catch (RemoteException e) {
1566                                Slog.i(TAG, "Observer no longer exists.");
1567                            }
1568                        }
1569                        if (args.traceMethod != null) {
1570                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1571                                    args.traceCookie);
1572                        }
1573                        return;
1574                    } else {
1575                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1576                    }
1577
1578                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1579                } break;
1580                case UPDATED_MEDIA_STATUS: {
1581                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1582                    boolean reportStatus = msg.arg1 == 1;
1583                    boolean doGc = msg.arg2 == 1;
1584                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1585                    if (doGc) {
1586                        // Force a gc to clear up stale containers.
1587                        Runtime.getRuntime().gc();
1588                    }
1589                    if (msg.obj != null) {
1590                        @SuppressWarnings("unchecked")
1591                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1592                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1593                        // Unload containers
1594                        unloadAllContainers(args);
1595                    }
1596                    if (reportStatus) {
1597                        try {
1598                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1599                            PackageHelper.getMountService().finishMediaUpdate();
1600                        } catch (RemoteException e) {
1601                            Log.e(TAG, "MountService not running?");
1602                        }
1603                    }
1604                } break;
1605                case WRITE_SETTINGS: {
1606                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1607                    synchronized (mPackages) {
1608                        removeMessages(WRITE_SETTINGS);
1609                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1610                        mSettings.writeLPr();
1611                        mDirtyUsers.clear();
1612                    }
1613                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1614                } break;
1615                case WRITE_PACKAGE_RESTRICTIONS: {
1616                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1617                    synchronized (mPackages) {
1618                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1619                        for (int userId : mDirtyUsers) {
1620                            mSettings.writePackageRestrictionsLPr(userId);
1621                        }
1622                        mDirtyUsers.clear();
1623                    }
1624                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1625                } break;
1626                case CHECK_PENDING_VERIFICATION: {
1627                    final int verificationId = msg.arg1;
1628                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1629
1630                    if ((state != null) && !state.timeoutExtended()) {
1631                        final InstallArgs args = state.getInstallArgs();
1632                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1633
1634                        Slog.i(TAG, "Verification timed out for " + originUri);
1635                        mPendingVerification.remove(verificationId);
1636
1637                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1638
1639                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1640                            Slog.i(TAG, "Continuing with installation of " + originUri);
1641                            state.setVerifierResponse(Binder.getCallingUid(),
1642                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1643                            broadcastPackageVerified(verificationId, originUri,
1644                                    PackageManager.VERIFICATION_ALLOW,
1645                                    state.getInstallArgs().getUser());
1646                            try {
1647                                ret = args.copyApk(mContainerService, true);
1648                            } catch (RemoteException e) {
1649                                Slog.e(TAG, "Could not contact the ContainerService");
1650                            }
1651                        } else {
1652                            broadcastPackageVerified(verificationId, originUri,
1653                                    PackageManager.VERIFICATION_REJECT,
1654                                    state.getInstallArgs().getUser());
1655                        }
1656
1657                        Trace.asyncTraceEnd(
1658                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1659
1660                        processPendingInstall(args, ret);
1661                        mHandler.sendEmptyMessage(MCS_UNBIND);
1662                    }
1663                    break;
1664                }
1665                case PACKAGE_VERIFIED: {
1666                    final int verificationId = msg.arg1;
1667
1668                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1669                    if (state == null) {
1670                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1671                        break;
1672                    }
1673
1674                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1675
1676                    state.setVerifierResponse(response.callerUid, response.code);
1677
1678                    if (state.isVerificationComplete()) {
1679                        mPendingVerification.remove(verificationId);
1680
1681                        final InstallArgs args = state.getInstallArgs();
1682                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1683
1684                        int ret;
1685                        if (state.isInstallAllowed()) {
1686                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1687                            broadcastPackageVerified(verificationId, originUri,
1688                                    response.code, state.getInstallArgs().getUser());
1689                            try {
1690                                ret = args.copyApk(mContainerService, true);
1691                            } catch (RemoteException e) {
1692                                Slog.e(TAG, "Could not contact the ContainerService");
1693                            }
1694                        } else {
1695                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1696                        }
1697
1698                        Trace.asyncTraceEnd(
1699                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1700
1701                        processPendingInstall(args, ret);
1702                        mHandler.sendEmptyMessage(MCS_UNBIND);
1703                    }
1704
1705                    break;
1706                }
1707                case START_INTENT_FILTER_VERIFICATIONS: {
1708                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1709                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1710                            params.replacing, params.pkg);
1711                    break;
1712                }
1713                case INTENT_FILTER_VERIFIED: {
1714                    final int verificationId = msg.arg1;
1715
1716                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1717                            verificationId);
1718                    if (state == null) {
1719                        Slog.w(TAG, "Invalid IntentFilter verification token "
1720                                + verificationId + " received");
1721                        break;
1722                    }
1723
1724                    final int userId = state.getUserId();
1725
1726                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1727                            "Processing IntentFilter verification with token:"
1728                            + verificationId + " and userId:" + userId);
1729
1730                    final IntentFilterVerificationResponse response =
1731                            (IntentFilterVerificationResponse) msg.obj;
1732
1733                    state.setVerifierResponse(response.callerUid, response.code);
1734
1735                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1736                            "IntentFilter verification with token:" + verificationId
1737                            + " and userId:" + userId
1738                            + " is settings verifier response with response code:"
1739                            + response.code);
1740
1741                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1742                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1743                                + response.getFailedDomainsString());
1744                    }
1745
1746                    if (state.isVerificationComplete()) {
1747                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1748                    } else {
1749                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1750                                "IntentFilter verification with token:" + verificationId
1751                                + " was not said to be complete");
1752                    }
1753
1754                    break;
1755                }
1756            }
1757        }
1758    }
1759
1760    private StorageEventListener mStorageListener = new StorageEventListener() {
1761        @Override
1762        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1763            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1764                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1765                    final String volumeUuid = vol.getFsUuid();
1766
1767                    // Clean up any users or apps that were removed or recreated
1768                    // while this volume was missing
1769                    reconcileUsers(volumeUuid);
1770                    reconcileApps(volumeUuid);
1771
1772                    // Clean up any install sessions that expired or were
1773                    // cancelled while this volume was missing
1774                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1775
1776                    loadPrivatePackages(vol);
1777
1778                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1779                    unloadPrivatePackages(vol);
1780                }
1781            }
1782
1783            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1784                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1785                    updateExternalMediaStatus(true, false);
1786                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1787                    updateExternalMediaStatus(false, false);
1788                }
1789            }
1790        }
1791
1792        @Override
1793        public void onVolumeForgotten(String fsUuid) {
1794            if (TextUtils.isEmpty(fsUuid)) {
1795                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1796                return;
1797            }
1798
1799            // Remove any apps installed on the forgotten volume
1800            synchronized (mPackages) {
1801                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1802                for (PackageSetting ps : packages) {
1803                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1804                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1805                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1806                }
1807
1808                mSettings.onVolumeForgotten(fsUuid);
1809                mSettings.writeLPr();
1810            }
1811        }
1812    };
1813
1814    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1815            String[] grantedPermissions) {
1816        if (userId >= UserHandle.USER_SYSTEM) {
1817            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1818        } else if (userId == UserHandle.USER_ALL) {
1819            final int[] userIds;
1820            synchronized (mPackages) {
1821                userIds = UserManagerService.getInstance().getUserIds();
1822            }
1823            for (int someUserId : userIds) {
1824                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1825            }
1826        }
1827
1828        // We could have touched GID membership, so flush out packages.list
1829        synchronized (mPackages) {
1830            mSettings.writePackageListLPr();
1831        }
1832    }
1833
1834    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1835            String[] grantedPermissions) {
1836        SettingBase sb = (SettingBase) pkg.mExtras;
1837        if (sb == null) {
1838            return;
1839        }
1840
1841        PermissionsState permissionsState = sb.getPermissionsState();
1842
1843        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1844                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1845
1846        synchronized (mPackages) {
1847            for (String permission : pkg.requestedPermissions) {
1848                BasePermission bp = mSettings.mPermissions.get(permission);
1849                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1850                        && (grantedPermissions == null
1851                               || ArrayUtils.contains(grantedPermissions, permission))) {
1852                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1853                    // Installer cannot change immutable permissions.
1854                    if ((flags & immutableFlags) == 0) {
1855                        grantRuntimePermission(pkg.packageName, permission, userId);
1856                    }
1857                }
1858            }
1859        }
1860    }
1861
1862    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1863        Bundle extras = null;
1864        switch (res.returnCode) {
1865            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1866                extras = new Bundle();
1867                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1868                        res.origPermission);
1869                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1870                        res.origPackage);
1871                break;
1872            }
1873            case PackageManager.INSTALL_SUCCEEDED: {
1874                extras = new Bundle();
1875                extras.putBoolean(Intent.EXTRA_REPLACING,
1876                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1877                break;
1878            }
1879        }
1880        return extras;
1881    }
1882
1883    void scheduleWriteSettingsLocked() {
1884        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1885            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1886        }
1887    }
1888
1889    void scheduleWritePackageRestrictionsLocked(int userId) {
1890        if (!sUserManager.exists(userId)) return;
1891        mDirtyUsers.add(userId);
1892        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1893            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1894        }
1895    }
1896
1897    public static PackageManagerService main(Context context, Installer installer,
1898            boolean factoryTest, boolean onlyCore) {
1899        PackageManagerService m = new PackageManagerService(context, installer,
1900                factoryTest, onlyCore);
1901        m.enableSystemUserPackages();
1902        ServiceManager.addService("package", m);
1903        return m;
1904    }
1905
1906    private void enableSystemUserPackages() {
1907        if (!UserManager.isSplitSystemUser()) {
1908            return;
1909        }
1910        // For system user, enable apps based on the following conditions:
1911        // - app is whitelisted or belong to one of these groups:
1912        //   -- system app which has no launcher icons
1913        //   -- system app which has INTERACT_ACROSS_USERS permission
1914        //   -- system IME app
1915        // - app is not in the blacklist
1916        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1917        Set<String> enableApps = new ArraySet<>();
1918        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1919                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1920                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1921        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1922        enableApps.addAll(wlApps);
1923        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1924                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1925        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1926        enableApps.removeAll(blApps);
1927        Log.i(TAG, "Applications installed for system user: " + enableApps);
1928        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1929                UserHandle.SYSTEM);
1930        final int allAppsSize = allAps.size();
1931        synchronized (mPackages) {
1932            for (int i = 0; i < allAppsSize; i++) {
1933                String pName = allAps.get(i);
1934                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1935                // Should not happen, but we shouldn't be failing if it does
1936                if (pkgSetting == null) {
1937                    continue;
1938                }
1939                boolean install = enableApps.contains(pName);
1940                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1941                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1942                            + " for system user");
1943                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1944                }
1945            }
1946        }
1947    }
1948
1949    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1950        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1951                Context.DISPLAY_SERVICE);
1952        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1953    }
1954
1955    public PackageManagerService(Context context, Installer installer,
1956            boolean factoryTest, boolean onlyCore) {
1957        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1958                SystemClock.uptimeMillis());
1959
1960        if (mSdkVersion <= 0) {
1961            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1962        }
1963
1964        mContext = context;
1965        mFactoryTest = factoryTest;
1966        mOnlyCore = onlyCore;
1967        mMetrics = new DisplayMetrics();
1968        mSettings = new Settings(mPackages);
1969        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1970                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1971        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1972                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1973        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1974                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1975        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1976                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1977        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1978                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1979        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1980                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1981
1982        String separateProcesses = SystemProperties.get("debug.separate_processes");
1983        if (separateProcesses != null && separateProcesses.length() > 0) {
1984            if ("*".equals(separateProcesses)) {
1985                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1986                mSeparateProcesses = null;
1987                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1988            } else {
1989                mDefParseFlags = 0;
1990                mSeparateProcesses = separateProcesses.split(",");
1991                Slog.w(TAG, "Running with debug.separate_processes: "
1992                        + separateProcesses);
1993            }
1994        } else {
1995            mDefParseFlags = 0;
1996            mSeparateProcesses = null;
1997        }
1998
1999        mInstaller = installer;
2000        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2001                "*dexopt*");
2002        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2003
2004        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2005                FgThread.get().getLooper());
2006
2007        getDefaultDisplayMetrics(context, mMetrics);
2008
2009        SystemConfig systemConfig = SystemConfig.getInstance();
2010        mGlobalGids = systemConfig.getGlobalGids();
2011        mSystemPermissions = systemConfig.getSystemPermissions();
2012        mAvailableFeatures = systemConfig.getAvailableFeatures();
2013
2014        synchronized (mInstallLock) {
2015        // writer
2016        synchronized (mPackages) {
2017            mHandlerThread = new ServiceThread(TAG,
2018                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2019            mHandlerThread.start();
2020            mHandler = new PackageHandler(mHandlerThread.getLooper());
2021            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2022
2023            File dataDir = Environment.getDataDirectory();
2024            mAppInstallDir = new File(dataDir, "app");
2025            mAppLib32InstallDir = new File(dataDir, "app-lib");
2026            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2027            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2028            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2029
2030            sUserManager = new UserManagerService(context, this, mPackages);
2031
2032            // Propagate permission configuration in to package manager.
2033            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2034                    = systemConfig.getPermissions();
2035            for (int i=0; i<permConfig.size(); i++) {
2036                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2037                BasePermission bp = mSettings.mPermissions.get(perm.name);
2038                if (bp == null) {
2039                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2040                    mSettings.mPermissions.put(perm.name, bp);
2041                }
2042                if (perm.gids != null) {
2043                    bp.setGids(perm.gids, perm.perUser);
2044                }
2045            }
2046
2047            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2048            for (int i=0; i<libConfig.size(); i++) {
2049                mSharedLibraries.put(libConfig.keyAt(i),
2050                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2051            }
2052
2053            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2054
2055            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2056
2057            String customResolverActivity = Resources.getSystem().getString(
2058                    R.string.config_customResolverActivity);
2059            if (TextUtils.isEmpty(customResolverActivity)) {
2060                customResolverActivity = null;
2061            } else {
2062                mCustomResolverComponentName = ComponentName.unflattenFromString(
2063                        customResolverActivity);
2064            }
2065
2066            long startTime = SystemClock.uptimeMillis();
2067
2068            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2069                    startTime);
2070
2071            // Set flag to monitor and not change apk file paths when
2072            // scanning install directories.
2073            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2074
2075            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2076            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2077
2078            if (bootClassPath == null) {
2079                Slog.w(TAG, "No BOOTCLASSPATH found!");
2080            }
2081
2082            if (systemServerClassPath == null) {
2083                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2084            }
2085
2086            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2087            final String[] dexCodeInstructionSets =
2088                    getDexCodeInstructionSets(
2089                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2090
2091            /**
2092             * Ensure all external libraries have had dexopt run on them.
2093             */
2094            if (mSharedLibraries.size() > 0) {
2095                // NOTE: For now, we're compiling these system "shared libraries"
2096                // (and framework jars) into all available architectures. It's possible
2097                // to compile them only when we come across an app that uses them (there's
2098                // already logic for that in scanPackageLI) but that adds some complexity.
2099                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2100                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2101                        final String lib = libEntry.path;
2102                        if (lib == null) {
2103                            continue;
2104                        }
2105
2106                        try {
2107                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2108                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2109                                // Shared libraries do not have profiles so we perform a full
2110                                // AOT compilation.
2111                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2112                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2113                                        StorageManager.UUID_PRIVATE_INTERNAL,
2114                                        false /*useProfiles*/);
2115                            }
2116                        } catch (FileNotFoundException e) {
2117                            Slog.w(TAG, "Library not found: " + lib);
2118                        } catch (IOException | InstallerException e) {
2119                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2120                                    + e.getMessage());
2121                        }
2122                    }
2123                }
2124            }
2125
2126            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2127
2128            final VersionInfo ver = mSettings.getInternalVersion();
2129            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2130            // when upgrading from pre-M, promote system app permissions from install to runtime
2131            mPromoteSystemApps =
2132                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2133
2134            // save off the names of pre-existing system packages prior to scanning; we don't
2135            // want to automatically grant runtime permissions for new system apps
2136            if (mPromoteSystemApps) {
2137                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2138                while (pkgSettingIter.hasNext()) {
2139                    PackageSetting ps = pkgSettingIter.next();
2140                    if (isSystemApp(ps)) {
2141                        mExistingSystemPackages.add(ps.name);
2142                    }
2143                }
2144            }
2145
2146            // Collect vendor overlay packages.
2147            // (Do this before scanning any apps.)
2148            // For security and version matching reason, only consider
2149            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2150            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2151            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2152                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2153
2154            // Find base frameworks (resource packages without code).
2155            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2156                    | PackageParser.PARSE_IS_SYSTEM_DIR
2157                    | PackageParser.PARSE_IS_PRIVILEGED,
2158                    scanFlags | SCAN_NO_DEX, 0);
2159
2160            // Collected privileged system packages.
2161            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2162            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2163                    | PackageParser.PARSE_IS_SYSTEM_DIR
2164                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2165
2166            // Collect ordinary system packages.
2167            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2168            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2169                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2170
2171            // Collect all vendor packages.
2172            File vendorAppDir = new File("/vendor/app");
2173            try {
2174                vendorAppDir = vendorAppDir.getCanonicalFile();
2175            } catch (IOException e) {
2176                // failed to look up canonical path, continue with original one
2177            }
2178            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2179                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2180
2181            // Collect all OEM packages.
2182            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2183            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2184                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2185
2186            // Prune any system packages that no longer exist.
2187            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2188            if (!mOnlyCore) {
2189                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2190                while (psit.hasNext()) {
2191                    PackageSetting ps = psit.next();
2192
2193                    /*
2194                     * If this is not a system app, it can't be a
2195                     * disable system app.
2196                     */
2197                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2198                        continue;
2199                    }
2200
2201                    /*
2202                     * If the package is scanned, it's not erased.
2203                     */
2204                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2205                    if (scannedPkg != null) {
2206                        /*
2207                         * If the system app is both scanned and in the
2208                         * disabled packages list, then it must have been
2209                         * added via OTA. Remove it from the currently
2210                         * scanned package so the previously user-installed
2211                         * application can be scanned.
2212                         */
2213                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2214                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2215                                    + ps.name + "; removing system app.  Last known codePath="
2216                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2217                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2218                                    + scannedPkg.mVersionCode);
2219                            removePackageLI(ps, true);
2220                            mExpectingBetter.put(ps.name, ps.codePath);
2221                        }
2222
2223                        continue;
2224                    }
2225
2226                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2227                        psit.remove();
2228                        logCriticalInfo(Log.WARN, "System package " + ps.name
2229                                + " no longer exists; wiping its data");
2230                        removeDataDirsLI(null, ps.name);
2231                    } else {
2232                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2233                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2234                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2235                        }
2236                    }
2237                }
2238            }
2239
2240            //look for any incomplete package installations
2241            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2242            //clean up list
2243            for(int i = 0; i < deletePkgsList.size(); i++) {
2244                //clean up here
2245                cleanupInstallFailedPackage(deletePkgsList.get(i));
2246            }
2247            //delete tmp files
2248            deleteTempPackageFiles();
2249
2250            // Remove any shared userIDs that have no associated packages
2251            mSettings.pruneSharedUsersLPw();
2252
2253            if (!mOnlyCore) {
2254                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2255                        SystemClock.uptimeMillis());
2256                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2257
2258                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2259                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2260
2261                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2262                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2263
2264                /**
2265                 * Remove disable package settings for any updated system
2266                 * apps that were removed via an OTA. If they're not a
2267                 * previously-updated app, remove them completely.
2268                 * Otherwise, just revoke their system-level permissions.
2269                 */
2270                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2271                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2272                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2273
2274                    String msg;
2275                    if (deletedPkg == null) {
2276                        msg = "Updated system package " + deletedAppName
2277                                + " no longer exists; wiping its data";
2278                        removeDataDirsLI(null, deletedAppName);
2279                    } else {
2280                        msg = "Updated system app + " + deletedAppName
2281                                + " no longer present; removing system privileges for "
2282                                + deletedAppName;
2283
2284                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2285
2286                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2287                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2288                    }
2289                    logCriticalInfo(Log.WARN, msg);
2290                }
2291
2292                /**
2293                 * Make sure all system apps that we expected to appear on
2294                 * the userdata partition actually showed up. If they never
2295                 * appeared, crawl back and revive the system version.
2296                 */
2297                for (int i = 0; i < mExpectingBetter.size(); i++) {
2298                    final String packageName = mExpectingBetter.keyAt(i);
2299                    if (!mPackages.containsKey(packageName)) {
2300                        final File scanFile = mExpectingBetter.valueAt(i);
2301
2302                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2303                                + " but never showed up; reverting to system");
2304
2305                        final int reparseFlags;
2306                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2307                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2308                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2309                                    | PackageParser.PARSE_IS_PRIVILEGED;
2310                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2311                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2312                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2313                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2314                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2315                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2316                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2317                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2318                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2319                        } else {
2320                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2321                            continue;
2322                        }
2323
2324                        mSettings.enableSystemPackageLPw(packageName);
2325
2326                        try {
2327                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2328                        } catch (PackageManagerException e) {
2329                            Slog.e(TAG, "Failed to parse original system package: "
2330                                    + e.getMessage());
2331                        }
2332                    }
2333                }
2334            }
2335            mExpectingBetter.clear();
2336
2337            // Now that we know all of the shared libraries, update all clients to have
2338            // the correct library paths.
2339            updateAllSharedLibrariesLPw();
2340
2341            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2342                // NOTE: We ignore potential failures here during a system scan (like
2343                // the rest of the commands above) because there's precious little we
2344                // can do about it. A settings error is reported, though.
2345                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2346                        false /* boot complete */);
2347            }
2348
2349            // Now that we know all the packages we are keeping,
2350            // read and update their last usage times.
2351            mPackageUsage.readLP();
2352
2353            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2354                    SystemClock.uptimeMillis());
2355            Slog.i(TAG, "Time to scan packages: "
2356                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2357                    + " seconds");
2358
2359            // If the platform SDK has changed since the last time we booted,
2360            // we need to re-grant app permission to catch any new ones that
2361            // appear.  This is really a hack, and means that apps can in some
2362            // cases get permissions that the user didn't initially explicitly
2363            // allow...  it would be nice to have some better way to handle
2364            // this situation.
2365            int updateFlags = UPDATE_PERMISSIONS_ALL;
2366            if (ver.sdkVersion != mSdkVersion) {
2367                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2368                        + mSdkVersion + "; regranting permissions for internal storage");
2369                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2370            }
2371            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2372            ver.sdkVersion = mSdkVersion;
2373
2374            // If this is the first boot or an update from pre-M, and it is a normal
2375            // boot, then we need to initialize the default preferred apps across
2376            // all defined users.
2377            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2378                for (UserInfo user : sUserManager.getUsers(true)) {
2379                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2380                    applyFactoryDefaultBrowserLPw(user.id);
2381                    primeDomainVerificationsLPw(user.id);
2382                }
2383            }
2384
2385            // Prepare storage for system user really early during boot,
2386            // since core system apps like SettingsProvider and SystemUI
2387            // can't wait for user to start
2388            final int flags;
2389            if (StorageManager.isFileBasedEncryptionEnabled()) {
2390                flags = StorageManager.FLAG_STORAGE_DE;
2391            } else {
2392                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2393            }
2394            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2395
2396            // If this is first boot after an OTA, and a normal boot, then
2397            // we need to clear code cache directories.
2398            if (mIsUpgrade && !onlyCore) {
2399                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2400                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2401                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2402                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2403                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2404                    }
2405                }
2406                ver.fingerprint = Build.FINGERPRINT;
2407            }
2408
2409            checkDefaultBrowser();
2410
2411            // clear only after permissions and other defaults have been updated
2412            mExistingSystemPackages.clear();
2413            mPromoteSystemApps = false;
2414
2415            // All the changes are done during package scanning.
2416            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2417
2418            // can downgrade to reader
2419            mSettings.writeLPr();
2420
2421            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2422                    SystemClock.uptimeMillis());
2423
2424            if (!mOnlyCore) {
2425                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2426                mRequiredInstallerPackage = getRequiredInstallerLPr();
2427                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2428                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2429                        mIntentFilterVerifierComponent);
2430            } else {
2431                mRequiredVerifierPackage = null;
2432                mRequiredInstallerPackage = null;
2433                mIntentFilterVerifierComponent = null;
2434                mIntentFilterVerifier = null;
2435            }
2436
2437            mInstallerService = new PackageInstallerService(context, this);
2438
2439            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2440            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2441            // both the installer and resolver must be present to enable ephemeral
2442            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2443                if (DEBUG_EPHEMERAL) {
2444                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2445                            + " installer:" + ephemeralInstallerComponent);
2446                }
2447                mEphemeralResolverComponent = ephemeralResolverComponent;
2448                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2449                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2450                mEphemeralResolverConnection =
2451                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2452            } else {
2453                if (DEBUG_EPHEMERAL) {
2454                    final String missingComponent =
2455                            (ephemeralResolverComponent == null)
2456                            ? (ephemeralInstallerComponent == null)
2457                                    ? "resolver and installer"
2458                                    : "resolver"
2459                            : "installer";
2460                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2461                }
2462                mEphemeralResolverComponent = null;
2463                mEphemeralInstallerComponent = null;
2464                mEphemeralResolverConnection = null;
2465            }
2466
2467            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2468        } // synchronized (mPackages)
2469        } // synchronized (mInstallLock)
2470
2471        // Now after opening every single application zip, make sure they
2472        // are all flushed.  Not really needed, but keeps things nice and
2473        // tidy.
2474        Runtime.getRuntime().gc();
2475
2476        // The initial scanning above does many calls into installd while
2477        // holding the mPackages lock, but we're mostly interested in yelling
2478        // once we have a booted system.
2479        mInstaller.setWarnIfHeld(mPackages);
2480
2481        // Expose private service for system components to use.
2482        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2483    }
2484
2485    @Override
2486    public boolean isFirstBoot() {
2487        return !mRestoredSettings;
2488    }
2489
2490    @Override
2491    public boolean isOnlyCoreApps() {
2492        return mOnlyCore;
2493    }
2494
2495    @Override
2496    public boolean isUpgrade() {
2497        return mIsUpgrade;
2498    }
2499
2500    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2501        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2502
2503        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2504                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2505        if (matches.size() == 1) {
2506            return matches.get(0).getComponentInfo().packageName;
2507        } else {
2508            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2509            return null;
2510        }
2511    }
2512
2513    private @NonNull String getRequiredInstallerLPr() {
2514        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2515        intent.addCategory(Intent.CATEGORY_DEFAULT);
2516        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2517
2518        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2519                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2520        if (matches.size() == 1) {
2521            return matches.get(0).getComponentInfo().packageName;
2522        } else {
2523            throw new RuntimeException("There must be exactly one installer; found " + matches);
2524        }
2525    }
2526
2527    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2528        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2529
2530        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2531                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2532        ResolveInfo best = null;
2533        final int N = matches.size();
2534        for (int i = 0; i < N; i++) {
2535            final ResolveInfo cur = matches.get(i);
2536            final String packageName = cur.getComponentInfo().packageName;
2537            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2538                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2539                continue;
2540            }
2541
2542            if (best == null || cur.priority > best.priority) {
2543                best = cur;
2544            }
2545        }
2546
2547        if (best != null) {
2548            return best.getComponentInfo().getComponentName();
2549        } else {
2550            throw new RuntimeException("There must be at least one intent filter verifier");
2551        }
2552    }
2553
2554    private @Nullable ComponentName getEphemeralResolverLPr() {
2555        final String[] packageArray =
2556                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2557        if (packageArray.length == 0) {
2558            if (DEBUG_EPHEMERAL) {
2559                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2560            }
2561            return null;
2562        }
2563
2564        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2565        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2566                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2567
2568        final int N = resolvers.size();
2569        if (N == 0) {
2570            if (DEBUG_EPHEMERAL) {
2571                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2572            }
2573            return null;
2574        }
2575
2576        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2577        for (int i = 0; i < N; i++) {
2578            final ResolveInfo info = resolvers.get(i);
2579
2580            if (info.serviceInfo == null) {
2581                continue;
2582            }
2583
2584            final String packageName = info.serviceInfo.packageName;
2585            if (!possiblePackages.contains(packageName)) {
2586                if (DEBUG_EPHEMERAL) {
2587                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2588                            + " pkg: " + packageName + ", info:" + info);
2589                }
2590                continue;
2591            }
2592
2593            if (DEBUG_EPHEMERAL) {
2594                Slog.v(TAG, "Ephemeral resolver found;"
2595                        + " pkg: " + packageName + ", info:" + info);
2596            }
2597            return new ComponentName(packageName, info.serviceInfo.name);
2598        }
2599        if (DEBUG_EPHEMERAL) {
2600            Slog.v(TAG, "Ephemeral resolver NOT found");
2601        }
2602        return null;
2603    }
2604
2605    private @Nullable ComponentName getEphemeralInstallerLPr() {
2606        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2607        intent.addCategory(Intent.CATEGORY_DEFAULT);
2608        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2609
2610        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2611                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2612        if (matches.size() == 0) {
2613            return null;
2614        } else if (matches.size() == 1) {
2615            return matches.get(0).getComponentInfo().getComponentName();
2616        } else {
2617            throw new RuntimeException(
2618                    "There must be at most one ephemeral installer; found " + matches);
2619        }
2620    }
2621
2622    private void primeDomainVerificationsLPw(int userId) {
2623        if (DEBUG_DOMAIN_VERIFICATION) {
2624            Slog.d(TAG, "Priming domain verifications in user " + userId);
2625        }
2626
2627        SystemConfig systemConfig = SystemConfig.getInstance();
2628        ArraySet<String> packages = systemConfig.getLinkedApps();
2629        ArraySet<String> domains = new ArraySet<String>();
2630
2631        for (String packageName : packages) {
2632            PackageParser.Package pkg = mPackages.get(packageName);
2633            if (pkg != null) {
2634                if (!pkg.isSystemApp()) {
2635                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2636                    continue;
2637                }
2638
2639                domains.clear();
2640                for (PackageParser.Activity a : pkg.activities) {
2641                    for (ActivityIntentInfo filter : a.intents) {
2642                        if (hasValidDomains(filter)) {
2643                            domains.addAll(filter.getHostsList());
2644                        }
2645                    }
2646                }
2647
2648                if (domains.size() > 0) {
2649                    if (DEBUG_DOMAIN_VERIFICATION) {
2650                        Slog.v(TAG, "      + " + packageName);
2651                    }
2652                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2653                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2654                    // and then 'always' in the per-user state actually used for intent resolution.
2655                    final IntentFilterVerificationInfo ivi;
2656                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2657                            new ArrayList<String>(domains));
2658                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2659                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2660                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2661                } else {
2662                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2663                            + "' does not handle web links");
2664                }
2665            } else {
2666                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2667            }
2668        }
2669
2670        scheduleWritePackageRestrictionsLocked(userId);
2671        scheduleWriteSettingsLocked();
2672    }
2673
2674    private void applyFactoryDefaultBrowserLPw(int userId) {
2675        // The default browser app's package name is stored in a string resource,
2676        // with a product-specific overlay used for vendor customization.
2677        String browserPkg = mContext.getResources().getString(
2678                com.android.internal.R.string.default_browser);
2679        if (!TextUtils.isEmpty(browserPkg)) {
2680            // non-empty string => required to be a known package
2681            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2682            if (ps == null) {
2683                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2684                browserPkg = null;
2685            } else {
2686                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2687            }
2688        }
2689
2690        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2691        // default.  If there's more than one, just leave everything alone.
2692        if (browserPkg == null) {
2693            calculateDefaultBrowserLPw(userId);
2694        }
2695    }
2696
2697    private void calculateDefaultBrowserLPw(int userId) {
2698        List<String> allBrowsers = resolveAllBrowserApps(userId);
2699        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2700        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2701    }
2702
2703    private List<String> resolveAllBrowserApps(int userId) {
2704        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2705        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2706                PackageManager.MATCH_ALL, userId);
2707
2708        final int count = list.size();
2709        List<String> result = new ArrayList<String>(count);
2710        for (int i=0; i<count; i++) {
2711            ResolveInfo info = list.get(i);
2712            if (info.activityInfo == null
2713                    || !info.handleAllWebDataURI
2714                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2715                    || result.contains(info.activityInfo.packageName)) {
2716                continue;
2717            }
2718            result.add(info.activityInfo.packageName);
2719        }
2720
2721        return result;
2722    }
2723
2724    private boolean packageIsBrowser(String packageName, int userId) {
2725        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2726                PackageManager.MATCH_ALL, userId);
2727        final int N = list.size();
2728        for (int i = 0; i < N; i++) {
2729            ResolveInfo info = list.get(i);
2730            if (packageName.equals(info.activityInfo.packageName)) {
2731                return true;
2732            }
2733        }
2734        return false;
2735    }
2736
2737    private void checkDefaultBrowser() {
2738        final int myUserId = UserHandle.myUserId();
2739        final String packageName = getDefaultBrowserPackageName(myUserId);
2740        if (packageName != null) {
2741            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2742            if (info == null) {
2743                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2744                synchronized (mPackages) {
2745                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2746                }
2747            }
2748        }
2749    }
2750
2751    @Override
2752    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2753            throws RemoteException {
2754        try {
2755            return super.onTransact(code, data, reply, flags);
2756        } catch (RuntimeException e) {
2757            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2758                Slog.wtf(TAG, "Package Manager Crash", e);
2759            }
2760            throw e;
2761        }
2762    }
2763
2764    void cleanupInstallFailedPackage(PackageSetting ps) {
2765        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2766
2767        removeDataDirsLI(ps.volumeUuid, ps.name);
2768        if (ps.codePath != null) {
2769            removeCodePathLI(ps.codePath);
2770        }
2771        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2772            if (ps.resourcePath.isDirectory()) {
2773                FileUtils.deleteContents(ps.resourcePath);
2774            }
2775            ps.resourcePath.delete();
2776        }
2777        mSettings.removePackageLPw(ps.name);
2778    }
2779
2780    static int[] appendInts(int[] cur, int[] add) {
2781        if (add == null) return cur;
2782        if (cur == null) return add;
2783        final int N = add.length;
2784        for (int i=0; i<N; i++) {
2785            cur = appendInt(cur, add[i]);
2786        }
2787        return cur;
2788    }
2789
2790    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2791        if (!sUserManager.exists(userId)) return null;
2792        final PackageSetting ps = (PackageSetting) p.mExtras;
2793        if (ps == null) {
2794            return null;
2795        }
2796
2797        final PermissionsState permissionsState = ps.getPermissionsState();
2798
2799        final int[] gids = permissionsState.computeGids(userId);
2800        final Set<String> permissions = permissionsState.getPermissions(userId);
2801        final PackageUserState state = ps.readUserState(userId);
2802
2803        return PackageParser.generatePackageInfo(p, gids, flags,
2804                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2805    }
2806
2807    @Override
2808    public void checkPackageStartable(String packageName, int userId) {
2809        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2810
2811        synchronized (mPackages) {
2812            final PackageSetting ps = mSettings.mPackages.get(packageName);
2813            if (ps == null) {
2814                throw new SecurityException("Package " + packageName + " was not found!");
2815            }
2816
2817            if (ps.frozen) {
2818                throw new SecurityException("Package " + packageName + " is currently frozen!");
2819            }
2820
2821            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2822                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2823                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2824            }
2825        }
2826    }
2827
2828    @Override
2829    public boolean isPackageAvailable(String packageName, int userId) {
2830        if (!sUserManager.exists(userId)) return false;
2831        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2832        synchronized (mPackages) {
2833            PackageParser.Package p = mPackages.get(packageName);
2834            if (p != null) {
2835                final PackageSetting ps = (PackageSetting) p.mExtras;
2836                if (ps != null) {
2837                    final PackageUserState state = ps.readUserState(userId);
2838                    if (state != null) {
2839                        return PackageParser.isAvailable(state);
2840                    }
2841                }
2842            }
2843        }
2844        return false;
2845    }
2846
2847    @Override
2848    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        flags = updateFlagsForPackage(flags, userId, packageName);
2851        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2852        // reader
2853        synchronized (mPackages) {
2854            PackageParser.Package p = mPackages.get(packageName);
2855            if (DEBUG_PACKAGE_INFO)
2856                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2857            if (p != null) {
2858                return generatePackageInfo(p, flags, userId);
2859            }
2860            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2861                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2862            }
2863        }
2864        return null;
2865    }
2866
2867    @Override
2868    public String[] currentToCanonicalPackageNames(String[] names) {
2869        String[] out = new String[names.length];
2870        // reader
2871        synchronized (mPackages) {
2872            for (int i=names.length-1; i>=0; i--) {
2873                PackageSetting ps = mSettings.mPackages.get(names[i]);
2874                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2875            }
2876        }
2877        return out;
2878    }
2879
2880    @Override
2881    public String[] canonicalToCurrentPackageNames(String[] names) {
2882        String[] out = new String[names.length];
2883        // reader
2884        synchronized (mPackages) {
2885            for (int i=names.length-1; i>=0; i--) {
2886                String cur = mSettings.mRenamedPackages.get(names[i]);
2887                out[i] = cur != null ? cur : names[i];
2888            }
2889        }
2890        return out;
2891    }
2892
2893    @Override
2894    public int getPackageUid(String packageName, int flags, int userId) {
2895        if (!sUserManager.exists(userId)) return -1;
2896        flags = updateFlagsForPackage(flags, userId, packageName);
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2898
2899        // reader
2900        synchronized (mPackages) {
2901            final PackageParser.Package p = mPackages.get(packageName);
2902            if (p != null && p.isMatch(flags)) {
2903                return UserHandle.getUid(userId, p.applicationInfo.uid);
2904            }
2905            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2906                final PackageSetting ps = mSettings.mPackages.get(packageName);
2907                if (ps != null && ps.isMatch(flags)) {
2908                    return UserHandle.getUid(userId, ps.appId);
2909                }
2910            }
2911        }
2912
2913        return -1;
2914    }
2915
2916    @Override
2917    public int[] getPackageGids(String packageName, int flags, int userId) {
2918        if (!sUserManager.exists(userId)) return null;
2919        flags = updateFlagsForPackage(flags, userId, packageName);
2920        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2921                "getPackageGids");
2922
2923        // reader
2924        synchronized (mPackages) {
2925            final PackageParser.Package p = mPackages.get(packageName);
2926            if (p != null && p.isMatch(flags)) {
2927                PackageSetting ps = (PackageSetting) p.mExtras;
2928                return ps.getPermissionsState().computeGids(userId);
2929            }
2930            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2931                final PackageSetting ps = mSettings.mPackages.get(packageName);
2932                if (ps != null && ps.isMatch(flags)) {
2933                    return ps.getPermissionsState().computeGids(userId);
2934                }
2935            }
2936        }
2937
2938        return null;
2939    }
2940
2941    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2942        if (bp.perm != null) {
2943            return PackageParser.generatePermissionInfo(bp.perm, flags);
2944        }
2945        PermissionInfo pi = new PermissionInfo();
2946        pi.name = bp.name;
2947        pi.packageName = bp.sourcePackage;
2948        pi.nonLocalizedLabel = bp.name;
2949        pi.protectionLevel = bp.protectionLevel;
2950        return pi;
2951    }
2952
2953    @Override
2954    public PermissionInfo getPermissionInfo(String name, int flags) {
2955        // reader
2956        synchronized (mPackages) {
2957            final BasePermission p = mSettings.mPermissions.get(name);
2958            if (p != null) {
2959                return generatePermissionInfo(p, flags);
2960            }
2961            return null;
2962        }
2963    }
2964
2965    @Override
2966    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2967        // reader
2968        synchronized (mPackages) {
2969            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2970            for (BasePermission p : mSettings.mPermissions.values()) {
2971                if (group == null) {
2972                    if (p.perm == null || p.perm.info.group == null) {
2973                        out.add(generatePermissionInfo(p, flags));
2974                    }
2975                } else {
2976                    if (p.perm != null && group.equals(p.perm.info.group)) {
2977                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2978                    }
2979                }
2980            }
2981
2982            if (out.size() > 0) {
2983                return out;
2984            }
2985            return mPermissionGroups.containsKey(group) ? out : null;
2986        }
2987    }
2988
2989    @Override
2990    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2991        // reader
2992        synchronized (mPackages) {
2993            return PackageParser.generatePermissionGroupInfo(
2994                    mPermissionGroups.get(name), flags);
2995        }
2996    }
2997
2998    @Override
2999    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3000        // reader
3001        synchronized (mPackages) {
3002            final int N = mPermissionGroups.size();
3003            ArrayList<PermissionGroupInfo> out
3004                    = new ArrayList<PermissionGroupInfo>(N);
3005            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3006                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3007            }
3008            return out;
3009        }
3010    }
3011
3012    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3013            int userId) {
3014        if (!sUserManager.exists(userId)) return null;
3015        PackageSetting ps = mSettings.mPackages.get(packageName);
3016        if (ps != null) {
3017            if (ps.pkg == null) {
3018                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3019                        flags, userId);
3020                if (pInfo != null) {
3021                    return pInfo.applicationInfo;
3022                }
3023                return null;
3024            }
3025            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3026                    ps.readUserState(userId), userId);
3027        }
3028        return null;
3029    }
3030
3031    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3032            int userId) {
3033        if (!sUserManager.exists(userId)) return null;
3034        PackageSetting ps = mSettings.mPackages.get(packageName);
3035        if (ps != null) {
3036            PackageParser.Package pkg = ps.pkg;
3037            if (pkg == null) {
3038                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3039                    return null;
3040                }
3041                // Only data remains, so we aren't worried about code paths
3042                pkg = new PackageParser.Package(packageName);
3043                pkg.applicationInfo.packageName = packageName;
3044                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3045                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3046                pkg.applicationInfo.uid = ps.appId;
3047                pkg.applicationInfo.initForUser(userId);
3048                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3049                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3050            }
3051            return generatePackageInfo(pkg, flags, userId);
3052        }
3053        return null;
3054    }
3055
3056    @Override
3057    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3058        if (!sUserManager.exists(userId)) return null;
3059        flags = updateFlagsForApplication(flags, userId, packageName);
3060        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3061        // writer
3062        synchronized (mPackages) {
3063            PackageParser.Package p = mPackages.get(packageName);
3064            if (DEBUG_PACKAGE_INFO) Log.v(
3065                    TAG, "getApplicationInfo " + packageName
3066                    + ": " + p);
3067            if (p != null) {
3068                PackageSetting ps = mSettings.mPackages.get(packageName);
3069                if (ps == null) return null;
3070                // Note: isEnabledLP() does not apply here - always return info
3071                return PackageParser.generateApplicationInfo(
3072                        p, flags, ps.readUserState(userId), userId);
3073            }
3074            if ("android".equals(packageName)||"system".equals(packageName)) {
3075                return mAndroidApplication;
3076            }
3077            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3078                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3079            }
3080        }
3081        return null;
3082    }
3083
3084    @Override
3085    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3086            final IPackageDataObserver observer) {
3087        mContext.enforceCallingOrSelfPermission(
3088                android.Manifest.permission.CLEAR_APP_CACHE, null);
3089        // Queue up an async operation since clearing cache may take a little while.
3090        mHandler.post(new Runnable() {
3091            public void run() {
3092                mHandler.removeCallbacks(this);
3093                boolean success = true;
3094                synchronized (mInstallLock) {
3095                    try {
3096                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3097                    } catch (InstallerException e) {
3098                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3099                        success = false;
3100                    }
3101                }
3102                if (observer != null) {
3103                    try {
3104                        observer.onRemoveCompleted(null, success);
3105                    } catch (RemoteException e) {
3106                        Slog.w(TAG, "RemoveException when invoking call back");
3107                    }
3108                }
3109            }
3110        });
3111    }
3112
3113    @Override
3114    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3115            final IntentSender pi) {
3116        mContext.enforceCallingOrSelfPermission(
3117                android.Manifest.permission.CLEAR_APP_CACHE, null);
3118        // Queue up an async operation since clearing cache may take a little while.
3119        mHandler.post(new Runnable() {
3120            public void run() {
3121                mHandler.removeCallbacks(this);
3122                boolean success = true;
3123                synchronized (mInstallLock) {
3124                    try {
3125                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3126                    } catch (InstallerException e) {
3127                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3128                        success = false;
3129                    }
3130                }
3131                if(pi != null) {
3132                    try {
3133                        // Callback via pending intent
3134                        int code = success ? 1 : 0;
3135                        pi.sendIntent(null, code, null,
3136                                null, null);
3137                    } catch (SendIntentException e1) {
3138                        Slog.i(TAG, "Failed to send pending intent");
3139                    }
3140                }
3141            }
3142        });
3143    }
3144
3145    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3146        synchronized (mInstallLock) {
3147            try {
3148                mInstaller.freeCache(volumeUuid, freeStorageSize);
3149            } catch (InstallerException e) {
3150                throw new IOException("Failed to free enough space", e);
3151            }
3152        }
3153    }
3154
3155    /**
3156     * Return if the user key is currently unlocked.
3157     */
3158    private boolean isUserKeyUnlocked(int userId) {
3159        if (StorageManager.isFileBasedEncryptionEnabled()) {
3160            final IMountService mount = IMountService.Stub
3161                    .asInterface(ServiceManager.getService("mount"));
3162            if (mount == null) {
3163                Slog.w(TAG, "Early during boot, assuming locked");
3164                return false;
3165            }
3166            final long token = Binder.clearCallingIdentity();
3167            try {
3168                return mount.isUserKeyUnlocked(userId);
3169            } catch (RemoteException e) {
3170                throw e.rethrowAsRuntimeException();
3171            } finally {
3172                Binder.restoreCallingIdentity(token);
3173            }
3174        } else {
3175            return true;
3176        }
3177    }
3178
3179    /**
3180     * Update given flags based on encryption status of current user.
3181     */
3182    private int updateFlags(int flags, int userId) {
3183        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3184                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3185            // Caller expressed an explicit opinion about what encryption
3186            // aware/unaware components they want to see, so fall through and
3187            // give them what they want
3188        } else {
3189            // Caller expressed no opinion, so match based on user state
3190            if (isUserKeyUnlocked(userId)) {
3191                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3192            } else {
3193                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3194            }
3195        }
3196
3197        // Safe mode means we should ignore any third-party apps
3198        if (mSafeMode) {
3199            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3200        }
3201
3202        return flags;
3203    }
3204
3205    /**
3206     * Update given flags when being used to request {@link PackageInfo}.
3207     */
3208    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3209        boolean triaged = true;
3210        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3211                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3212            // Caller is asking for component details, so they'd better be
3213            // asking for specific encryption matching behavior, or be triaged
3214            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3215                    | PackageManager.MATCH_ENCRYPTION_AWARE
3216                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3217                triaged = false;
3218            }
3219        }
3220        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3221                | PackageManager.MATCH_SYSTEM_ONLY
3222                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3223            triaged = false;
3224        }
3225        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3226            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3227                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3228        }
3229        return updateFlags(flags, userId);
3230    }
3231
3232    /**
3233     * Update given flags when being used to request {@link ApplicationInfo}.
3234     */
3235    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3236        return updateFlagsForPackage(flags, userId, cookie);
3237    }
3238
3239    /**
3240     * Update given flags when being used to request {@link ComponentInfo}.
3241     */
3242    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3243        if (cookie instanceof Intent) {
3244            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3245                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3246            }
3247        }
3248
3249        boolean triaged = true;
3250        // Caller is asking for component details, so they'd better be
3251        // asking for specific encryption matching behavior, or be triaged
3252        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3253                | PackageManager.MATCH_ENCRYPTION_AWARE
3254                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3255            triaged = false;
3256        }
3257        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3258            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3259                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3260        }
3261        return updateFlags(flags, userId);
3262    }
3263
3264    /**
3265     * Update given flags when being used to request {@link ResolveInfo}.
3266     */
3267    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3268        return updateFlagsForComponent(flags, userId, cookie);
3269    }
3270
3271    @Override
3272    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3273        if (!sUserManager.exists(userId)) return null;
3274        flags = updateFlagsForComponent(flags, userId, component);
3275        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3276        synchronized (mPackages) {
3277            PackageParser.Activity a = mActivities.mActivities.get(component);
3278
3279            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3280            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3281                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3282                if (ps == null) return null;
3283                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3284                        userId);
3285            }
3286            if (mResolveComponentName.equals(component)) {
3287                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3288                        new PackageUserState(), userId);
3289            }
3290        }
3291        return null;
3292    }
3293
3294    @Override
3295    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3296            String resolvedType) {
3297        synchronized (mPackages) {
3298            if (component.equals(mResolveComponentName)) {
3299                // The resolver supports EVERYTHING!
3300                return true;
3301            }
3302            PackageParser.Activity a = mActivities.mActivities.get(component);
3303            if (a == null) {
3304                return false;
3305            }
3306            for (int i=0; i<a.intents.size(); i++) {
3307                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3308                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3309                    return true;
3310                }
3311            }
3312            return false;
3313        }
3314    }
3315
3316    @Override
3317    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3318        if (!sUserManager.exists(userId)) return null;
3319        flags = updateFlagsForComponent(flags, userId, component);
3320        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3321        synchronized (mPackages) {
3322            PackageParser.Activity a = mReceivers.mActivities.get(component);
3323            if (DEBUG_PACKAGE_INFO) Log.v(
3324                TAG, "getReceiverInfo " + component + ": " + a);
3325            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3326                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3327                if (ps == null) return null;
3328                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3329                        userId);
3330            }
3331        }
3332        return null;
3333    }
3334
3335    @Override
3336    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3337        if (!sUserManager.exists(userId)) return null;
3338        flags = updateFlagsForComponent(flags, userId, component);
3339        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3340        synchronized (mPackages) {
3341            PackageParser.Service s = mServices.mServices.get(component);
3342            if (DEBUG_PACKAGE_INFO) Log.v(
3343                TAG, "getServiceInfo " + component + ": " + s);
3344            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3345                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3346                if (ps == null) return null;
3347                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3348                        userId);
3349            }
3350        }
3351        return null;
3352    }
3353
3354    @Override
3355    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3356        if (!sUserManager.exists(userId)) return null;
3357        flags = updateFlagsForComponent(flags, userId, component);
3358        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3359        synchronized (mPackages) {
3360            PackageParser.Provider p = mProviders.mProviders.get(component);
3361            if (DEBUG_PACKAGE_INFO) Log.v(
3362                TAG, "getProviderInfo " + component + ": " + p);
3363            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3364                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3365                if (ps == null) return null;
3366                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3367                        userId);
3368            }
3369        }
3370        return null;
3371    }
3372
3373    @Override
3374    public String[] getSystemSharedLibraryNames() {
3375        Set<String> libSet;
3376        synchronized (mPackages) {
3377            libSet = mSharedLibraries.keySet();
3378            int size = libSet.size();
3379            if (size > 0) {
3380                String[] libs = new String[size];
3381                libSet.toArray(libs);
3382                return libs;
3383            }
3384        }
3385        return null;
3386    }
3387
3388    @Override
3389    public FeatureInfo[] getSystemAvailableFeatures() {
3390        Collection<FeatureInfo> featSet;
3391        synchronized (mPackages) {
3392            featSet = mAvailableFeatures.values();
3393            int size = featSet.size();
3394            if (size > 0) {
3395                FeatureInfo[] features = new FeatureInfo[size+1];
3396                featSet.toArray(features);
3397                FeatureInfo fi = new FeatureInfo();
3398                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3399                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3400                features[size] = fi;
3401                return features;
3402            }
3403        }
3404        return null;
3405    }
3406
3407    @Override
3408    public boolean hasSystemFeature(String name) {
3409        synchronized (mPackages) {
3410            return mAvailableFeatures.containsKey(name);
3411        }
3412    }
3413
3414    @Override
3415    public int checkPermission(String permName, String pkgName, int userId) {
3416        if (!sUserManager.exists(userId)) {
3417            return PackageManager.PERMISSION_DENIED;
3418        }
3419
3420        synchronized (mPackages) {
3421            final PackageParser.Package p = mPackages.get(pkgName);
3422            if (p != null && p.mExtras != null) {
3423                final PackageSetting ps = (PackageSetting) p.mExtras;
3424                final PermissionsState permissionsState = ps.getPermissionsState();
3425                if (permissionsState.hasPermission(permName, userId)) {
3426                    return PackageManager.PERMISSION_GRANTED;
3427                }
3428                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3429                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3430                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3431                    return PackageManager.PERMISSION_GRANTED;
3432                }
3433            }
3434        }
3435
3436        return PackageManager.PERMISSION_DENIED;
3437    }
3438
3439    @Override
3440    public int checkUidPermission(String permName, int uid) {
3441        final int userId = UserHandle.getUserId(uid);
3442
3443        if (!sUserManager.exists(userId)) {
3444            return PackageManager.PERMISSION_DENIED;
3445        }
3446
3447        synchronized (mPackages) {
3448            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3449            if (obj != null) {
3450                final SettingBase ps = (SettingBase) obj;
3451                final PermissionsState permissionsState = ps.getPermissionsState();
3452                if (permissionsState.hasPermission(permName, userId)) {
3453                    return PackageManager.PERMISSION_GRANTED;
3454                }
3455                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3456                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3457                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3458                    return PackageManager.PERMISSION_GRANTED;
3459                }
3460            } else {
3461                ArraySet<String> perms = mSystemPermissions.get(uid);
3462                if (perms != null) {
3463                    if (perms.contains(permName)) {
3464                        return PackageManager.PERMISSION_GRANTED;
3465                    }
3466                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3467                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3468                        return PackageManager.PERMISSION_GRANTED;
3469                    }
3470                }
3471            }
3472        }
3473
3474        return PackageManager.PERMISSION_DENIED;
3475    }
3476
3477    @Override
3478    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3479        if (UserHandle.getCallingUserId() != userId) {
3480            mContext.enforceCallingPermission(
3481                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3482                    "isPermissionRevokedByPolicy for user " + userId);
3483        }
3484
3485        if (checkPermission(permission, packageName, userId)
3486                == PackageManager.PERMISSION_GRANTED) {
3487            return false;
3488        }
3489
3490        final long identity = Binder.clearCallingIdentity();
3491        try {
3492            final int flags = getPermissionFlags(permission, packageName, userId);
3493            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3494        } finally {
3495            Binder.restoreCallingIdentity(identity);
3496        }
3497    }
3498
3499    @Override
3500    public String getPermissionControllerPackageName() {
3501        synchronized (mPackages) {
3502            return mRequiredInstallerPackage;
3503        }
3504    }
3505
3506    /**
3507     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3508     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3509     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3510     * @param message the message to log on security exception
3511     */
3512    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3513            boolean checkShell, String message) {
3514        if (userId < 0) {
3515            throw new IllegalArgumentException("Invalid userId " + userId);
3516        }
3517        if (checkShell) {
3518            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3519        }
3520        if (userId == UserHandle.getUserId(callingUid)) return;
3521        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3522            if (requireFullPermission) {
3523                mContext.enforceCallingOrSelfPermission(
3524                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3525            } else {
3526                try {
3527                    mContext.enforceCallingOrSelfPermission(
3528                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3529                } catch (SecurityException se) {
3530                    mContext.enforceCallingOrSelfPermission(
3531                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3532                }
3533            }
3534        }
3535    }
3536
3537    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3538        if (callingUid == Process.SHELL_UID) {
3539            if (userHandle >= 0
3540                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3541                throw new SecurityException("Shell does not have permission to access user "
3542                        + userHandle);
3543            } else if (userHandle < 0) {
3544                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3545                        + Debug.getCallers(3));
3546            }
3547        }
3548    }
3549
3550    private BasePermission findPermissionTreeLP(String permName) {
3551        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3552            if (permName.startsWith(bp.name) &&
3553                    permName.length() > bp.name.length() &&
3554                    permName.charAt(bp.name.length()) == '.') {
3555                return bp;
3556            }
3557        }
3558        return null;
3559    }
3560
3561    private BasePermission checkPermissionTreeLP(String permName) {
3562        if (permName != null) {
3563            BasePermission bp = findPermissionTreeLP(permName);
3564            if (bp != null) {
3565                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3566                    return bp;
3567                }
3568                throw new SecurityException("Calling uid "
3569                        + Binder.getCallingUid()
3570                        + " is not allowed to add to permission tree "
3571                        + bp.name + " owned by uid " + bp.uid);
3572            }
3573        }
3574        throw new SecurityException("No permission tree found for " + permName);
3575    }
3576
3577    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3578        if (s1 == null) {
3579            return s2 == null;
3580        }
3581        if (s2 == null) {
3582            return false;
3583        }
3584        if (s1.getClass() != s2.getClass()) {
3585            return false;
3586        }
3587        return s1.equals(s2);
3588    }
3589
3590    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3591        if (pi1.icon != pi2.icon) return false;
3592        if (pi1.logo != pi2.logo) return false;
3593        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3594        if (!compareStrings(pi1.name, pi2.name)) return false;
3595        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3596        // We'll take care of setting this one.
3597        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3598        // These are not currently stored in settings.
3599        //if (!compareStrings(pi1.group, pi2.group)) return false;
3600        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3601        //if (pi1.labelRes != pi2.labelRes) return false;
3602        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3603        return true;
3604    }
3605
3606    int permissionInfoFootprint(PermissionInfo info) {
3607        int size = info.name.length();
3608        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3609        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3610        return size;
3611    }
3612
3613    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3614        int size = 0;
3615        for (BasePermission perm : mSettings.mPermissions.values()) {
3616            if (perm.uid == tree.uid) {
3617                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3618            }
3619        }
3620        return size;
3621    }
3622
3623    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3624        // We calculate the max size of permissions defined by this uid and throw
3625        // if that plus the size of 'info' would exceed our stated maximum.
3626        if (tree.uid != Process.SYSTEM_UID) {
3627            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3628            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3629                throw new SecurityException("Permission tree size cap exceeded");
3630            }
3631        }
3632    }
3633
3634    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3635        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3636            throw new SecurityException("Label must be specified in permission");
3637        }
3638        BasePermission tree = checkPermissionTreeLP(info.name);
3639        BasePermission bp = mSettings.mPermissions.get(info.name);
3640        boolean added = bp == null;
3641        boolean changed = true;
3642        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3643        if (added) {
3644            enforcePermissionCapLocked(info, tree);
3645            bp = new BasePermission(info.name, tree.sourcePackage,
3646                    BasePermission.TYPE_DYNAMIC);
3647        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3648            throw new SecurityException(
3649                    "Not allowed to modify non-dynamic permission "
3650                    + info.name);
3651        } else {
3652            if (bp.protectionLevel == fixedLevel
3653                    && bp.perm.owner.equals(tree.perm.owner)
3654                    && bp.uid == tree.uid
3655                    && comparePermissionInfos(bp.perm.info, info)) {
3656                changed = false;
3657            }
3658        }
3659        bp.protectionLevel = fixedLevel;
3660        info = new PermissionInfo(info);
3661        info.protectionLevel = fixedLevel;
3662        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3663        bp.perm.info.packageName = tree.perm.info.packageName;
3664        bp.uid = tree.uid;
3665        if (added) {
3666            mSettings.mPermissions.put(info.name, bp);
3667        }
3668        if (changed) {
3669            if (!async) {
3670                mSettings.writeLPr();
3671            } else {
3672                scheduleWriteSettingsLocked();
3673            }
3674        }
3675        return added;
3676    }
3677
3678    @Override
3679    public boolean addPermission(PermissionInfo info) {
3680        synchronized (mPackages) {
3681            return addPermissionLocked(info, false);
3682        }
3683    }
3684
3685    @Override
3686    public boolean addPermissionAsync(PermissionInfo info) {
3687        synchronized (mPackages) {
3688            return addPermissionLocked(info, true);
3689        }
3690    }
3691
3692    @Override
3693    public void removePermission(String name) {
3694        synchronized (mPackages) {
3695            checkPermissionTreeLP(name);
3696            BasePermission bp = mSettings.mPermissions.get(name);
3697            if (bp != null) {
3698                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3699                    throw new SecurityException(
3700                            "Not allowed to modify non-dynamic permission "
3701                            + name);
3702                }
3703                mSettings.mPermissions.remove(name);
3704                mSettings.writeLPr();
3705            }
3706        }
3707    }
3708
3709    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3710            BasePermission bp) {
3711        int index = pkg.requestedPermissions.indexOf(bp.name);
3712        if (index == -1) {
3713            throw new SecurityException("Package " + pkg.packageName
3714                    + " has not requested permission " + bp.name);
3715        }
3716        if (!bp.isRuntime() && !bp.isDevelopment()) {
3717            throw new SecurityException("Permission " + bp.name
3718                    + " is not a changeable permission type");
3719        }
3720    }
3721
3722    @Override
3723    public void grantRuntimePermission(String packageName, String name, final int userId) {
3724        if (!sUserManager.exists(userId)) {
3725            Log.e(TAG, "No such user:" + userId);
3726            return;
3727        }
3728
3729        mContext.enforceCallingOrSelfPermission(
3730                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3731                "grantRuntimePermission");
3732
3733        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3734                "grantRuntimePermission");
3735
3736        final int uid;
3737        final SettingBase sb;
3738
3739        synchronized (mPackages) {
3740            final PackageParser.Package pkg = mPackages.get(packageName);
3741            if (pkg == null) {
3742                throw new IllegalArgumentException("Unknown package: " + packageName);
3743            }
3744
3745            final BasePermission bp = mSettings.mPermissions.get(name);
3746            if (bp == null) {
3747                throw new IllegalArgumentException("Unknown permission: " + name);
3748            }
3749
3750            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3751
3752            // If a permission review is required for legacy apps we represent
3753            // their permissions as always granted runtime ones since we need
3754            // to keep the review required permission flag per user while an
3755            // install permission's state is shared across all users.
3756            if (Build.PERMISSIONS_REVIEW_REQUIRED
3757                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3758                    && bp.isRuntime()) {
3759                return;
3760            }
3761
3762            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3763            sb = (SettingBase) pkg.mExtras;
3764            if (sb == null) {
3765                throw new IllegalArgumentException("Unknown package: " + packageName);
3766            }
3767
3768            final PermissionsState permissionsState = sb.getPermissionsState();
3769
3770            final int flags = permissionsState.getPermissionFlags(name, userId);
3771            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3772                throw new SecurityException("Cannot grant system fixed permission "
3773                        + name + " for package " + packageName);
3774            }
3775
3776            if (bp.isDevelopment()) {
3777                // Development permissions must be handled specially, since they are not
3778                // normal runtime permissions.  For now they apply to all users.
3779                if (permissionsState.grantInstallPermission(bp) !=
3780                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3781                    scheduleWriteSettingsLocked();
3782                }
3783                return;
3784            }
3785
3786            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3787                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3788                return;
3789            }
3790
3791            final int result = permissionsState.grantRuntimePermission(bp, userId);
3792            switch (result) {
3793                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3794                    return;
3795                }
3796
3797                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3798                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3799                    mHandler.post(new Runnable() {
3800                        @Override
3801                        public void run() {
3802                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3803                        }
3804                    });
3805                }
3806                break;
3807            }
3808
3809            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3810
3811            // Not critical if that is lost - app has to request again.
3812            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3813        }
3814
3815        // Only need to do this if user is initialized. Otherwise it's a new user
3816        // and there are no processes running as the user yet and there's no need
3817        // to make an expensive call to remount processes for the changed permissions.
3818        if (READ_EXTERNAL_STORAGE.equals(name)
3819                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3820            final long token = Binder.clearCallingIdentity();
3821            try {
3822                if (sUserManager.isInitialized(userId)) {
3823                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3824                            MountServiceInternal.class);
3825                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3826                }
3827            } finally {
3828                Binder.restoreCallingIdentity(token);
3829            }
3830        }
3831    }
3832
3833    @Override
3834    public void revokeRuntimePermission(String packageName, String name, int userId) {
3835        if (!sUserManager.exists(userId)) {
3836            Log.e(TAG, "No such user:" + userId);
3837            return;
3838        }
3839
3840        mContext.enforceCallingOrSelfPermission(
3841                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3842                "revokeRuntimePermission");
3843
3844        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3845                "revokeRuntimePermission");
3846
3847        final int appId;
3848
3849        synchronized (mPackages) {
3850            final PackageParser.Package pkg = mPackages.get(packageName);
3851            if (pkg == null) {
3852                throw new IllegalArgumentException("Unknown package: " + packageName);
3853            }
3854
3855            final BasePermission bp = mSettings.mPermissions.get(name);
3856            if (bp == null) {
3857                throw new IllegalArgumentException("Unknown permission: " + name);
3858            }
3859
3860            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3861
3862            // If a permission review is required for legacy apps we represent
3863            // their permissions as always granted runtime ones since we need
3864            // to keep the review required permission flag per user while an
3865            // install permission's state is shared across all users.
3866            if (Build.PERMISSIONS_REVIEW_REQUIRED
3867                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3868                    && bp.isRuntime()) {
3869                return;
3870            }
3871
3872            SettingBase sb = (SettingBase) pkg.mExtras;
3873            if (sb == null) {
3874                throw new IllegalArgumentException("Unknown package: " + packageName);
3875            }
3876
3877            final PermissionsState permissionsState = sb.getPermissionsState();
3878
3879            final int flags = permissionsState.getPermissionFlags(name, userId);
3880            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3881                throw new SecurityException("Cannot revoke system fixed permission "
3882                        + name + " for package " + packageName);
3883            }
3884
3885            if (bp.isDevelopment()) {
3886                // Development permissions must be handled specially, since they are not
3887                // normal runtime permissions.  For now they apply to all users.
3888                if (permissionsState.revokeInstallPermission(bp) !=
3889                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3890                    scheduleWriteSettingsLocked();
3891                }
3892                return;
3893            }
3894
3895            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3896                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3897                return;
3898            }
3899
3900            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3901
3902            // Critical, after this call app should never have the permission.
3903            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3904
3905            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3906        }
3907
3908        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3909    }
3910
3911    @Override
3912    public void resetRuntimePermissions() {
3913        mContext.enforceCallingOrSelfPermission(
3914                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3915                "revokeRuntimePermission");
3916
3917        int callingUid = Binder.getCallingUid();
3918        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3919            mContext.enforceCallingOrSelfPermission(
3920                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3921                    "resetRuntimePermissions");
3922        }
3923
3924        synchronized (mPackages) {
3925            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3926            for (int userId : UserManagerService.getInstance().getUserIds()) {
3927                final int packageCount = mPackages.size();
3928                for (int i = 0; i < packageCount; i++) {
3929                    PackageParser.Package pkg = mPackages.valueAt(i);
3930                    if (!(pkg.mExtras instanceof PackageSetting)) {
3931                        continue;
3932                    }
3933                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3934                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3935                }
3936            }
3937        }
3938    }
3939
3940    @Override
3941    public int getPermissionFlags(String name, String packageName, int userId) {
3942        if (!sUserManager.exists(userId)) {
3943            return 0;
3944        }
3945
3946        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3947
3948        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3949                "getPermissionFlags");
3950
3951        synchronized (mPackages) {
3952            final PackageParser.Package pkg = mPackages.get(packageName);
3953            if (pkg == null) {
3954                throw new IllegalArgumentException("Unknown package: " + packageName);
3955            }
3956
3957            final BasePermission bp = mSettings.mPermissions.get(name);
3958            if (bp == null) {
3959                throw new IllegalArgumentException("Unknown permission: " + name);
3960            }
3961
3962            SettingBase sb = (SettingBase) pkg.mExtras;
3963            if (sb == null) {
3964                throw new IllegalArgumentException("Unknown package: " + packageName);
3965            }
3966
3967            PermissionsState permissionsState = sb.getPermissionsState();
3968            return permissionsState.getPermissionFlags(name, userId);
3969        }
3970    }
3971
3972    @Override
3973    public void updatePermissionFlags(String name, String packageName, int flagMask,
3974            int flagValues, int userId) {
3975        if (!sUserManager.exists(userId)) {
3976            return;
3977        }
3978
3979        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3980
3981        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3982                "updatePermissionFlags");
3983
3984        // Only the system can change these flags and nothing else.
3985        if (getCallingUid() != Process.SYSTEM_UID) {
3986            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3987            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3988            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3989            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3990            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3991        }
3992
3993        synchronized (mPackages) {
3994            final PackageParser.Package pkg = mPackages.get(packageName);
3995            if (pkg == null) {
3996                throw new IllegalArgumentException("Unknown package: " + packageName);
3997            }
3998
3999            final BasePermission bp = mSettings.mPermissions.get(name);
4000            if (bp == null) {
4001                throw new IllegalArgumentException("Unknown permission: " + name);
4002            }
4003
4004            SettingBase sb = (SettingBase) pkg.mExtras;
4005            if (sb == null) {
4006                throw new IllegalArgumentException("Unknown package: " + packageName);
4007            }
4008
4009            PermissionsState permissionsState = sb.getPermissionsState();
4010
4011            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4012
4013            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4014                // Install and runtime permissions are stored in different places,
4015                // so figure out what permission changed and persist the change.
4016                if (permissionsState.getInstallPermissionState(name) != null) {
4017                    scheduleWriteSettingsLocked();
4018                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4019                        || hadState) {
4020                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4021                }
4022            }
4023        }
4024    }
4025
4026    /**
4027     * Update the permission flags for all packages and runtime permissions of a user in order
4028     * to allow device or profile owner to remove POLICY_FIXED.
4029     */
4030    @Override
4031    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4032        if (!sUserManager.exists(userId)) {
4033            return;
4034        }
4035
4036        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4037
4038        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4039                "updatePermissionFlagsForAllApps");
4040
4041        // Only the system can change system fixed flags.
4042        if (getCallingUid() != Process.SYSTEM_UID) {
4043            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4044            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4045        }
4046
4047        synchronized (mPackages) {
4048            boolean changed = false;
4049            final int packageCount = mPackages.size();
4050            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4051                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4052                SettingBase sb = (SettingBase) pkg.mExtras;
4053                if (sb == null) {
4054                    continue;
4055                }
4056                PermissionsState permissionsState = sb.getPermissionsState();
4057                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4058                        userId, flagMask, flagValues);
4059            }
4060            if (changed) {
4061                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4062            }
4063        }
4064    }
4065
4066    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4067        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4068                != PackageManager.PERMISSION_GRANTED
4069            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4070                != PackageManager.PERMISSION_GRANTED) {
4071            throw new SecurityException(message + " requires "
4072                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4073                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4074        }
4075    }
4076
4077    @Override
4078    public boolean shouldShowRequestPermissionRationale(String permissionName,
4079            String packageName, int userId) {
4080        if (UserHandle.getCallingUserId() != userId) {
4081            mContext.enforceCallingPermission(
4082                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4083                    "canShowRequestPermissionRationale for user " + userId);
4084        }
4085
4086        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4087        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4088            return false;
4089        }
4090
4091        if (checkPermission(permissionName, packageName, userId)
4092                == PackageManager.PERMISSION_GRANTED) {
4093            return false;
4094        }
4095
4096        final int flags;
4097
4098        final long identity = Binder.clearCallingIdentity();
4099        try {
4100            flags = getPermissionFlags(permissionName,
4101                    packageName, userId);
4102        } finally {
4103            Binder.restoreCallingIdentity(identity);
4104        }
4105
4106        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4107                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4108                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4109
4110        if ((flags & fixedFlags) != 0) {
4111            return false;
4112        }
4113
4114        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4115    }
4116
4117    @Override
4118    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4119        mContext.enforceCallingOrSelfPermission(
4120                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4121                "addOnPermissionsChangeListener");
4122
4123        synchronized (mPackages) {
4124            mOnPermissionChangeListeners.addListenerLocked(listener);
4125        }
4126    }
4127
4128    @Override
4129    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4130        synchronized (mPackages) {
4131            mOnPermissionChangeListeners.removeListenerLocked(listener);
4132        }
4133    }
4134
4135    @Override
4136    public boolean isProtectedBroadcast(String actionName) {
4137        synchronized (mPackages) {
4138            if (mProtectedBroadcasts.contains(actionName)) {
4139                return true;
4140            } else if (actionName != null) {
4141                // TODO: remove these terrible hacks
4142                if (actionName.startsWith("android.net.netmon.lingerExpired")
4143                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4144                    return true;
4145                }
4146            }
4147        }
4148        return false;
4149    }
4150
4151    @Override
4152    public int checkSignatures(String pkg1, String pkg2) {
4153        synchronized (mPackages) {
4154            final PackageParser.Package p1 = mPackages.get(pkg1);
4155            final PackageParser.Package p2 = mPackages.get(pkg2);
4156            if (p1 == null || p1.mExtras == null
4157                    || p2 == null || p2.mExtras == null) {
4158                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4159            }
4160            return compareSignatures(p1.mSignatures, p2.mSignatures);
4161        }
4162    }
4163
4164    @Override
4165    public int checkUidSignatures(int uid1, int uid2) {
4166        // Map to base uids.
4167        uid1 = UserHandle.getAppId(uid1);
4168        uid2 = UserHandle.getAppId(uid2);
4169        // reader
4170        synchronized (mPackages) {
4171            Signature[] s1;
4172            Signature[] s2;
4173            Object obj = mSettings.getUserIdLPr(uid1);
4174            if (obj != null) {
4175                if (obj instanceof SharedUserSetting) {
4176                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4177                } else if (obj instanceof PackageSetting) {
4178                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4179                } else {
4180                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4181                }
4182            } else {
4183                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4184            }
4185            obj = mSettings.getUserIdLPr(uid2);
4186            if (obj != null) {
4187                if (obj instanceof SharedUserSetting) {
4188                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4189                } else if (obj instanceof PackageSetting) {
4190                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4191                } else {
4192                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4193                }
4194            } else {
4195                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4196            }
4197            return compareSignatures(s1, s2);
4198        }
4199    }
4200
4201    private void killUid(int appId, int userId, String reason) {
4202        final long identity = Binder.clearCallingIdentity();
4203        try {
4204            IActivityManager am = ActivityManagerNative.getDefault();
4205            if (am != null) {
4206                try {
4207                    am.killUid(appId, userId, reason);
4208                } catch (RemoteException e) {
4209                    /* ignore - same process */
4210                }
4211            }
4212        } finally {
4213            Binder.restoreCallingIdentity(identity);
4214        }
4215    }
4216
4217    /**
4218     * Compares two sets of signatures. Returns:
4219     * <br />
4220     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4221     * <br />
4222     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4223     * <br />
4224     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4225     * <br />
4226     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4227     * <br />
4228     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4229     */
4230    static int compareSignatures(Signature[] s1, Signature[] s2) {
4231        if (s1 == null) {
4232            return s2 == null
4233                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4234                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4235        }
4236
4237        if (s2 == null) {
4238            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4239        }
4240
4241        if (s1.length != s2.length) {
4242            return PackageManager.SIGNATURE_NO_MATCH;
4243        }
4244
4245        // Since both signature sets are of size 1, we can compare without HashSets.
4246        if (s1.length == 1) {
4247            return s1[0].equals(s2[0]) ?
4248                    PackageManager.SIGNATURE_MATCH :
4249                    PackageManager.SIGNATURE_NO_MATCH;
4250        }
4251
4252        ArraySet<Signature> set1 = new ArraySet<Signature>();
4253        for (Signature sig : s1) {
4254            set1.add(sig);
4255        }
4256        ArraySet<Signature> set2 = new ArraySet<Signature>();
4257        for (Signature sig : s2) {
4258            set2.add(sig);
4259        }
4260        // Make sure s2 contains all signatures in s1.
4261        if (set1.equals(set2)) {
4262            return PackageManager.SIGNATURE_MATCH;
4263        }
4264        return PackageManager.SIGNATURE_NO_MATCH;
4265    }
4266
4267    /**
4268     * If the database version for this type of package (internal storage or
4269     * external storage) is less than the version where package signatures
4270     * were updated, return true.
4271     */
4272    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4273        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4274        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4275    }
4276
4277    /**
4278     * Used for backward compatibility to make sure any packages with
4279     * certificate chains get upgraded to the new style. {@code existingSigs}
4280     * will be in the old format (since they were stored on disk from before the
4281     * system upgrade) and {@code scannedSigs} will be in the newer format.
4282     */
4283    private int compareSignaturesCompat(PackageSignatures existingSigs,
4284            PackageParser.Package scannedPkg) {
4285        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4286            return PackageManager.SIGNATURE_NO_MATCH;
4287        }
4288
4289        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4290        for (Signature sig : existingSigs.mSignatures) {
4291            existingSet.add(sig);
4292        }
4293        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4294        for (Signature sig : scannedPkg.mSignatures) {
4295            try {
4296                Signature[] chainSignatures = sig.getChainSignatures();
4297                for (Signature chainSig : chainSignatures) {
4298                    scannedCompatSet.add(chainSig);
4299                }
4300            } catch (CertificateEncodingException e) {
4301                scannedCompatSet.add(sig);
4302            }
4303        }
4304        /*
4305         * Make sure the expanded scanned set contains all signatures in the
4306         * existing one.
4307         */
4308        if (scannedCompatSet.equals(existingSet)) {
4309            // Migrate the old signatures to the new scheme.
4310            existingSigs.assignSignatures(scannedPkg.mSignatures);
4311            // The new KeySets will be re-added later in the scanning process.
4312            synchronized (mPackages) {
4313                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4314            }
4315            return PackageManager.SIGNATURE_MATCH;
4316        }
4317        return PackageManager.SIGNATURE_NO_MATCH;
4318    }
4319
4320    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4321        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4322        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4323    }
4324
4325    private int compareSignaturesRecover(PackageSignatures existingSigs,
4326            PackageParser.Package scannedPkg) {
4327        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4328            return PackageManager.SIGNATURE_NO_MATCH;
4329        }
4330
4331        String msg = null;
4332        try {
4333            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4334                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4335                        + scannedPkg.packageName);
4336                return PackageManager.SIGNATURE_MATCH;
4337            }
4338        } catch (CertificateException e) {
4339            msg = e.getMessage();
4340        }
4341
4342        logCriticalInfo(Log.INFO,
4343                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4344        return PackageManager.SIGNATURE_NO_MATCH;
4345    }
4346
4347    @Override
4348    public String[] getPackagesForUid(int uid) {
4349        uid = UserHandle.getAppId(uid);
4350        // reader
4351        synchronized (mPackages) {
4352            Object obj = mSettings.getUserIdLPr(uid);
4353            if (obj instanceof SharedUserSetting) {
4354                final SharedUserSetting sus = (SharedUserSetting) obj;
4355                final int N = sus.packages.size();
4356                final String[] res = new String[N];
4357                final Iterator<PackageSetting> it = sus.packages.iterator();
4358                int i = 0;
4359                while (it.hasNext()) {
4360                    res[i++] = it.next().name;
4361                }
4362                return res;
4363            } else if (obj instanceof PackageSetting) {
4364                final PackageSetting ps = (PackageSetting) obj;
4365                return new String[] { ps.name };
4366            }
4367        }
4368        return null;
4369    }
4370
4371    @Override
4372    public String getNameForUid(int uid) {
4373        // reader
4374        synchronized (mPackages) {
4375            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4376            if (obj instanceof SharedUserSetting) {
4377                final SharedUserSetting sus = (SharedUserSetting) obj;
4378                return sus.name + ":" + sus.userId;
4379            } else if (obj instanceof PackageSetting) {
4380                final PackageSetting ps = (PackageSetting) obj;
4381                return ps.name;
4382            }
4383        }
4384        return null;
4385    }
4386
4387    @Override
4388    public int getUidForSharedUser(String sharedUserName) {
4389        if(sharedUserName == null) {
4390            return -1;
4391        }
4392        // reader
4393        synchronized (mPackages) {
4394            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4395            if (suid == null) {
4396                return -1;
4397            }
4398            return suid.userId;
4399        }
4400    }
4401
4402    @Override
4403    public int getFlagsForUid(int uid) {
4404        synchronized (mPackages) {
4405            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4406            if (obj instanceof SharedUserSetting) {
4407                final SharedUserSetting sus = (SharedUserSetting) obj;
4408                return sus.pkgFlags;
4409            } else if (obj instanceof PackageSetting) {
4410                final PackageSetting ps = (PackageSetting) obj;
4411                return ps.pkgFlags;
4412            }
4413        }
4414        return 0;
4415    }
4416
4417    @Override
4418    public int getPrivateFlagsForUid(int uid) {
4419        synchronized (mPackages) {
4420            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4421            if (obj instanceof SharedUserSetting) {
4422                final SharedUserSetting sus = (SharedUserSetting) obj;
4423                return sus.pkgPrivateFlags;
4424            } else if (obj instanceof PackageSetting) {
4425                final PackageSetting ps = (PackageSetting) obj;
4426                return ps.pkgPrivateFlags;
4427            }
4428        }
4429        return 0;
4430    }
4431
4432    @Override
4433    public boolean isUidPrivileged(int uid) {
4434        uid = UserHandle.getAppId(uid);
4435        // reader
4436        synchronized (mPackages) {
4437            Object obj = mSettings.getUserIdLPr(uid);
4438            if (obj instanceof SharedUserSetting) {
4439                final SharedUserSetting sus = (SharedUserSetting) obj;
4440                final Iterator<PackageSetting> it = sus.packages.iterator();
4441                while (it.hasNext()) {
4442                    if (it.next().isPrivileged()) {
4443                        return true;
4444                    }
4445                }
4446            } else if (obj instanceof PackageSetting) {
4447                final PackageSetting ps = (PackageSetting) obj;
4448                return ps.isPrivileged();
4449            }
4450        }
4451        return false;
4452    }
4453
4454    @Override
4455    public String[] getAppOpPermissionPackages(String permissionName) {
4456        synchronized (mPackages) {
4457            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4458            if (pkgs == null) {
4459                return null;
4460            }
4461            return pkgs.toArray(new String[pkgs.size()]);
4462        }
4463    }
4464
4465    @Override
4466    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4467            int flags, int userId) {
4468        if (!sUserManager.exists(userId)) return null;
4469        flags = updateFlagsForResolve(flags, userId, intent);
4470        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4471        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4472        final ResolveInfo bestChoice =
4473                chooseBestActivity(intent, resolvedType, flags, query, userId);
4474
4475        if (isEphemeralAllowed(intent, query, userId)) {
4476            final EphemeralResolveInfo ai =
4477                    getEphemeralResolveInfo(intent, resolvedType, userId);
4478            if (ai != null) {
4479                if (DEBUG_EPHEMERAL) {
4480                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4481                }
4482                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4483                bestChoice.ephemeralResolveInfo = ai;
4484            }
4485        }
4486        return bestChoice;
4487    }
4488
4489    @Override
4490    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4491            IntentFilter filter, int match, ComponentName activity) {
4492        final int userId = UserHandle.getCallingUserId();
4493        if (DEBUG_PREFERRED) {
4494            Log.v(TAG, "setLastChosenActivity intent=" + intent
4495                + " resolvedType=" + resolvedType
4496                + " flags=" + flags
4497                + " filter=" + filter
4498                + " match=" + match
4499                + " activity=" + activity);
4500            filter.dump(new PrintStreamPrinter(System.out), "    ");
4501        }
4502        intent.setComponent(null);
4503        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4504        // Find any earlier preferred or last chosen entries and nuke them
4505        findPreferredActivity(intent, resolvedType,
4506                flags, query, 0, false, true, false, userId);
4507        // Add the new activity as the last chosen for this filter
4508        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4509                "Setting last chosen");
4510    }
4511
4512    @Override
4513    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4514        final int userId = UserHandle.getCallingUserId();
4515        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4516        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4517        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4518                false, false, false, userId);
4519    }
4520
4521
4522    private boolean isEphemeralAllowed(
4523            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4524        // Short circuit and return early if possible.
4525        if (DISABLE_EPHEMERAL_APPS) {
4526            return false;
4527        }
4528        final int callingUser = UserHandle.getCallingUserId();
4529        if (callingUser != UserHandle.USER_SYSTEM) {
4530            return false;
4531        }
4532        if (mEphemeralResolverConnection == null) {
4533            return false;
4534        }
4535        if (intent.getComponent() != null) {
4536            return false;
4537        }
4538        if (intent.getPackage() != null) {
4539            return false;
4540        }
4541        final boolean isWebUri = hasWebURI(intent);
4542        if (!isWebUri) {
4543            return false;
4544        }
4545        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4546        synchronized (mPackages) {
4547            final int count = resolvedActivites.size();
4548            for (int n = 0; n < count; n++) {
4549                ResolveInfo info = resolvedActivites.get(n);
4550                String packageName = info.activityInfo.packageName;
4551                PackageSetting ps = mSettings.mPackages.get(packageName);
4552                if (ps != null) {
4553                    // Try to get the status from User settings first
4554                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4555                    int status = (int) (packedStatus >> 32);
4556                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4557                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4558                        if (DEBUG_EPHEMERAL) {
4559                            Slog.v(TAG, "DENY ephemeral apps;"
4560                                + " pkg: " + packageName + ", status: " + status);
4561                        }
4562                        return false;
4563                    }
4564                }
4565            }
4566        }
4567        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4568        return true;
4569    }
4570
4571    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4572            int userId) {
4573        MessageDigest digest = null;
4574        try {
4575            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4576        } catch (NoSuchAlgorithmException e) {
4577            // If we can't create a digest, ignore ephemeral apps.
4578            return null;
4579        }
4580
4581        final byte[] hostBytes = intent.getData().getHost().getBytes();
4582        final byte[] digestBytes = digest.digest(hostBytes);
4583        int shaPrefix =
4584                digestBytes[0] << 24
4585                | digestBytes[1] << 16
4586                | digestBytes[2] << 8
4587                | digestBytes[3] << 0;
4588        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4589                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4590        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4591            // No hash prefix match; there are no ephemeral apps for this domain.
4592            return null;
4593        }
4594        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4595            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4596            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4597                continue;
4598            }
4599            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4600            // No filters; this should never happen.
4601            if (filters.isEmpty()) {
4602                continue;
4603            }
4604            // We have a domain match; resolve the filters to see if anything matches.
4605            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4606            for (int j = filters.size() - 1; j >= 0; --j) {
4607                final EphemeralResolveIntentInfo intentInfo =
4608                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4609                ephemeralResolver.addFilter(intentInfo);
4610            }
4611            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4612                    intent, resolvedType, false /*defaultOnly*/, userId);
4613            if (!matchedResolveInfoList.isEmpty()) {
4614                return matchedResolveInfoList.get(0);
4615            }
4616        }
4617        // Hash or filter mis-match; no ephemeral apps for this domain.
4618        return null;
4619    }
4620
4621    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4622            int flags, List<ResolveInfo> query, int userId) {
4623        if (query != null) {
4624            final int N = query.size();
4625            if (N == 1) {
4626                return query.get(0);
4627            } else if (N > 1) {
4628                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4629                // If there is more than one activity with the same priority,
4630                // then let the user decide between them.
4631                ResolveInfo r0 = query.get(0);
4632                ResolveInfo r1 = query.get(1);
4633                if (DEBUG_INTENT_MATCHING || debug) {
4634                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4635                            + r1.activityInfo.name + "=" + r1.priority);
4636                }
4637                // If the first activity has a higher priority, or a different
4638                // default, then it is always desirable to pick it.
4639                if (r0.priority != r1.priority
4640                        || r0.preferredOrder != r1.preferredOrder
4641                        || r0.isDefault != r1.isDefault) {
4642                    return query.get(0);
4643                }
4644                // If we have saved a preference for a preferred activity for
4645                // this Intent, use that.
4646                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4647                        flags, query, r0.priority, true, false, debug, userId);
4648                if (ri != null) {
4649                    return ri;
4650                }
4651                ri = new ResolveInfo(mResolveInfo);
4652                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4653                ri.activityInfo.applicationInfo = new ApplicationInfo(
4654                        ri.activityInfo.applicationInfo);
4655                if (userId != 0) {
4656                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4657                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4658                }
4659                // Make sure that the resolver is displayable in car mode
4660                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4661                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4662                return ri;
4663            }
4664        }
4665        return null;
4666    }
4667
4668    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4669            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4670        final int N = query.size();
4671        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4672                .get(userId);
4673        // Get the list of persistent preferred activities that handle the intent
4674        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4675        List<PersistentPreferredActivity> pprefs = ppir != null
4676                ? ppir.queryIntent(intent, resolvedType,
4677                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4678                : null;
4679        if (pprefs != null && pprefs.size() > 0) {
4680            final int M = pprefs.size();
4681            for (int i=0; i<M; i++) {
4682                final PersistentPreferredActivity ppa = pprefs.get(i);
4683                if (DEBUG_PREFERRED || debug) {
4684                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4685                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4686                            + "\n  component=" + ppa.mComponent);
4687                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4688                }
4689                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4690                        flags | MATCH_DISABLED_COMPONENTS, userId);
4691                if (DEBUG_PREFERRED || debug) {
4692                    Slog.v(TAG, "Found persistent preferred activity:");
4693                    if (ai != null) {
4694                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4695                    } else {
4696                        Slog.v(TAG, "  null");
4697                    }
4698                }
4699                if (ai == null) {
4700                    // This previously registered persistent preferred activity
4701                    // component is no longer known. Ignore it and do NOT remove it.
4702                    continue;
4703                }
4704                for (int j=0; j<N; j++) {
4705                    final ResolveInfo ri = query.get(j);
4706                    if (!ri.activityInfo.applicationInfo.packageName
4707                            .equals(ai.applicationInfo.packageName)) {
4708                        continue;
4709                    }
4710                    if (!ri.activityInfo.name.equals(ai.name)) {
4711                        continue;
4712                    }
4713                    //  Found a persistent preference that can handle the intent.
4714                    if (DEBUG_PREFERRED || debug) {
4715                        Slog.v(TAG, "Returning persistent preferred activity: " +
4716                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4717                    }
4718                    return ri;
4719                }
4720            }
4721        }
4722        return null;
4723    }
4724
4725    // TODO: handle preferred activities missing while user has amnesia
4726    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4727            List<ResolveInfo> query, int priority, boolean always,
4728            boolean removeMatches, boolean debug, int userId) {
4729        if (!sUserManager.exists(userId)) return null;
4730        flags = updateFlagsForResolve(flags, userId, intent);
4731        // writer
4732        synchronized (mPackages) {
4733            if (intent.getSelector() != null) {
4734                intent = intent.getSelector();
4735            }
4736            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4737
4738            // Try to find a matching persistent preferred activity.
4739            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4740                    debug, userId);
4741
4742            // If a persistent preferred activity matched, use it.
4743            if (pri != null) {
4744                return pri;
4745            }
4746
4747            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4748            // Get the list of preferred activities that handle the intent
4749            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4750            List<PreferredActivity> prefs = pir != null
4751                    ? pir.queryIntent(intent, resolvedType,
4752                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4753                    : null;
4754            if (prefs != null && prefs.size() > 0) {
4755                boolean changed = false;
4756                try {
4757                    // First figure out how good the original match set is.
4758                    // We will only allow preferred activities that came
4759                    // from the same match quality.
4760                    int match = 0;
4761
4762                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4763
4764                    final int N = query.size();
4765                    for (int j=0; j<N; j++) {
4766                        final ResolveInfo ri = query.get(j);
4767                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4768                                + ": 0x" + Integer.toHexString(match));
4769                        if (ri.match > match) {
4770                            match = ri.match;
4771                        }
4772                    }
4773
4774                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4775                            + Integer.toHexString(match));
4776
4777                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4778                    final int M = prefs.size();
4779                    for (int i=0; i<M; i++) {
4780                        final PreferredActivity pa = prefs.get(i);
4781                        if (DEBUG_PREFERRED || debug) {
4782                            Slog.v(TAG, "Checking PreferredActivity ds="
4783                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4784                                    + "\n  component=" + pa.mPref.mComponent);
4785                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4786                        }
4787                        if (pa.mPref.mMatch != match) {
4788                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4789                                    + Integer.toHexString(pa.mPref.mMatch));
4790                            continue;
4791                        }
4792                        // If it's not an "always" type preferred activity and that's what we're
4793                        // looking for, skip it.
4794                        if (always && !pa.mPref.mAlways) {
4795                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4796                            continue;
4797                        }
4798                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4799                                flags | MATCH_DISABLED_COMPONENTS, userId);
4800                        if (DEBUG_PREFERRED || debug) {
4801                            Slog.v(TAG, "Found preferred activity:");
4802                            if (ai != null) {
4803                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4804                            } else {
4805                                Slog.v(TAG, "  null");
4806                            }
4807                        }
4808                        if (ai == null) {
4809                            // This previously registered preferred activity
4810                            // component is no longer known.  Most likely an update
4811                            // to the app was installed and in the new version this
4812                            // component no longer exists.  Clean it up by removing
4813                            // it from the preferred activities list, and skip it.
4814                            Slog.w(TAG, "Removing dangling preferred activity: "
4815                                    + pa.mPref.mComponent);
4816                            pir.removeFilter(pa);
4817                            changed = true;
4818                            continue;
4819                        }
4820                        for (int j=0; j<N; j++) {
4821                            final ResolveInfo ri = query.get(j);
4822                            if (!ri.activityInfo.applicationInfo.packageName
4823                                    .equals(ai.applicationInfo.packageName)) {
4824                                continue;
4825                            }
4826                            if (!ri.activityInfo.name.equals(ai.name)) {
4827                                continue;
4828                            }
4829
4830                            if (removeMatches) {
4831                                pir.removeFilter(pa);
4832                                changed = true;
4833                                if (DEBUG_PREFERRED) {
4834                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4835                                }
4836                                break;
4837                            }
4838
4839                            // Okay we found a previously set preferred or last chosen app.
4840                            // If the result set is different from when this
4841                            // was created, we need to clear it and re-ask the
4842                            // user their preference, if we're looking for an "always" type entry.
4843                            if (always && !pa.mPref.sameSet(query)) {
4844                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4845                                        + intent + " type " + resolvedType);
4846                                if (DEBUG_PREFERRED) {
4847                                    Slog.v(TAG, "Removing preferred activity since set changed "
4848                                            + pa.mPref.mComponent);
4849                                }
4850                                pir.removeFilter(pa);
4851                                // Re-add the filter as a "last chosen" entry (!always)
4852                                PreferredActivity lastChosen = new PreferredActivity(
4853                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4854                                pir.addFilter(lastChosen);
4855                                changed = true;
4856                                return null;
4857                            }
4858
4859                            // Yay! Either the set matched or we're looking for the last chosen
4860                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4861                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4862                            return ri;
4863                        }
4864                    }
4865                } finally {
4866                    if (changed) {
4867                        if (DEBUG_PREFERRED) {
4868                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4869                        }
4870                        scheduleWritePackageRestrictionsLocked(userId);
4871                    }
4872                }
4873            }
4874        }
4875        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4876        return null;
4877    }
4878
4879    /*
4880     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4881     */
4882    @Override
4883    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4884            int targetUserId) {
4885        mContext.enforceCallingOrSelfPermission(
4886                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4887        List<CrossProfileIntentFilter> matches =
4888                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4889        if (matches != null) {
4890            int size = matches.size();
4891            for (int i = 0; i < size; i++) {
4892                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4893            }
4894        }
4895        if (hasWebURI(intent)) {
4896            // cross-profile app linking works only towards the parent.
4897            final UserInfo parent = getProfileParent(sourceUserId);
4898            synchronized(mPackages) {
4899                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4900                        intent, resolvedType, 0, sourceUserId, parent.id);
4901                return xpDomainInfo != null;
4902            }
4903        }
4904        return false;
4905    }
4906
4907    private UserInfo getProfileParent(int userId) {
4908        final long identity = Binder.clearCallingIdentity();
4909        try {
4910            return sUserManager.getProfileParent(userId);
4911        } finally {
4912            Binder.restoreCallingIdentity(identity);
4913        }
4914    }
4915
4916    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4917            String resolvedType, int userId) {
4918        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4919        if (resolver != null) {
4920            return resolver.queryIntent(intent, resolvedType, false, userId);
4921        }
4922        return null;
4923    }
4924
4925    @Override
4926    public List<ResolveInfo> queryIntentActivities(Intent intent,
4927            String resolvedType, int flags, int userId) {
4928        if (!sUserManager.exists(userId)) return Collections.emptyList();
4929        flags = updateFlagsForResolve(flags, userId, intent);
4930        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4931        ComponentName comp = intent.getComponent();
4932        if (comp == null) {
4933            if (intent.getSelector() != null) {
4934                intent = intent.getSelector();
4935                comp = intent.getComponent();
4936            }
4937        }
4938
4939        if (comp != null) {
4940            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4941            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4942            if (ai != null) {
4943                final ResolveInfo ri = new ResolveInfo();
4944                ri.activityInfo = ai;
4945                list.add(ri);
4946            }
4947            return list;
4948        }
4949
4950        // reader
4951        synchronized (mPackages) {
4952            final String pkgName = intent.getPackage();
4953            if (pkgName == null) {
4954                List<CrossProfileIntentFilter> matchingFilters =
4955                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4956                // Check for results that need to skip the current profile.
4957                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4958                        resolvedType, flags, userId);
4959                if (xpResolveInfo != null) {
4960                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4961                    result.add(xpResolveInfo);
4962                    return filterIfNotSystemUser(result, userId);
4963                }
4964
4965                // Check for results in the current profile.
4966                List<ResolveInfo> result = mActivities.queryIntent(
4967                        intent, resolvedType, flags, userId);
4968                result = filterIfNotSystemUser(result, userId);
4969
4970                // Check for cross profile results.
4971                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4972                xpResolveInfo = queryCrossProfileIntents(
4973                        matchingFilters, intent, resolvedType, flags, userId,
4974                        hasNonNegativePriorityResult);
4975                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4976                    boolean isVisibleToUser = filterIfNotSystemUser(
4977                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4978                    if (isVisibleToUser) {
4979                        result.add(xpResolveInfo);
4980                        Collections.sort(result, mResolvePrioritySorter);
4981                    }
4982                }
4983                if (hasWebURI(intent)) {
4984                    CrossProfileDomainInfo xpDomainInfo = null;
4985                    final UserInfo parent = getProfileParent(userId);
4986                    if (parent != null) {
4987                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4988                                flags, userId, parent.id);
4989                    }
4990                    if (xpDomainInfo != null) {
4991                        if (xpResolveInfo != null) {
4992                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4993                            // in the result.
4994                            result.remove(xpResolveInfo);
4995                        }
4996                        if (result.size() == 0) {
4997                            result.add(xpDomainInfo.resolveInfo);
4998                            return result;
4999                        }
5000                    } else if (result.size() <= 1) {
5001                        return result;
5002                    }
5003                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5004                            xpDomainInfo, userId);
5005                    Collections.sort(result, mResolvePrioritySorter);
5006                }
5007                return result;
5008            }
5009            final PackageParser.Package pkg = mPackages.get(pkgName);
5010            if (pkg != null) {
5011                return filterIfNotSystemUser(
5012                        mActivities.queryIntentForPackage(
5013                                intent, resolvedType, flags, pkg.activities, userId),
5014                        userId);
5015            }
5016            return new ArrayList<ResolveInfo>();
5017        }
5018    }
5019
5020    private static class CrossProfileDomainInfo {
5021        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5022        ResolveInfo resolveInfo;
5023        /* Best domain verification status of the activities found in the other profile */
5024        int bestDomainVerificationStatus;
5025    }
5026
5027    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5028            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5029        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5030                sourceUserId)) {
5031            return null;
5032        }
5033        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5034                resolvedType, flags, parentUserId);
5035
5036        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5037            return null;
5038        }
5039        CrossProfileDomainInfo result = null;
5040        int size = resultTargetUser.size();
5041        for (int i = 0; i < size; i++) {
5042            ResolveInfo riTargetUser = resultTargetUser.get(i);
5043            // Intent filter verification is only for filters that specify a host. So don't return
5044            // those that handle all web uris.
5045            if (riTargetUser.handleAllWebDataURI) {
5046                continue;
5047            }
5048            String packageName = riTargetUser.activityInfo.packageName;
5049            PackageSetting ps = mSettings.mPackages.get(packageName);
5050            if (ps == null) {
5051                continue;
5052            }
5053            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5054            int status = (int)(verificationState >> 32);
5055            if (result == null) {
5056                result = new CrossProfileDomainInfo();
5057                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5058                        sourceUserId, parentUserId);
5059                result.bestDomainVerificationStatus = status;
5060            } else {
5061                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5062                        result.bestDomainVerificationStatus);
5063            }
5064        }
5065        // Don't consider matches with status NEVER across profiles.
5066        if (result != null && result.bestDomainVerificationStatus
5067                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5068            return null;
5069        }
5070        return result;
5071    }
5072
5073    /**
5074     * Verification statuses are ordered from the worse to the best, except for
5075     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5076     */
5077    private int bestDomainVerificationStatus(int status1, int status2) {
5078        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5079            return status2;
5080        }
5081        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5082            return status1;
5083        }
5084        return (int) MathUtils.max(status1, status2);
5085    }
5086
5087    private boolean isUserEnabled(int userId) {
5088        long callingId = Binder.clearCallingIdentity();
5089        try {
5090            UserInfo userInfo = sUserManager.getUserInfo(userId);
5091            return userInfo != null && userInfo.isEnabled();
5092        } finally {
5093            Binder.restoreCallingIdentity(callingId);
5094        }
5095    }
5096
5097    /**
5098     * Filter out activities with systemUserOnly flag set, when current user is not System.
5099     *
5100     * @return filtered list
5101     */
5102    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5103        if (userId == UserHandle.USER_SYSTEM) {
5104            return resolveInfos;
5105        }
5106        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5107            ResolveInfo info = resolveInfos.get(i);
5108            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5109                resolveInfos.remove(i);
5110            }
5111        }
5112        return resolveInfos;
5113    }
5114
5115    /**
5116     * @param resolveInfos list of resolve infos in descending priority order
5117     * @return if the list contains a resolve info with non-negative priority
5118     */
5119    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5120        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5121    }
5122
5123    private static boolean hasWebURI(Intent intent) {
5124        if (intent.getData() == null) {
5125            return false;
5126        }
5127        final String scheme = intent.getScheme();
5128        if (TextUtils.isEmpty(scheme)) {
5129            return false;
5130        }
5131        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5132    }
5133
5134    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5135            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5136            int userId) {
5137        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5138
5139        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5140            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5141                    candidates.size());
5142        }
5143
5144        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5145        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5146        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5147        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5148        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5149        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5150
5151        synchronized (mPackages) {
5152            final int count = candidates.size();
5153            // First, try to use linked apps. Partition the candidates into four lists:
5154            // one for the final results, one for the "do not use ever", one for "undefined status"
5155            // and finally one for "browser app type".
5156            for (int n=0; n<count; n++) {
5157                ResolveInfo info = candidates.get(n);
5158                String packageName = info.activityInfo.packageName;
5159                PackageSetting ps = mSettings.mPackages.get(packageName);
5160                if (ps != null) {
5161                    // Add to the special match all list (Browser use case)
5162                    if (info.handleAllWebDataURI) {
5163                        matchAllList.add(info);
5164                        continue;
5165                    }
5166                    // Try to get the status from User settings first
5167                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5168                    int status = (int)(packedStatus >> 32);
5169                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5170                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5171                        if (DEBUG_DOMAIN_VERIFICATION) {
5172                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5173                                    + " : linkgen=" + linkGeneration);
5174                        }
5175                        // Use link-enabled generation as preferredOrder, i.e.
5176                        // prefer newly-enabled over earlier-enabled.
5177                        info.preferredOrder = linkGeneration;
5178                        alwaysList.add(info);
5179                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5180                        if (DEBUG_DOMAIN_VERIFICATION) {
5181                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5182                        }
5183                        neverList.add(info);
5184                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5185                        if (DEBUG_DOMAIN_VERIFICATION) {
5186                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5187                        }
5188                        alwaysAskList.add(info);
5189                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5190                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5191                        if (DEBUG_DOMAIN_VERIFICATION) {
5192                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5193                        }
5194                        undefinedList.add(info);
5195                    }
5196                }
5197            }
5198
5199            // We'll want to include browser possibilities in a few cases
5200            boolean includeBrowser = false;
5201
5202            // First try to add the "always" resolution(s) for the current user, if any
5203            if (alwaysList.size() > 0) {
5204                result.addAll(alwaysList);
5205            } else {
5206                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5207                result.addAll(undefinedList);
5208                // Maybe add one for the other profile.
5209                if (xpDomainInfo != null && (
5210                        xpDomainInfo.bestDomainVerificationStatus
5211                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5212                    result.add(xpDomainInfo.resolveInfo);
5213                }
5214                includeBrowser = true;
5215            }
5216
5217            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5218            // If there were 'always' entries their preferred order has been set, so we also
5219            // back that off to make the alternatives equivalent
5220            if (alwaysAskList.size() > 0) {
5221                for (ResolveInfo i : result) {
5222                    i.preferredOrder = 0;
5223                }
5224                result.addAll(alwaysAskList);
5225                includeBrowser = true;
5226            }
5227
5228            if (includeBrowser) {
5229                // Also add browsers (all of them or only the default one)
5230                if (DEBUG_DOMAIN_VERIFICATION) {
5231                    Slog.v(TAG, "   ...including browsers in candidate set");
5232                }
5233                if ((matchFlags & MATCH_ALL) != 0) {
5234                    result.addAll(matchAllList);
5235                } else {
5236                    // Browser/generic handling case.  If there's a default browser, go straight
5237                    // to that (but only if there is no other higher-priority match).
5238                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5239                    int maxMatchPrio = 0;
5240                    ResolveInfo defaultBrowserMatch = null;
5241                    final int numCandidates = matchAllList.size();
5242                    for (int n = 0; n < numCandidates; n++) {
5243                        ResolveInfo info = matchAllList.get(n);
5244                        // track the highest overall match priority...
5245                        if (info.priority > maxMatchPrio) {
5246                            maxMatchPrio = info.priority;
5247                        }
5248                        // ...and the highest-priority default browser match
5249                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5250                            if (defaultBrowserMatch == null
5251                                    || (defaultBrowserMatch.priority < info.priority)) {
5252                                if (debug) {
5253                                    Slog.v(TAG, "Considering default browser match " + info);
5254                                }
5255                                defaultBrowserMatch = info;
5256                            }
5257                        }
5258                    }
5259                    if (defaultBrowserMatch != null
5260                            && defaultBrowserMatch.priority >= maxMatchPrio
5261                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5262                    {
5263                        if (debug) {
5264                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5265                        }
5266                        result.add(defaultBrowserMatch);
5267                    } else {
5268                        result.addAll(matchAllList);
5269                    }
5270                }
5271
5272                // If there is nothing selected, add all candidates and remove the ones that the user
5273                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5274                if (result.size() == 0) {
5275                    result.addAll(candidates);
5276                    result.removeAll(neverList);
5277                }
5278            }
5279        }
5280        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5281            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5282                    result.size());
5283            for (ResolveInfo info : result) {
5284                Slog.v(TAG, "  + " + info.activityInfo);
5285            }
5286        }
5287        return result;
5288    }
5289
5290    // Returns a packed value as a long:
5291    //
5292    // high 'int'-sized word: link status: undefined/ask/never/always.
5293    // low 'int'-sized word: relative priority among 'always' results.
5294    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5295        long result = ps.getDomainVerificationStatusForUser(userId);
5296        // if none available, get the master status
5297        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5298            if (ps.getIntentFilterVerificationInfo() != null) {
5299                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5300            }
5301        }
5302        return result;
5303    }
5304
5305    private ResolveInfo querySkipCurrentProfileIntents(
5306            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5307            int flags, int sourceUserId) {
5308        if (matchingFilters != null) {
5309            int size = matchingFilters.size();
5310            for (int i = 0; i < size; i ++) {
5311                CrossProfileIntentFilter filter = matchingFilters.get(i);
5312                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5313                    // Checking if there are activities in the target user that can handle the
5314                    // intent.
5315                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5316                            resolvedType, flags, sourceUserId);
5317                    if (resolveInfo != null) {
5318                        return resolveInfo;
5319                    }
5320                }
5321            }
5322        }
5323        return null;
5324    }
5325
5326    // Return matching ResolveInfo in target user if any.
5327    private ResolveInfo queryCrossProfileIntents(
5328            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5329            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5330        if (matchingFilters != null) {
5331            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5332            // match the same intent. For performance reasons, it is better not to
5333            // run queryIntent twice for the same userId
5334            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5335            int size = matchingFilters.size();
5336            for (int i = 0; i < size; i++) {
5337                CrossProfileIntentFilter filter = matchingFilters.get(i);
5338                int targetUserId = filter.getTargetUserId();
5339                boolean skipCurrentProfile =
5340                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5341                boolean skipCurrentProfileIfNoMatchFound =
5342                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5343                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5344                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5345                    // Checking if there are activities in the target user that can handle the
5346                    // intent.
5347                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5348                            resolvedType, flags, sourceUserId);
5349                    if (resolveInfo != null) return resolveInfo;
5350                    alreadyTriedUserIds.put(targetUserId, true);
5351                }
5352            }
5353        }
5354        return null;
5355    }
5356
5357    /**
5358     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5359     * will forward the intent to the filter's target user.
5360     * Otherwise, returns null.
5361     */
5362    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5363            String resolvedType, int flags, int sourceUserId) {
5364        int targetUserId = filter.getTargetUserId();
5365        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5366                resolvedType, flags, targetUserId);
5367        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5368            // If all the matches in the target profile are suspended, return null.
5369            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5370                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5371                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5372                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5373                            targetUserId);
5374                }
5375            }
5376        }
5377        return null;
5378    }
5379
5380    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5381            int sourceUserId, int targetUserId) {
5382        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5383        long ident = Binder.clearCallingIdentity();
5384        boolean targetIsProfile;
5385        try {
5386            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5387        } finally {
5388            Binder.restoreCallingIdentity(ident);
5389        }
5390        String className;
5391        if (targetIsProfile) {
5392            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5393        } else {
5394            className = FORWARD_INTENT_TO_PARENT;
5395        }
5396        ComponentName forwardingActivityComponentName = new ComponentName(
5397                mAndroidApplication.packageName, className);
5398        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5399                sourceUserId);
5400        if (!targetIsProfile) {
5401            forwardingActivityInfo.showUserIcon = targetUserId;
5402            forwardingResolveInfo.noResourceId = true;
5403        }
5404        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5405        forwardingResolveInfo.priority = 0;
5406        forwardingResolveInfo.preferredOrder = 0;
5407        forwardingResolveInfo.match = 0;
5408        forwardingResolveInfo.isDefault = true;
5409        forwardingResolveInfo.filter = filter;
5410        forwardingResolveInfo.targetUserId = targetUserId;
5411        return forwardingResolveInfo;
5412    }
5413
5414    @Override
5415    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5416            Intent[] specifics, String[] specificTypes, Intent intent,
5417            String resolvedType, int flags, int userId) {
5418        if (!sUserManager.exists(userId)) return Collections.emptyList();
5419        flags = updateFlagsForResolve(flags, userId, intent);
5420        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5421                false, "query intent activity options");
5422        final String resultsAction = intent.getAction();
5423
5424        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5425                | PackageManager.GET_RESOLVED_FILTER, userId);
5426
5427        if (DEBUG_INTENT_MATCHING) {
5428            Log.v(TAG, "Query " + intent + ": " + results);
5429        }
5430
5431        int specificsPos = 0;
5432        int N;
5433
5434        // todo: note that the algorithm used here is O(N^2).  This
5435        // isn't a problem in our current environment, but if we start running
5436        // into situations where we have more than 5 or 10 matches then this
5437        // should probably be changed to something smarter...
5438
5439        // First we go through and resolve each of the specific items
5440        // that were supplied, taking care of removing any corresponding
5441        // duplicate items in the generic resolve list.
5442        if (specifics != null) {
5443            for (int i=0; i<specifics.length; i++) {
5444                final Intent sintent = specifics[i];
5445                if (sintent == null) {
5446                    continue;
5447                }
5448
5449                if (DEBUG_INTENT_MATCHING) {
5450                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5451                }
5452
5453                String action = sintent.getAction();
5454                if (resultsAction != null && resultsAction.equals(action)) {
5455                    // If this action was explicitly requested, then don't
5456                    // remove things that have it.
5457                    action = null;
5458                }
5459
5460                ResolveInfo ri = null;
5461                ActivityInfo ai = null;
5462
5463                ComponentName comp = sintent.getComponent();
5464                if (comp == null) {
5465                    ri = resolveIntent(
5466                        sintent,
5467                        specificTypes != null ? specificTypes[i] : null,
5468                            flags, userId);
5469                    if (ri == null) {
5470                        continue;
5471                    }
5472                    if (ri == mResolveInfo) {
5473                        // ACK!  Must do something better with this.
5474                    }
5475                    ai = ri.activityInfo;
5476                    comp = new ComponentName(ai.applicationInfo.packageName,
5477                            ai.name);
5478                } else {
5479                    ai = getActivityInfo(comp, flags, userId);
5480                    if (ai == null) {
5481                        continue;
5482                    }
5483                }
5484
5485                // Look for any generic query activities that are duplicates
5486                // of this specific one, and remove them from the results.
5487                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5488                N = results.size();
5489                int j;
5490                for (j=specificsPos; j<N; j++) {
5491                    ResolveInfo sri = results.get(j);
5492                    if ((sri.activityInfo.name.equals(comp.getClassName())
5493                            && sri.activityInfo.applicationInfo.packageName.equals(
5494                                    comp.getPackageName()))
5495                        || (action != null && sri.filter.matchAction(action))) {
5496                        results.remove(j);
5497                        if (DEBUG_INTENT_MATCHING) Log.v(
5498                            TAG, "Removing duplicate item from " + j
5499                            + " due to specific " + specificsPos);
5500                        if (ri == null) {
5501                            ri = sri;
5502                        }
5503                        j--;
5504                        N--;
5505                    }
5506                }
5507
5508                // Add this specific item to its proper place.
5509                if (ri == null) {
5510                    ri = new ResolveInfo();
5511                    ri.activityInfo = ai;
5512                }
5513                results.add(specificsPos, ri);
5514                ri.specificIndex = i;
5515                specificsPos++;
5516            }
5517        }
5518
5519        // Now we go through the remaining generic results and remove any
5520        // duplicate actions that are found here.
5521        N = results.size();
5522        for (int i=specificsPos; i<N-1; i++) {
5523            final ResolveInfo rii = results.get(i);
5524            if (rii.filter == null) {
5525                continue;
5526            }
5527
5528            // Iterate over all of the actions of this result's intent
5529            // filter...  typically this should be just one.
5530            final Iterator<String> it = rii.filter.actionsIterator();
5531            if (it == null) {
5532                continue;
5533            }
5534            while (it.hasNext()) {
5535                final String action = it.next();
5536                if (resultsAction != null && resultsAction.equals(action)) {
5537                    // If this action was explicitly requested, then don't
5538                    // remove things that have it.
5539                    continue;
5540                }
5541                for (int j=i+1; j<N; j++) {
5542                    final ResolveInfo rij = results.get(j);
5543                    if (rij.filter != null && rij.filter.hasAction(action)) {
5544                        results.remove(j);
5545                        if (DEBUG_INTENT_MATCHING) Log.v(
5546                            TAG, "Removing duplicate item from " + j
5547                            + " due to action " + action + " at " + i);
5548                        j--;
5549                        N--;
5550                    }
5551                }
5552            }
5553
5554            // If the caller didn't request filter information, drop it now
5555            // so we don't have to marshall/unmarshall it.
5556            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5557                rii.filter = null;
5558            }
5559        }
5560
5561        // Filter out the caller activity if so requested.
5562        if (caller != null) {
5563            N = results.size();
5564            for (int i=0; i<N; i++) {
5565                ActivityInfo ainfo = results.get(i).activityInfo;
5566                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5567                        && caller.getClassName().equals(ainfo.name)) {
5568                    results.remove(i);
5569                    break;
5570                }
5571            }
5572        }
5573
5574        // If the caller didn't request filter information,
5575        // drop them now so we don't have to
5576        // marshall/unmarshall it.
5577        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5578            N = results.size();
5579            for (int i=0; i<N; i++) {
5580                results.get(i).filter = null;
5581            }
5582        }
5583
5584        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5585        return results;
5586    }
5587
5588    @Override
5589    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5590            int userId) {
5591        if (!sUserManager.exists(userId)) return Collections.emptyList();
5592        flags = updateFlagsForResolve(flags, userId, intent);
5593        ComponentName comp = intent.getComponent();
5594        if (comp == null) {
5595            if (intent.getSelector() != null) {
5596                intent = intent.getSelector();
5597                comp = intent.getComponent();
5598            }
5599        }
5600        if (comp != null) {
5601            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5602            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5603            if (ai != null) {
5604                ResolveInfo ri = new ResolveInfo();
5605                ri.activityInfo = ai;
5606                list.add(ri);
5607            }
5608            return list;
5609        }
5610
5611        // reader
5612        synchronized (mPackages) {
5613            String pkgName = intent.getPackage();
5614            if (pkgName == null) {
5615                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5616            }
5617            final PackageParser.Package pkg = mPackages.get(pkgName);
5618            if (pkg != null) {
5619                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5620                        userId);
5621            }
5622            return null;
5623        }
5624    }
5625
5626    @Override
5627    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5628        if (!sUserManager.exists(userId)) return null;
5629        flags = updateFlagsForResolve(flags, userId, intent);
5630        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5631        if (query != null) {
5632            if (query.size() >= 1) {
5633                // If there is more than one service with the same priority,
5634                // just arbitrarily pick the first one.
5635                return query.get(0);
5636            }
5637        }
5638        return null;
5639    }
5640
5641    @Override
5642    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5643            int userId) {
5644        if (!sUserManager.exists(userId)) return Collections.emptyList();
5645        flags = updateFlagsForResolve(flags, userId, intent);
5646        ComponentName comp = intent.getComponent();
5647        if (comp == null) {
5648            if (intent.getSelector() != null) {
5649                intent = intent.getSelector();
5650                comp = intent.getComponent();
5651            }
5652        }
5653        if (comp != null) {
5654            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5655            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5656            if (si != null) {
5657                final ResolveInfo ri = new ResolveInfo();
5658                ri.serviceInfo = si;
5659                list.add(ri);
5660            }
5661            return list;
5662        }
5663
5664        // reader
5665        synchronized (mPackages) {
5666            String pkgName = intent.getPackage();
5667            if (pkgName == null) {
5668                return mServices.queryIntent(intent, resolvedType, flags, userId);
5669            }
5670            final PackageParser.Package pkg = mPackages.get(pkgName);
5671            if (pkg != null) {
5672                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5673                        userId);
5674            }
5675            return null;
5676        }
5677    }
5678
5679    @Override
5680    public List<ResolveInfo> queryIntentContentProviders(
5681            Intent intent, String resolvedType, int flags, int userId) {
5682        if (!sUserManager.exists(userId)) return Collections.emptyList();
5683        flags = updateFlagsForResolve(flags, userId, intent);
5684        ComponentName comp = intent.getComponent();
5685        if (comp == null) {
5686            if (intent.getSelector() != null) {
5687                intent = intent.getSelector();
5688                comp = intent.getComponent();
5689            }
5690        }
5691        if (comp != null) {
5692            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5693            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5694            if (pi != null) {
5695                final ResolveInfo ri = new ResolveInfo();
5696                ri.providerInfo = pi;
5697                list.add(ri);
5698            }
5699            return list;
5700        }
5701
5702        // reader
5703        synchronized (mPackages) {
5704            String pkgName = intent.getPackage();
5705            if (pkgName == null) {
5706                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5707            }
5708            final PackageParser.Package pkg = mPackages.get(pkgName);
5709            if (pkg != null) {
5710                return mProviders.queryIntentForPackage(
5711                        intent, resolvedType, flags, pkg.providers, userId);
5712            }
5713            return null;
5714        }
5715    }
5716
5717    @Override
5718    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5719        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5720        flags = updateFlagsForPackage(flags, userId, null);
5721        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5722        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5723
5724        // writer
5725        synchronized (mPackages) {
5726            ArrayList<PackageInfo> list;
5727            if (listUninstalled) {
5728                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5729                for (PackageSetting ps : mSettings.mPackages.values()) {
5730                    PackageInfo pi;
5731                    if (ps.pkg != null) {
5732                        pi = generatePackageInfo(ps.pkg, flags, userId);
5733                    } else {
5734                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5735                    }
5736                    if (pi != null) {
5737                        list.add(pi);
5738                    }
5739                }
5740            } else {
5741                list = new ArrayList<PackageInfo>(mPackages.size());
5742                for (PackageParser.Package p : mPackages.values()) {
5743                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5744                    if (pi != null) {
5745                        list.add(pi);
5746                    }
5747                }
5748            }
5749
5750            return new ParceledListSlice<PackageInfo>(list);
5751        }
5752    }
5753
5754    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5755            String[] permissions, boolean[] tmp, int flags, int userId) {
5756        int numMatch = 0;
5757        final PermissionsState permissionsState = ps.getPermissionsState();
5758        for (int i=0; i<permissions.length; i++) {
5759            final String permission = permissions[i];
5760            if (permissionsState.hasPermission(permission, userId)) {
5761                tmp[i] = true;
5762                numMatch++;
5763            } else {
5764                tmp[i] = false;
5765            }
5766        }
5767        if (numMatch == 0) {
5768            return;
5769        }
5770        PackageInfo pi;
5771        if (ps.pkg != null) {
5772            pi = generatePackageInfo(ps.pkg, flags, userId);
5773        } else {
5774            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5775        }
5776        // The above might return null in cases of uninstalled apps or install-state
5777        // skew across users/profiles.
5778        if (pi != null) {
5779            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5780                if (numMatch == permissions.length) {
5781                    pi.requestedPermissions = permissions;
5782                } else {
5783                    pi.requestedPermissions = new String[numMatch];
5784                    numMatch = 0;
5785                    for (int i=0; i<permissions.length; i++) {
5786                        if (tmp[i]) {
5787                            pi.requestedPermissions[numMatch] = permissions[i];
5788                            numMatch++;
5789                        }
5790                    }
5791                }
5792            }
5793            list.add(pi);
5794        }
5795    }
5796
5797    @Override
5798    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5799            String[] permissions, int flags, int userId) {
5800        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5801        flags = updateFlagsForPackage(flags, userId, permissions);
5802        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5803
5804        // writer
5805        synchronized (mPackages) {
5806            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5807            boolean[] tmpBools = new boolean[permissions.length];
5808            if (listUninstalled) {
5809                for (PackageSetting ps : mSettings.mPackages.values()) {
5810                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5811                }
5812            } else {
5813                for (PackageParser.Package pkg : mPackages.values()) {
5814                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5815                    if (ps != null) {
5816                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5817                                userId);
5818                    }
5819                }
5820            }
5821
5822            return new ParceledListSlice<PackageInfo>(list);
5823        }
5824    }
5825
5826    @Override
5827    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5828        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5829        flags = updateFlagsForApplication(flags, userId, null);
5830        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5831
5832        // writer
5833        synchronized (mPackages) {
5834            ArrayList<ApplicationInfo> list;
5835            if (listUninstalled) {
5836                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5837                for (PackageSetting ps : mSettings.mPackages.values()) {
5838                    ApplicationInfo ai;
5839                    if (ps.pkg != null) {
5840                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5841                                ps.readUserState(userId), userId);
5842                    } else {
5843                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5844                    }
5845                    if (ai != null) {
5846                        list.add(ai);
5847                    }
5848                }
5849            } else {
5850                list = new ArrayList<ApplicationInfo>(mPackages.size());
5851                for (PackageParser.Package p : mPackages.values()) {
5852                    if (p.mExtras != null) {
5853                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5854                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5855                        if (ai != null) {
5856                            list.add(ai);
5857                        }
5858                    }
5859                }
5860            }
5861
5862            return new ParceledListSlice<ApplicationInfo>(list);
5863        }
5864    }
5865
5866    @Override
5867    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5868        if (DISABLE_EPHEMERAL_APPS) {
5869            return null;
5870        }
5871
5872        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5873                "getEphemeralApplications");
5874        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5875                "getEphemeralApplications");
5876        synchronized (mPackages) {
5877            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5878                    .getEphemeralApplicationsLPw(userId);
5879            if (ephemeralApps != null) {
5880                return new ParceledListSlice<>(ephemeralApps);
5881            }
5882        }
5883        return null;
5884    }
5885
5886    @Override
5887    public boolean isEphemeralApplication(String packageName, int userId) {
5888        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5889                "isEphemeral");
5890        if (DISABLE_EPHEMERAL_APPS) {
5891            return false;
5892        }
5893
5894        if (!isCallerSameApp(packageName)) {
5895            return false;
5896        }
5897        synchronized (mPackages) {
5898            PackageParser.Package pkg = mPackages.get(packageName);
5899            if (pkg != null) {
5900                return pkg.applicationInfo.isEphemeralApp();
5901            }
5902        }
5903        return false;
5904    }
5905
5906    @Override
5907    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5908        if (DISABLE_EPHEMERAL_APPS) {
5909            return null;
5910        }
5911
5912        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5913                "getCookie");
5914        if (!isCallerSameApp(packageName)) {
5915            return null;
5916        }
5917        synchronized (mPackages) {
5918            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5919                    packageName, userId);
5920        }
5921    }
5922
5923    @Override
5924    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5925        if (DISABLE_EPHEMERAL_APPS) {
5926            return true;
5927        }
5928
5929        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5930                "setCookie");
5931        if (!isCallerSameApp(packageName)) {
5932            return false;
5933        }
5934        synchronized (mPackages) {
5935            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5936                    packageName, cookie, userId);
5937        }
5938    }
5939
5940    @Override
5941    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5942        if (DISABLE_EPHEMERAL_APPS) {
5943            return null;
5944        }
5945
5946        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5947                "getEphemeralApplicationIcon");
5948        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5949                "getEphemeralApplicationIcon");
5950        synchronized (mPackages) {
5951            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5952                    packageName, userId);
5953        }
5954    }
5955
5956    private boolean isCallerSameApp(String packageName) {
5957        PackageParser.Package pkg = mPackages.get(packageName);
5958        return pkg != null
5959                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5960    }
5961
5962    public List<ApplicationInfo> getPersistentApplications(int flags) {
5963        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5964
5965        // reader
5966        synchronized (mPackages) {
5967            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5968            final int userId = UserHandle.getCallingUserId();
5969            while (i.hasNext()) {
5970                final PackageParser.Package p = i.next();
5971                if (p.applicationInfo != null
5972                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5973                        && (!mSafeMode || isSystemApp(p))) {
5974                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5975                    if (ps != null) {
5976                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5977                                ps.readUserState(userId), userId);
5978                        if (ai != null) {
5979                            finalList.add(ai);
5980                        }
5981                    }
5982                }
5983            }
5984        }
5985
5986        return finalList;
5987    }
5988
5989    @Override
5990    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5991        if (!sUserManager.exists(userId)) return null;
5992        flags = updateFlagsForComponent(flags, userId, name);
5993        // reader
5994        synchronized (mPackages) {
5995            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5996            PackageSetting ps = provider != null
5997                    ? mSettings.mPackages.get(provider.owner.packageName)
5998                    : null;
5999            return ps != null
6000                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6001                    ? PackageParser.generateProviderInfo(provider, flags,
6002                            ps.readUserState(userId), userId)
6003                    : null;
6004        }
6005    }
6006
6007    /**
6008     * @deprecated
6009     */
6010    @Deprecated
6011    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6012        // reader
6013        synchronized (mPackages) {
6014            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6015                    .entrySet().iterator();
6016            final int userId = UserHandle.getCallingUserId();
6017            while (i.hasNext()) {
6018                Map.Entry<String, PackageParser.Provider> entry = i.next();
6019                PackageParser.Provider p = entry.getValue();
6020                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6021
6022                if (ps != null && p.syncable
6023                        && (!mSafeMode || (p.info.applicationInfo.flags
6024                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6025                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6026                            ps.readUserState(userId), userId);
6027                    if (info != null) {
6028                        outNames.add(entry.getKey());
6029                        outInfo.add(info);
6030                    }
6031                }
6032            }
6033        }
6034    }
6035
6036    @Override
6037    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6038            int uid, int flags) {
6039        final int userId = processName != null ? UserHandle.getUserId(uid)
6040                : UserHandle.getCallingUserId();
6041        if (!sUserManager.exists(userId)) return null;
6042        flags = updateFlagsForComponent(flags, userId, processName);
6043
6044        ArrayList<ProviderInfo> finalList = null;
6045        // reader
6046        synchronized (mPackages) {
6047            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6048            while (i.hasNext()) {
6049                final PackageParser.Provider p = i.next();
6050                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6051                if (ps != null && p.info.authority != null
6052                        && (processName == null
6053                                || (p.info.processName.equals(processName)
6054                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6055                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6056                    if (finalList == null) {
6057                        finalList = new ArrayList<ProviderInfo>(3);
6058                    }
6059                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6060                            ps.readUserState(userId), userId);
6061                    if (info != null) {
6062                        finalList.add(info);
6063                    }
6064                }
6065            }
6066        }
6067
6068        if (finalList != null) {
6069            Collections.sort(finalList, mProviderInitOrderSorter);
6070            return new ParceledListSlice<ProviderInfo>(finalList);
6071        }
6072
6073        return null;
6074    }
6075
6076    @Override
6077    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6078        // reader
6079        synchronized (mPackages) {
6080            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6081            return PackageParser.generateInstrumentationInfo(i, flags);
6082        }
6083    }
6084
6085    @Override
6086    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6087            int flags) {
6088        ArrayList<InstrumentationInfo> finalList =
6089            new ArrayList<InstrumentationInfo>();
6090
6091        // reader
6092        synchronized (mPackages) {
6093            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6094            while (i.hasNext()) {
6095                final PackageParser.Instrumentation p = i.next();
6096                if (targetPackage == null
6097                        || targetPackage.equals(p.info.targetPackage)) {
6098                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6099                            flags);
6100                    if (ii != null) {
6101                        finalList.add(ii);
6102                    }
6103                }
6104            }
6105        }
6106
6107        return finalList;
6108    }
6109
6110    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6111        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6112        if (overlays == null) {
6113            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6114            return;
6115        }
6116        for (PackageParser.Package opkg : overlays.values()) {
6117            // Not much to do if idmap fails: we already logged the error
6118            // and we certainly don't want to abort installation of pkg simply
6119            // because an overlay didn't fit properly. For these reasons,
6120            // ignore the return value of createIdmapForPackagePairLI.
6121            createIdmapForPackagePairLI(pkg, opkg);
6122        }
6123    }
6124
6125    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6126            PackageParser.Package opkg) {
6127        if (!opkg.mTrustedOverlay) {
6128            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6129                    opkg.baseCodePath + ": overlay not trusted");
6130            return false;
6131        }
6132        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6133        if (overlaySet == null) {
6134            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6135                    opkg.baseCodePath + " but target package has no known overlays");
6136            return false;
6137        }
6138        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6139        // TODO: generate idmap for split APKs
6140        try {
6141            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6142        } catch (InstallerException e) {
6143            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6144                    + opkg.baseCodePath);
6145            return false;
6146        }
6147        PackageParser.Package[] overlayArray =
6148            overlaySet.values().toArray(new PackageParser.Package[0]);
6149        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6150            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6151                return p1.mOverlayPriority - p2.mOverlayPriority;
6152            }
6153        };
6154        Arrays.sort(overlayArray, cmp);
6155
6156        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6157        int i = 0;
6158        for (PackageParser.Package p : overlayArray) {
6159            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6160        }
6161        return true;
6162    }
6163
6164    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6165        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6166        try {
6167            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6168        } finally {
6169            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6170        }
6171    }
6172
6173    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6174        final File[] files = dir.listFiles();
6175        if (ArrayUtils.isEmpty(files)) {
6176            Log.d(TAG, "No files in app dir " + dir);
6177            return;
6178        }
6179
6180        if (DEBUG_PACKAGE_SCANNING) {
6181            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6182                    + " flags=0x" + Integer.toHexString(parseFlags));
6183        }
6184
6185        for (File file : files) {
6186            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6187                    && !PackageInstallerService.isStageName(file.getName());
6188            if (!isPackage) {
6189                // Ignore entries which are not packages
6190                continue;
6191            }
6192            try {
6193                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6194                        scanFlags, currentTime, null);
6195            } catch (PackageManagerException e) {
6196                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6197
6198                // Delete invalid userdata apps
6199                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6200                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6201                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6202                    removeCodePathLI(file);
6203                }
6204            }
6205        }
6206    }
6207
6208    private static File getSettingsProblemFile() {
6209        File dataDir = Environment.getDataDirectory();
6210        File systemDir = new File(dataDir, "system");
6211        File fname = new File(systemDir, "uiderrors.txt");
6212        return fname;
6213    }
6214
6215    static void reportSettingsProblem(int priority, String msg) {
6216        logCriticalInfo(priority, msg);
6217    }
6218
6219    static void logCriticalInfo(int priority, String msg) {
6220        Slog.println(priority, TAG, msg);
6221        EventLogTags.writePmCriticalInfo(msg);
6222        try {
6223            File fname = getSettingsProblemFile();
6224            FileOutputStream out = new FileOutputStream(fname, true);
6225            PrintWriter pw = new FastPrintWriter(out);
6226            SimpleDateFormat formatter = new SimpleDateFormat();
6227            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6228            pw.println(dateString + ": " + msg);
6229            pw.close();
6230            FileUtils.setPermissions(
6231                    fname.toString(),
6232                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6233                    -1, -1);
6234        } catch (java.io.IOException e) {
6235        }
6236    }
6237
6238    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6239            PackageParser.Package pkg, File srcFile, int parseFlags)
6240            throws PackageManagerException {
6241        if (ps != null
6242                && ps.codePath.equals(srcFile)
6243                && ps.timeStamp == srcFile.lastModified()
6244                && !isCompatSignatureUpdateNeeded(pkg)
6245                && !isRecoverSignatureUpdateNeeded(pkg)) {
6246            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6247            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6248            ArraySet<PublicKey> signingKs;
6249            synchronized (mPackages) {
6250                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6251            }
6252            if (ps.signatures.mSignatures != null
6253                    && ps.signatures.mSignatures.length != 0
6254                    && signingKs != null) {
6255                // Optimization: reuse the existing cached certificates
6256                // if the package appears to be unchanged.
6257                pkg.mSignatures = ps.signatures.mSignatures;
6258                pkg.mSigningKeys = signingKs;
6259                return;
6260            }
6261
6262            Slog.w(TAG, "PackageSetting for " + ps.name
6263                    + " is missing signatures.  Collecting certs again to recover them.");
6264        } else {
6265            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6266        }
6267
6268        try {
6269            pp.collectCertificates(pkg, parseFlags);
6270        } catch (PackageParserException e) {
6271            throw PackageManagerException.from(e);
6272        }
6273    }
6274
6275    /**
6276     *  Traces a package scan.
6277     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6278     */
6279    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6280            long currentTime, UserHandle user) throws PackageManagerException {
6281        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6282        try {
6283            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6284        } finally {
6285            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6286        }
6287    }
6288
6289    /**
6290     *  Scans a package and returns the newly parsed package.
6291     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6292     */
6293    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6294            long currentTime, UserHandle user) throws PackageManagerException {
6295        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6296        parseFlags |= mDefParseFlags;
6297        PackageParser pp = new PackageParser();
6298        pp.setSeparateProcesses(mSeparateProcesses);
6299        pp.setOnlyCoreApps(mOnlyCore);
6300        pp.setDisplayMetrics(mMetrics);
6301
6302        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6303            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6304        }
6305
6306        final PackageParser.Package pkg;
6307        try {
6308            pkg = pp.parsePackage(scanFile, parseFlags);
6309        } catch (PackageParserException e) {
6310            throw PackageManagerException.from(e);
6311        }
6312
6313        PackageSetting ps = null;
6314        PackageSetting updatedPkg;
6315        // reader
6316        synchronized (mPackages) {
6317            // Look to see if we already know about this package.
6318            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6319            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6320                // This package has been renamed to its original name.  Let's
6321                // use that.
6322                ps = mSettings.peekPackageLPr(oldName);
6323            }
6324            // If there was no original package, see one for the real package name.
6325            if (ps == null) {
6326                ps = mSettings.peekPackageLPr(pkg.packageName);
6327            }
6328            // Check to see if this package could be hiding/updating a system
6329            // package.  Must look for it either under the original or real
6330            // package name depending on our state.
6331            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6332            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6333        }
6334        boolean updatedPkgBetter = false;
6335        // First check if this is a system package that may involve an update
6336        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6337            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6338            // it needs to drop FLAG_PRIVILEGED.
6339            if (locationIsPrivileged(scanFile)) {
6340                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6341            } else {
6342                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6343            }
6344
6345            if (ps != null && !ps.codePath.equals(scanFile)) {
6346                // The path has changed from what was last scanned...  check the
6347                // version of the new path against what we have stored to determine
6348                // what to do.
6349                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6350                if (pkg.mVersionCode <= ps.versionCode) {
6351                    // The system package has been updated and the code path does not match
6352                    // Ignore entry. Skip it.
6353                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6354                            + " ignored: updated version " + ps.versionCode
6355                            + " better than this " + pkg.mVersionCode);
6356                    if (!updatedPkg.codePath.equals(scanFile)) {
6357                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6358                                + ps.name + " changing from " + updatedPkg.codePathString
6359                                + " to " + scanFile);
6360                        updatedPkg.codePath = scanFile;
6361                        updatedPkg.codePathString = scanFile.toString();
6362                        updatedPkg.resourcePath = scanFile;
6363                        updatedPkg.resourcePathString = scanFile.toString();
6364                    }
6365                    updatedPkg.pkg = pkg;
6366                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6367                            "Package " + ps.name + " at " + scanFile
6368                                    + " ignored: updated version " + ps.versionCode
6369                                    + " better than this " + pkg.mVersionCode);
6370                } else {
6371                    // The current app on the system partition is better than
6372                    // what we have updated to on the data partition; switch
6373                    // back to the system partition version.
6374                    // At this point, its safely assumed that package installation for
6375                    // apps in system partition will go through. If not there won't be a working
6376                    // version of the app
6377                    // writer
6378                    synchronized (mPackages) {
6379                        // Just remove the loaded entries from package lists.
6380                        mPackages.remove(ps.name);
6381                    }
6382
6383                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6384                            + " reverting from " + ps.codePathString
6385                            + ": new version " + pkg.mVersionCode
6386                            + " better than installed " + ps.versionCode);
6387
6388                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6389                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6390                    synchronized (mInstallLock) {
6391                        args.cleanUpResourcesLI();
6392                    }
6393                    synchronized (mPackages) {
6394                        mSettings.enableSystemPackageLPw(ps.name);
6395                    }
6396                    updatedPkgBetter = true;
6397                }
6398            }
6399        }
6400
6401        if (updatedPkg != null) {
6402            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6403            // initially
6404            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6405
6406            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6407            // flag set initially
6408            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6409                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6410            }
6411        }
6412
6413        // Verify certificates against what was last scanned
6414        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6415
6416        /*
6417         * A new system app appeared, but we already had a non-system one of the
6418         * same name installed earlier.
6419         */
6420        boolean shouldHideSystemApp = false;
6421        if (updatedPkg == null && ps != null
6422                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6423            /*
6424             * Check to make sure the signatures match first. If they don't,
6425             * wipe the installed application and its data.
6426             */
6427            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6428                    != PackageManager.SIGNATURE_MATCH) {
6429                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6430                        + " signatures don't match existing userdata copy; removing");
6431                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6432                ps = null;
6433            } else {
6434                /*
6435                 * If the newly-added system app is an older version than the
6436                 * already installed version, hide it. It will be scanned later
6437                 * and re-added like an update.
6438                 */
6439                if (pkg.mVersionCode <= ps.versionCode) {
6440                    shouldHideSystemApp = true;
6441                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6442                            + " but new version " + pkg.mVersionCode + " better than installed "
6443                            + ps.versionCode + "; hiding system");
6444                } else {
6445                    /*
6446                     * The newly found system app is a newer version that the
6447                     * one previously installed. Simply remove the
6448                     * already-installed application and replace it with our own
6449                     * while keeping the application data.
6450                     */
6451                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6452                            + " reverting from " + ps.codePathString + ": new version "
6453                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6454                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6455                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6456                    synchronized (mInstallLock) {
6457                        args.cleanUpResourcesLI();
6458                    }
6459                }
6460            }
6461        }
6462
6463        // The apk is forward locked (not public) if its code and resources
6464        // are kept in different files. (except for app in either system or
6465        // vendor path).
6466        // TODO grab this value from PackageSettings
6467        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6468            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6469                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6470            }
6471        }
6472
6473        // TODO: extend to support forward-locked splits
6474        String resourcePath = null;
6475        String baseResourcePath = null;
6476        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6477            if (ps != null && ps.resourcePathString != null) {
6478                resourcePath = ps.resourcePathString;
6479                baseResourcePath = ps.resourcePathString;
6480            } else {
6481                // Should not happen at all. Just log an error.
6482                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6483            }
6484        } else {
6485            resourcePath = pkg.codePath;
6486            baseResourcePath = pkg.baseCodePath;
6487        }
6488
6489        // Set application objects path explicitly.
6490        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6491        pkg.applicationInfo.setCodePath(pkg.codePath);
6492        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6493        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6494        pkg.applicationInfo.setResourcePath(resourcePath);
6495        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6496        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6497
6498        // Note that we invoke the following method only if we are about to unpack an application
6499        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6500                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6501
6502        /*
6503         * If the system app should be overridden by a previously installed
6504         * data, hide the system app now and let the /data/app scan pick it up
6505         * again.
6506         */
6507        if (shouldHideSystemApp) {
6508            synchronized (mPackages) {
6509                mSettings.disableSystemPackageLPw(pkg.packageName);
6510            }
6511        }
6512
6513        return scannedPkg;
6514    }
6515
6516    private static String fixProcessName(String defProcessName,
6517            String processName, int uid) {
6518        if (processName == null) {
6519            return defProcessName;
6520        }
6521        return processName;
6522    }
6523
6524    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6525            throws PackageManagerException {
6526        if (pkgSetting.signatures.mSignatures != null) {
6527            // Already existing package. Make sure signatures match
6528            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6529                    == PackageManager.SIGNATURE_MATCH;
6530            if (!match) {
6531                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6532                        == PackageManager.SIGNATURE_MATCH;
6533            }
6534            if (!match) {
6535                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6536                        == PackageManager.SIGNATURE_MATCH;
6537            }
6538            if (!match) {
6539                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6540                        + pkg.packageName + " signatures do not match the "
6541                        + "previously installed version; ignoring!");
6542            }
6543        }
6544
6545        // Check for shared user signatures
6546        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6547            // Already existing package. Make sure signatures match
6548            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6549                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6550            if (!match) {
6551                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6552                        == PackageManager.SIGNATURE_MATCH;
6553            }
6554            if (!match) {
6555                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6556                        == PackageManager.SIGNATURE_MATCH;
6557            }
6558            if (!match) {
6559                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6560                        "Package " + pkg.packageName
6561                        + " has no signatures that match those in shared user "
6562                        + pkgSetting.sharedUser.name + "; ignoring!");
6563            }
6564        }
6565    }
6566
6567    /**
6568     * Enforces that only the system UID or root's UID can call a method exposed
6569     * via Binder.
6570     *
6571     * @param message used as message if SecurityException is thrown
6572     * @throws SecurityException if the caller is not system or root
6573     */
6574    private static final void enforceSystemOrRoot(String message) {
6575        final int uid = Binder.getCallingUid();
6576        if (uid != Process.SYSTEM_UID && uid != 0) {
6577            throw new SecurityException(message);
6578        }
6579    }
6580
6581    @Override
6582    public void performFstrimIfNeeded() {
6583        enforceSystemOrRoot("Only the system can request fstrim");
6584
6585        // Before everything else, see whether we need to fstrim.
6586        try {
6587            IMountService ms = PackageHelper.getMountService();
6588            if (ms != null) {
6589                final boolean isUpgrade = isUpgrade();
6590                boolean doTrim = isUpgrade;
6591                if (doTrim) {
6592                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6593                } else {
6594                    final long interval = android.provider.Settings.Global.getLong(
6595                            mContext.getContentResolver(),
6596                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6597                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6598                    if (interval > 0) {
6599                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6600                        if (timeSinceLast > interval) {
6601                            doTrim = true;
6602                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6603                                    + "; running immediately");
6604                        }
6605                    }
6606                }
6607                if (doTrim) {
6608                    if (!isFirstBoot()) {
6609                        try {
6610                            ActivityManagerNative.getDefault().showBootMessage(
6611                                    mContext.getResources().getString(
6612                                            R.string.android_upgrading_fstrim), true);
6613                        } catch (RemoteException e) {
6614                        }
6615                    }
6616                    ms.runMaintenance();
6617                }
6618            } else {
6619                Slog.e(TAG, "Mount service unavailable!");
6620            }
6621        } catch (RemoteException e) {
6622            // Can't happen; MountService is local
6623        }
6624    }
6625
6626    @Override
6627    public void extractPackagesIfNeeded() {
6628        enforceSystemOrRoot("Only the system can request package extraction");
6629
6630        // Extract pacakges only if profile-guided compilation is enabled because
6631        // otherwise BackgroundDexOptService will not dexopt them later.
6632        if (mUseJitProfiles) {
6633            ArraySet<String> pkgs = getOptimizablePackages();
6634            if (pkgs != null) {
6635                for (String pkg : pkgs) {
6636                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6637                            true /* extractOnly */, false /* force */);
6638                }
6639            }
6640        }
6641    }
6642
6643    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6644        List<ResolveInfo> ris = null;
6645        try {
6646            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6647                    intent, null, 0, userId);
6648        } catch (RemoteException e) {
6649        }
6650        ArraySet<String> pkgNames = new ArraySet<String>();
6651        if (ris != null) {
6652            for (ResolveInfo ri : ris) {
6653                pkgNames.add(ri.activityInfo.packageName);
6654            }
6655        }
6656        return pkgNames;
6657    }
6658
6659    @Override
6660    public void notifyPackageUse(String packageName) {
6661        synchronized (mPackages) {
6662            PackageParser.Package p = mPackages.get(packageName);
6663            if (p == null) {
6664                return;
6665            }
6666            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6667        }
6668    }
6669
6670    // TODO: this is not used nor needed. Delete it.
6671    @Override
6672    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6673        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6674                false /* extractOnly */, false /* force */);
6675    }
6676
6677    @Override
6678    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6679            boolean extractOnly, boolean force) {
6680        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6681    }
6682
6683    private boolean performDexOptTraced(String packageName, String instructionSet,
6684                boolean useProfiles, boolean extractOnly, boolean force) {
6685        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6686        try {
6687            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6688                    force);
6689        } finally {
6690            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6691        }
6692    }
6693
6694    private boolean performDexOptInternal(String packageName, String instructionSet,
6695                boolean useProfiles, boolean extractOnly, boolean force) {
6696        PackageParser.Package p;
6697        final String targetInstructionSet;
6698        synchronized (mPackages) {
6699            p = mPackages.get(packageName);
6700            if (p == null) {
6701                return false;
6702            }
6703            mPackageUsage.write(false);
6704
6705            targetInstructionSet = instructionSet != null ? instructionSet :
6706                    getPrimaryInstructionSet(p.applicationInfo);
6707            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6708                // Skip only if we do not use profiles since they might trigger a recompilation.
6709                return false;
6710            }
6711        }
6712        long callingId = Binder.clearCallingIdentity();
6713        try {
6714            synchronized (mInstallLock) {
6715                final String[] instructionSets = new String[] { targetInstructionSet };
6716                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6717                        useProfiles, extractOnly, force);
6718                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6719            }
6720        } finally {
6721            Binder.restoreCallingIdentity(callingId);
6722        }
6723    }
6724
6725    public ArraySet<String> getOptimizablePackages() {
6726        ArraySet<String> pkgs = new ArraySet<String>();
6727        synchronized (mPackages) {
6728            for (PackageParser.Package p : mPackages.values()) {
6729                if (PackageDexOptimizer.canOptimizePackage(p)) {
6730                    pkgs.add(p.packageName);
6731                }
6732            }
6733        }
6734        return pkgs;
6735    }
6736
6737    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6738            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6739        // Select the dex optimizer based on the force parameter.
6740        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6741        //       allocate an object here.
6742        PackageDexOptimizer pdo = force
6743                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6744                : mPackageDexOptimizer;
6745
6746        // Optimize all dependencies first. Note: we ignore the return value and march on
6747        // on errors.
6748        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6749        if (!deps.isEmpty()) {
6750            for (PackageParser.Package depPackage : deps) {
6751                // TODO: Analyze and investigate if we (should) profile libraries.
6752                // Currently this will do a full compilation of the library.
6753                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6754                        false /* extractOnly */);
6755            }
6756        }
6757
6758        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6759    }
6760
6761    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6762        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6763            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6764            Set<String> collectedNames = new HashSet<>();
6765            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6766
6767            retValue.remove(p);
6768
6769            return retValue;
6770        } else {
6771            return Collections.emptyList();
6772        }
6773    }
6774
6775    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6776            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6777        if (!collectedNames.contains(p.packageName)) {
6778            collectedNames.add(p.packageName);
6779            collected.add(p);
6780
6781            if (p.usesLibraries != null) {
6782                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6783            }
6784            if (p.usesOptionalLibraries != null) {
6785                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6786                        collectedNames);
6787            }
6788        }
6789    }
6790
6791    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6792            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6793        for (String libName : libs) {
6794            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6795            if (libPkg != null) {
6796                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6797            }
6798        }
6799    }
6800
6801    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6802        synchronized (mPackages) {
6803            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6804            if (lib != null && lib.apk != null) {
6805                return mPackages.get(lib.apk);
6806            }
6807        }
6808        return null;
6809    }
6810
6811    public void shutdown() {
6812        mPackageUsage.write(true);
6813    }
6814
6815    @Override
6816    public void forceDexOpt(String packageName) {
6817        enforceSystemOrRoot("forceDexOpt");
6818
6819        PackageParser.Package pkg;
6820        synchronized (mPackages) {
6821            pkg = mPackages.get(packageName);
6822            if (pkg == null) {
6823                throw new IllegalArgumentException("Unknown package: " + packageName);
6824            }
6825        }
6826
6827        synchronized (mInstallLock) {
6828            final String[] instructionSets = new String[] {
6829                    getPrimaryInstructionSet(pkg.applicationInfo) };
6830
6831            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6832
6833            // Whoever is calling forceDexOpt wants a fully compiled package.
6834            // Don't use profiles since that may cause compilation to be skipped.
6835            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
6836                    false /* useProfiles */, false /* extractOnly */, true /* force */);
6837
6838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6839            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6840                throw new IllegalStateException("Failed to dexopt: " + res);
6841            }
6842        }
6843    }
6844
6845    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6846        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6847            Slog.w(TAG, "Unable to update from " + oldPkg.name
6848                    + " to " + newPkg.packageName
6849                    + ": old package not in system partition");
6850            return false;
6851        } else if (mPackages.get(oldPkg.name) != null) {
6852            Slog.w(TAG, "Unable to update from " + oldPkg.name
6853                    + " to " + newPkg.packageName
6854                    + ": old package still exists");
6855            return false;
6856        }
6857        return true;
6858    }
6859
6860    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6861        // TODO: triage flags as part of 26466827
6862        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
6863
6864        boolean res = true;
6865        final int[] users = sUserManager.getUserIds();
6866        for (int user : users) {
6867            try {
6868                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6869            } catch (InstallerException e) {
6870                Slog.w(TAG, "Failed to delete data directory", e);
6871                res = false;
6872            }
6873        }
6874        return res;
6875    }
6876
6877    void removeCodePathLI(File codePath) {
6878        if (codePath.isDirectory()) {
6879            try {
6880                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6881            } catch (InstallerException e) {
6882                Slog.w(TAG, "Failed to remove code path", e);
6883            }
6884        } else {
6885            codePath.delete();
6886        }
6887    }
6888
6889    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6890        try {
6891            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6892        } catch (InstallerException e) {
6893            Slog.w(TAG, "Failed to destroy app data", e);
6894        }
6895    }
6896
6897    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6898            int appId, String seinfo) {
6899        try {
6900            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6901        } catch (InstallerException e) {
6902            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6903        }
6904    }
6905
6906    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6907        // TODO: triage flags as part of 26466827
6908        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
6909
6910        final int[] users = sUserManager.getUserIds();
6911        for (int user : users) {
6912            try {
6913                mInstaller.clearAppData(volumeUuid, packageName, user,
6914                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6915            } catch (InstallerException e) {
6916                Slog.w(TAG, "Failed to delete code cache directory", e);
6917            }
6918        }
6919    }
6920
6921    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6922            PackageParser.Package changingLib) {
6923        if (file.path != null) {
6924            usesLibraryFiles.add(file.path);
6925            return;
6926        }
6927        PackageParser.Package p = mPackages.get(file.apk);
6928        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6929            // If we are doing this while in the middle of updating a library apk,
6930            // then we need to make sure to use that new apk for determining the
6931            // dependencies here.  (We haven't yet finished committing the new apk
6932            // to the package manager state.)
6933            if (p == null || p.packageName.equals(changingLib.packageName)) {
6934                p = changingLib;
6935            }
6936        }
6937        if (p != null) {
6938            usesLibraryFiles.addAll(p.getAllCodePaths());
6939        }
6940    }
6941
6942    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6943            PackageParser.Package changingLib) throws PackageManagerException {
6944        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6945            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6946            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6947            for (int i=0; i<N; i++) {
6948                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6949                if (file == null) {
6950                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6951                            "Package " + pkg.packageName + " requires unavailable shared library "
6952                            + pkg.usesLibraries.get(i) + "; failing!");
6953                }
6954                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6955            }
6956            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6957            for (int i=0; i<N; i++) {
6958                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6959                if (file == null) {
6960                    Slog.w(TAG, "Package " + pkg.packageName
6961                            + " desires unavailable shared library "
6962                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6963                } else {
6964                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6965                }
6966            }
6967            N = usesLibraryFiles.size();
6968            if (N > 0) {
6969                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6970            } else {
6971                pkg.usesLibraryFiles = null;
6972            }
6973        }
6974    }
6975
6976    private static boolean hasString(List<String> list, List<String> which) {
6977        if (list == null) {
6978            return false;
6979        }
6980        for (int i=list.size()-1; i>=0; i--) {
6981            for (int j=which.size()-1; j>=0; j--) {
6982                if (which.get(j).equals(list.get(i))) {
6983                    return true;
6984                }
6985            }
6986        }
6987        return false;
6988    }
6989
6990    private void updateAllSharedLibrariesLPw() {
6991        for (PackageParser.Package pkg : mPackages.values()) {
6992            try {
6993                updateSharedLibrariesLPw(pkg, null);
6994            } catch (PackageManagerException e) {
6995                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6996            }
6997        }
6998    }
6999
7000    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7001            PackageParser.Package changingPkg) {
7002        ArrayList<PackageParser.Package> res = null;
7003        for (PackageParser.Package pkg : mPackages.values()) {
7004            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7005                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7006                if (res == null) {
7007                    res = new ArrayList<PackageParser.Package>();
7008                }
7009                res.add(pkg);
7010                try {
7011                    updateSharedLibrariesLPw(pkg, changingPkg);
7012                } catch (PackageManagerException e) {
7013                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7014                }
7015            }
7016        }
7017        return res;
7018    }
7019
7020    /**
7021     * Derive the value of the {@code cpuAbiOverride} based on the provided
7022     * value and an optional stored value from the package settings.
7023     */
7024    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7025        String cpuAbiOverride = null;
7026
7027        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7028            cpuAbiOverride = null;
7029        } else if (abiOverride != null) {
7030            cpuAbiOverride = abiOverride;
7031        } else if (settings != null) {
7032            cpuAbiOverride = settings.cpuAbiOverrideString;
7033        }
7034
7035        return cpuAbiOverride;
7036    }
7037
7038    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7039            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7040        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7041        try {
7042            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7043        } finally {
7044            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7045        }
7046    }
7047
7048    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7049            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7050        boolean success = false;
7051        try {
7052            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7053                    currentTime, user);
7054            success = true;
7055            return res;
7056        } finally {
7057            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7058                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7059            }
7060        }
7061    }
7062
7063    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7064            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7065        final File scanFile = new File(pkg.codePath);
7066        if (pkg.applicationInfo.getCodePath() == null ||
7067                pkg.applicationInfo.getResourcePath() == null) {
7068            // Bail out. The resource and code paths haven't been set.
7069            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7070                    "Code and resource paths haven't been set correctly");
7071        }
7072
7073        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7074            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7075        } else {
7076            // Only allow system apps to be flagged as core apps.
7077            pkg.coreApp = false;
7078        }
7079
7080        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7081            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7082        }
7083
7084        if (mCustomResolverComponentName != null &&
7085                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7086            setUpCustomResolverActivity(pkg);
7087        }
7088
7089        if (pkg.packageName.equals("android")) {
7090            synchronized (mPackages) {
7091                if (mAndroidApplication != null) {
7092                    Slog.w(TAG, "*************************************************");
7093                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7094                    Slog.w(TAG, " file=" + scanFile);
7095                    Slog.w(TAG, "*************************************************");
7096                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7097                            "Core android package being redefined.  Skipping.");
7098                }
7099
7100                // Set up information for our fall-back user intent resolution activity.
7101                mPlatformPackage = pkg;
7102                pkg.mVersionCode = mSdkVersion;
7103                mAndroidApplication = pkg.applicationInfo;
7104
7105                if (!mResolverReplaced) {
7106                    mResolveActivity.applicationInfo = mAndroidApplication;
7107                    mResolveActivity.name = ResolverActivity.class.getName();
7108                    mResolveActivity.packageName = mAndroidApplication.packageName;
7109                    mResolveActivity.processName = "system:ui";
7110                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7111                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7112                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7113                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7114                    mResolveActivity.exported = true;
7115                    mResolveActivity.enabled = true;
7116                    mResolveInfo.activityInfo = mResolveActivity;
7117                    mResolveInfo.priority = 0;
7118                    mResolveInfo.preferredOrder = 0;
7119                    mResolveInfo.match = 0;
7120                    mResolveComponentName = new ComponentName(
7121                            mAndroidApplication.packageName, mResolveActivity.name);
7122                }
7123            }
7124        }
7125
7126        if (DEBUG_PACKAGE_SCANNING) {
7127            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7128                Log.d(TAG, "Scanning package " + pkg.packageName);
7129        }
7130
7131        if (mPackages.containsKey(pkg.packageName)
7132                || mSharedLibraries.containsKey(pkg.packageName)) {
7133            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7134                    "Application package " + pkg.packageName
7135                    + " already installed.  Skipping duplicate.");
7136        }
7137
7138        // If we're only installing presumed-existing packages, require that the
7139        // scanned APK is both already known and at the path previously established
7140        // for it.  Previously unknown packages we pick up normally, but if we have an
7141        // a priori expectation about this package's install presence, enforce it.
7142        // With a singular exception for new system packages. When an OTA contains
7143        // a new system package, we allow the codepath to change from a system location
7144        // to the user-installed location. If we don't allow this change, any newer,
7145        // user-installed version of the application will be ignored.
7146        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7147            if (mExpectingBetter.containsKey(pkg.packageName)) {
7148                logCriticalInfo(Log.WARN,
7149                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7150            } else {
7151                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7152                if (known != null) {
7153                    if (DEBUG_PACKAGE_SCANNING) {
7154                        Log.d(TAG, "Examining " + pkg.codePath
7155                                + " and requiring known paths " + known.codePathString
7156                                + " & " + known.resourcePathString);
7157                    }
7158                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7159                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7160                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7161                                "Application package " + pkg.packageName
7162                                + " found at " + pkg.applicationInfo.getCodePath()
7163                                + " but expected at " + known.codePathString + "; ignoring.");
7164                    }
7165                }
7166            }
7167        }
7168
7169        // Initialize package source and resource directories
7170        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7171        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7172
7173        SharedUserSetting suid = null;
7174        PackageSetting pkgSetting = null;
7175
7176        if (!isSystemApp(pkg)) {
7177            // Only system apps can use these features.
7178            pkg.mOriginalPackages = null;
7179            pkg.mRealPackage = null;
7180            pkg.mAdoptPermissions = null;
7181        }
7182
7183        // writer
7184        synchronized (mPackages) {
7185            if (pkg.mSharedUserId != null) {
7186                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7187                if (suid == null) {
7188                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7189                            "Creating application package " + pkg.packageName
7190                            + " for shared user failed");
7191                }
7192                if (DEBUG_PACKAGE_SCANNING) {
7193                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7194                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7195                                + "): packages=" + suid.packages);
7196                }
7197            }
7198
7199            // Check if we are renaming from an original package name.
7200            PackageSetting origPackage = null;
7201            String realName = null;
7202            if (pkg.mOriginalPackages != null) {
7203                // This package may need to be renamed to a previously
7204                // installed name.  Let's check on that...
7205                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7206                if (pkg.mOriginalPackages.contains(renamed)) {
7207                    // This package had originally been installed as the
7208                    // original name, and we have already taken care of
7209                    // transitioning to the new one.  Just update the new
7210                    // one to continue using the old name.
7211                    realName = pkg.mRealPackage;
7212                    if (!pkg.packageName.equals(renamed)) {
7213                        // Callers into this function may have already taken
7214                        // care of renaming the package; only do it here if
7215                        // it is not already done.
7216                        pkg.setPackageName(renamed);
7217                    }
7218
7219                } else {
7220                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7221                        if ((origPackage = mSettings.peekPackageLPr(
7222                                pkg.mOriginalPackages.get(i))) != null) {
7223                            // We do have the package already installed under its
7224                            // original name...  should we use it?
7225                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7226                                // New package is not compatible with original.
7227                                origPackage = null;
7228                                continue;
7229                            } else if (origPackage.sharedUser != null) {
7230                                // Make sure uid is compatible between packages.
7231                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7232                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7233                                            + " to " + pkg.packageName + ": old uid "
7234                                            + origPackage.sharedUser.name
7235                                            + " differs from " + pkg.mSharedUserId);
7236                                    origPackage = null;
7237                                    continue;
7238                                }
7239                            } else {
7240                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7241                                        + pkg.packageName + " to old name " + origPackage.name);
7242                            }
7243                            break;
7244                        }
7245                    }
7246                }
7247            }
7248
7249            if (mTransferedPackages.contains(pkg.packageName)) {
7250                Slog.w(TAG, "Package " + pkg.packageName
7251                        + " was transferred to another, but its .apk remains");
7252            }
7253
7254            // Just create the setting, don't add it yet. For already existing packages
7255            // the PkgSetting exists already and doesn't have to be created.
7256            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7257                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7258                    pkg.applicationInfo.primaryCpuAbi,
7259                    pkg.applicationInfo.secondaryCpuAbi,
7260                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7261                    user, false);
7262            if (pkgSetting == null) {
7263                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7264                        "Creating application package " + pkg.packageName + " failed");
7265            }
7266
7267            if (pkgSetting.origPackage != null) {
7268                // If we are first transitioning from an original package,
7269                // fix up the new package's name now.  We need to do this after
7270                // looking up the package under its new name, so getPackageLP
7271                // can take care of fiddling things correctly.
7272                pkg.setPackageName(origPackage.name);
7273
7274                // File a report about this.
7275                String msg = "New package " + pkgSetting.realName
7276                        + " renamed to replace old package " + pkgSetting.name;
7277                reportSettingsProblem(Log.WARN, msg);
7278
7279                // Make a note of it.
7280                mTransferedPackages.add(origPackage.name);
7281
7282                // No longer need to retain this.
7283                pkgSetting.origPackage = null;
7284            }
7285
7286            if (realName != null) {
7287                // Make a note of it.
7288                mTransferedPackages.add(pkg.packageName);
7289            }
7290
7291            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7292                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7293            }
7294
7295            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7296                // Check all shared libraries and map to their actual file path.
7297                // We only do this here for apps not on a system dir, because those
7298                // are the only ones that can fail an install due to this.  We
7299                // will take care of the system apps by updating all of their
7300                // library paths after the scan is done.
7301                updateSharedLibrariesLPw(pkg, null);
7302            }
7303
7304            if (mFoundPolicyFile) {
7305                SELinuxMMAC.assignSeinfoValue(pkg);
7306            }
7307
7308            pkg.applicationInfo.uid = pkgSetting.appId;
7309            pkg.mExtras = pkgSetting;
7310            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7311                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7312                    // We just determined the app is signed correctly, so bring
7313                    // over the latest parsed certs.
7314                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7315                } else {
7316                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7317                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7318                                "Package " + pkg.packageName + " upgrade keys do not match the "
7319                                + "previously installed version");
7320                    } else {
7321                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7322                        String msg = "System package " + pkg.packageName
7323                            + " signature changed; retaining data.";
7324                        reportSettingsProblem(Log.WARN, msg);
7325                    }
7326                }
7327            } else {
7328                try {
7329                    verifySignaturesLP(pkgSetting, pkg);
7330                    // We just determined the app is signed correctly, so bring
7331                    // over the latest parsed certs.
7332                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7333                } catch (PackageManagerException e) {
7334                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7335                        throw e;
7336                    }
7337                    // The signature has changed, but this package is in the system
7338                    // image...  let's recover!
7339                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7340                    // However...  if this package is part of a shared user, but it
7341                    // doesn't match the signature of the shared user, let's fail.
7342                    // What this means is that you can't change the signatures
7343                    // associated with an overall shared user, which doesn't seem all
7344                    // that unreasonable.
7345                    if (pkgSetting.sharedUser != null) {
7346                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7347                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7348                            throw new PackageManagerException(
7349                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7350                                            "Signature mismatch for shared user: "
7351                                            + pkgSetting.sharedUser);
7352                        }
7353                    }
7354                    // File a report about this.
7355                    String msg = "System package " + pkg.packageName
7356                        + " signature changed; retaining data.";
7357                    reportSettingsProblem(Log.WARN, msg);
7358                }
7359            }
7360            // Verify that this new package doesn't have any content providers
7361            // that conflict with existing packages.  Only do this if the
7362            // package isn't already installed, since we don't want to break
7363            // things that are installed.
7364            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7365                final int N = pkg.providers.size();
7366                int i;
7367                for (i=0; i<N; i++) {
7368                    PackageParser.Provider p = pkg.providers.get(i);
7369                    if (p.info.authority != null) {
7370                        String names[] = p.info.authority.split(";");
7371                        for (int j = 0; j < names.length; j++) {
7372                            if (mProvidersByAuthority.containsKey(names[j])) {
7373                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7374                                final String otherPackageName =
7375                                        ((other != null && other.getComponentName() != null) ?
7376                                                other.getComponentName().getPackageName() : "?");
7377                                throw new PackageManagerException(
7378                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7379                                                "Can't install because provider name " + names[j]
7380                                                + " (in package " + pkg.applicationInfo.packageName
7381                                                + ") is already used by " + otherPackageName);
7382                            }
7383                        }
7384                    }
7385                }
7386            }
7387
7388            if (pkg.mAdoptPermissions != null) {
7389                // This package wants to adopt ownership of permissions from
7390                // another package.
7391                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7392                    final String origName = pkg.mAdoptPermissions.get(i);
7393                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7394                    if (orig != null) {
7395                        if (verifyPackageUpdateLPr(orig, pkg)) {
7396                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7397                                    + pkg.packageName);
7398                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7399                        }
7400                    }
7401                }
7402            }
7403        }
7404
7405        final String pkgName = pkg.packageName;
7406
7407        final long scanFileTime = scanFile.lastModified();
7408        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7409        pkg.applicationInfo.processName = fixProcessName(
7410                pkg.applicationInfo.packageName,
7411                pkg.applicationInfo.processName,
7412                pkg.applicationInfo.uid);
7413
7414        if (pkg != mPlatformPackage) {
7415            // Get all of our default paths setup
7416            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7417        }
7418
7419        final String path = scanFile.getPath();
7420        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7421
7422        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7423            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7424
7425            // Some system apps still use directory structure for native libraries
7426            // in which case we might end up not detecting abi solely based on apk
7427            // structure. Try to detect abi based on directory structure.
7428            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7429                    pkg.applicationInfo.primaryCpuAbi == null) {
7430                setBundledAppAbisAndRoots(pkg, pkgSetting);
7431                setNativeLibraryPaths(pkg);
7432            }
7433
7434        } else {
7435            if ((scanFlags & SCAN_MOVE) != 0) {
7436                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7437                // but we already have this packages package info in the PackageSetting. We just
7438                // use that and derive the native library path based on the new codepath.
7439                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7440                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7441            }
7442
7443            // Set native library paths again. For moves, the path will be updated based on the
7444            // ABIs we've determined above. For non-moves, the path will be updated based on the
7445            // ABIs we determined during compilation, but the path will depend on the final
7446            // package path (after the rename away from the stage path).
7447            setNativeLibraryPaths(pkg);
7448        }
7449
7450        // This is a special case for the "system" package, where the ABI is
7451        // dictated by the zygote configuration (and init.rc). We should keep track
7452        // of this ABI so that we can deal with "normal" applications that run under
7453        // the same UID correctly.
7454        if (mPlatformPackage == pkg) {
7455            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7456                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7457        }
7458
7459        // If there's a mismatch between the abi-override in the package setting
7460        // and the abiOverride specified for the install. Warn about this because we
7461        // would've already compiled the app without taking the package setting into
7462        // account.
7463        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7464            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7465                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7466                        " for package " + pkg.packageName);
7467            }
7468        }
7469
7470        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7471        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7472        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7473
7474        // Copy the derived override back to the parsed package, so that we can
7475        // update the package settings accordingly.
7476        pkg.cpuAbiOverride = cpuAbiOverride;
7477
7478        if (DEBUG_ABI_SELECTION) {
7479            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7480                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7481                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7482        }
7483
7484        // Push the derived path down into PackageSettings so we know what to
7485        // clean up at uninstall time.
7486        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7487
7488        if (DEBUG_ABI_SELECTION) {
7489            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7490                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7491                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7492        }
7493
7494        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7495            // We don't do this here during boot because we can do it all
7496            // at once after scanning all existing packages.
7497            //
7498            // We also do this *before* we perform dexopt on this package, so that
7499            // we can avoid redundant dexopts, and also to make sure we've got the
7500            // code and package path correct.
7501            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7502                    pkg, true /* boot complete */);
7503        }
7504
7505        if (mFactoryTest && pkg.requestedPermissions.contains(
7506                android.Manifest.permission.FACTORY_TEST)) {
7507            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7508        }
7509
7510        ArrayList<PackageParser.Package> clientLibPkgs = null;
7511
7512        // writer
7513        synchronized (mPackages) {
7514            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7515                // Only system apps can add new shared libraries.
7516                if (pkg.libraryNames != null) {
7517                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7518                        String name = pkg.libraryNames.get(i);
7519                        boolean allowed = false;
7520                        if (pkg.isUpdatedSystemApp()) {
7521                            // New library entries can only be added through the
7522                            // system image.  This is important to get rid of a lot
7523                            // of nasty edge cases: for example if we allowed a non-
7524                            // system update of the app to add a library, then uninstalling
7525                            // the update would make the library go away, and assumptions
7526                            // we made such as through app install filtering would now
7527                            // have allowed apps on the device which aren't compatible
7528                            // with it.  Better to just have the restriction here, be
7529                            // conservative, and create many fewer cases that can negatively
7530                            // impact the user experience.
7531                            final PackageSetting sysPs = mSettings
7532                                    .getDisabledSystemPkgLPr(pkg.packageName);
7533                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7534                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7535                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7536                                        allowed = true;
7537                                        break;
7538                                    }
7539                                }
7540                            }
7541                        } else {
7542                            allowed = true;
7543                        }
7544                        if (allowed) {
7545                            if (!mSharedLibraries.containsKey(name)) {
7546                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7547                            } else if (!name.equals(pkg.packageName)) {
7548                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7549                                        + name + " already exists; skipping");
7550                            }
7551                        } else {
7552                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7553                                    + name + " that is not declared on system image; skipping");
7554                        }
7555                    }
7556                    if ((scanFlags & SCAN_BOOTING) == 0) {
7557                        // If we are not booting, we need to update any applications
7558                        // that are clients of our shared library.  If we are booting,
7559                        // this will all be done once the scan is complete.
7560                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7561                    }
7562                }
7563            }
7564        }
7565
7566        // Request the ActivityManager to kill the process(only for existing packages)
7567        // so that we do not end up in a confused state while the user is still using the older
7568        // version of the application while the new one gets installed.
7569        if ((scanFlags & SCAN_REPLACING) != 0) {
7570            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7571
7572            killApplication(pkg.applicationInfo.packageName,
7573                        pkg.applicationInfo.uid, "replace pkg");
7574
7575            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7576        }
7577
7578        // Also need to kill any apps that are dependent on the library.
7579        if (clientLibPkgs != null) {
7580            for (int i=0; i<clientLibPkgs.size(); i++) {
7581                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7582                killApplication(clientPkg.applicationInfo.packageName,
7583                        clientPkg.applicationInfo.uid, "update lib");
7584            }
7585        }
7586
7587        // Make sure we're not adding any bogus keyset info
7588        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7589        ksms.assertScannedPackageValid(pkg);
7590
7591        // writer
7592        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7593
7594        boolean createIdmapFailed = false;
7595        synchronized (mPackages) {
7596            // We don't expect installation to fail beyond this point
7597
7598            // Add the new setting to mSettings
7599            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7600            // Add the new setting to mPackages
7601            mPackages.put(pkg.applicationInfo.packageName, pkg);
7602            // Make sure we don't accidentally delete its data.
7603            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7604            while (iter.hasNext()) {
7605                PackageCleanItem item = iter.next();
7606                if (pkgName.equals(item.packageName)) {
7607                    iter.remove();
7608                }
7609            }
7610
7611            // Take care of first install / last update times.
7612            if (currentTime != 0) {
7613                if (pkgSetting.firstInstallTime == 0) {
7614                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7615                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7616                    pkgSetting.lastUpdateTime = currentTime;
7617                }
7618            } else if (pkgSetting.firstInstallTime == 0) {
7619                // We need *something*.  Take time time stamp of the file.
7620                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7621            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7622                if (scanFileTime != pkgSetting.timeStamp) {
7623                    // A package on the system image has changed; consider this
7624                    // to be an update.
7625                    pkgSetting.lastUpdateTime = scanFileTime;
7626                }
7627            }
7628
7629            // Add the package's KeySets to the global KeySetManagerService
7630            ksms.addScannedPackageLPw(pkg);
7631
7632            int N = pkg.providers.size();
7633            StringBuilder r = null;
7634            int i;
7635            for (i=0; i<N; i++) {
7636                PackageParser.Provider p = pkg.providers.get(i);
7637                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7638                        p.info.processName, pkg.applicationInfo.uid);
7639                mProviders.addProvider(p);
7640                p.syncable = p.info.isSyncable;
7641                if (p.info.authority != null) {
7642                    String names[] = p.info.authority.split(";");
7643                    p.info.authority = null;
7644                    for (int j = 0; j < names.length; j++) {
7645                        if (j == 1 && p.syncable) {
7646                            // We only want the first authority for a provider to possibly be
7647                            // syncable, so if we already added this provider using a different
7648                            // authority clear the syncable flag. We copy the provider before
7649                            // changing it because the mProviders object contains a reference
7650                            // to a provider that we don't want to change.
7651                            // Only do this for the second authority since the resulting provider
7652                            // object can be the same for all future authorities for this provider.
7653                            p = new PackageParser.Provider(p);
7654                            p.syncable = false;
7655                        }
7656                        if (!mProvidersByAuthority.containsKey(names[j])) {
7657                            mProvidersByAuthority.put(names[j], p);
7658                            if (p.info.authority == null) {
7659                                p.info.authority = names[j];
7660                            } else {
7661                                p.info.authority = p.info.authority + ";" + names[j];
7662                            }
7663                            if (DEBUG_PACKAGE_SCANNING) {
7664                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7665                                    Log.d(TAG, "Registered content provider: " + names[j]
7666                                            + ", className = " + p.info.name + ", isSyncable = "
7667                                            + p.info.isSyncable);
7668                            }
7669                        } else {
7670                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7671                            Slog.w(TAG, "Skipping provider name " + names[j] +
7672                                    " (in package " + pkg.applicationInfo.packageName +
7673                                    "): name already used by "
7674                                    + ((other != null && other.getComponentName() != null)
7675                                            ? other.getComponentName().getPackageName() : "?"));
7676                        }
7677                    }
7678                }
7679                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7680                    if (r == null) {
7681                        r = new StringBuilder(256);
7682                    } else {
7683                        r.append(' ');
7684                    }
7685                    r.append(p.info.name);
7686                }
7687            }
7688            if (r != null) {
7689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7690            }
7691
7692            N = pkg.services.size();
7693            r = null;
7694            for (i=0; i<N; i++) {
7695                PackageParser.Service s = pkg.services.get(i);
7696                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7697                        s.info.processName, pkg.applicationInfo.uid);
7698                mServices.addService(s);
7699                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7700                    if (r == null) {
7701                        r = new StringBuilder(256);
7702                    } else {
7703                        r.append(' ');
7704                    }
7705                    r.append(s.info.name);
7706                }
7707            }
7708            if (r != null) {
7709                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7710            }
7711
7712            N = pkg.receivers.size();
7713            r = null;
7714            for (i=0; i<N; i++) {
7715                PackageParser.Activity a = pkg.receivers.get(i);
7716                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7717                        a.info.processName, pkg.applicationInfo.uid);
7718                mReceivers.addActivity(a, "receiver");
7719                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7720                    if (r == null) {
7721                        r = new StringBuilder(256);
7722                    } else {
7723                        r.append(' ');
7724                    }
7725                    r.append(a.info.name);
7726                }
7727            }
7728            if (r != null) {
7729                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7730            }
7731
7732            N = pkg.activities.size();
7733            r = null;
7734            for (i=0; i<N; i++) {
7735                PackageParser.Activity a = pkg.activities.get(i);
7736                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7737                        a.info.processName, pkg.applicationInfo.uid);
7738                mActivities.addActivity(a, "activity");
7739                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7740                    if (r == null) {
7741                        r = new StringBuilder(256);
7742                    } else {
7743                        r.append(' ');
7744                    }
7745                    r.append(a.info.name);
7746                }
7747            }
7748            if (r != null) {
7749                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7750            }
7751
7752            N = pkg.permissionGroups.size();
7753            r = null;
7754            for (i=0; i<N; i++) {
7755                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7756                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7757                if (cur == null) {
7758                    mPermissionGroups.put(pg.info.name, pg);
7759                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7760                        if (r == null) {
7761                            r = new StringBuilder(256);
7762                        } else {
7763                            r.append(' ');
7764                        }
7765                        r.append(pg.info.name);
7766                    }
7767                } else {
7768                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7769                            + pg.info.packageName + " ignored: original from "
7770                            + cur.info.packageName);
7771                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7772                        if (r == null) {
7773                            r = new StringBuilder(256);
7774                        } else {
7775                            r.append(' ');
7776                        }
7777                        r.append("DUP:");
7778                        r.append(pg.info.name);
7779                    }
7780                }
7781            }
7782            if (r != null) {
7783                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7784            }
7785
7786            N = pkg.permissions.size();
7787            r = null;
7788            for (i=0; i<N; i++) {
7789                PackageParser.Permission p = pkg.permissions.get(i);
7790
7791                // Assume by default that we did not install this permission into the system.
7792                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7793
7794                // Now that permission groups have a special meaning, we ignore permission
7795                // groups for legacy apps to prevent unexpected behavior. In particular,
7796                // permissions for one app being granted to someone just becuase they happen
7797                // to be in a group defined by another app (before this had no implications).
7798                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7799                    p.group = mPermissionGroups.get(p.info.group);
7800                    // Warn for a permission in an unknown group.
7801                    if (p.info.group != null && p.group == null) {
7802                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7803                                + p.info.packageName + " in an unknown group " + p.info.group);
7804                    }
7805                }
7806
7807                ArrayMap<String, BasePermission> permissionMap =
7808                        p.tree ? mSettings.mPermissionTrees
7809                                : mSettings.mPermissions;
7810                BasePermission bp = permissionMap.get(p.info.name);
7811
7812                // Allow system apps to redefine non-system permissions
7813                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7814                    final boolean currentOwnerIsSystem = (bp.perm != null
7815                            && isSystemApp(bp.perm.owner));
7816                    if (isSystemApp(p.owner)) {
7817                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7818                            // It's a built-in permission and no owner, take ownership now
7819                            bp.packageSetting = pkgSetting;
7820                            bp.perm = p;
7821                            bp.uid = pkg.applicationInfo.uid;
7822                            bp.sourcePackage = p.info.packageName;
7823                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7824                        } else if (!currentOwnerIsSystem) {
7825                            String msg = "New decl " + p.owner + " of permission  "
7826                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7827                            reportSettingsProblem(Log.WARN, msg);
7828                            bp = null;
7829                        }
7830                    }
7831                }
7832
7833                if (bp == null) {
7834                    bp = new BasePermission(p.info.name, p.info.packageName,
7835                            BasePermission.TYPE_NORMAL);
7836                    permissionMap.put(p.info.name, bp);
7837                }
7838
7839                if (bp.perm == null) {
7840                    if (bp.sourcePackage == null
7841                            || bp.sourcePackage.equals(p.info.packageName)) {
7842                        BasePermission tree = findPermissionTreeLP(p.info.name);
7843                        if (tree == null
7844                                || tree.sourcePackage.equals(p.info.packageName)) {
7845                            bp.packageSetting = pkgSetting;
7846                            bp.perm = p;
7847                            bp.uid = pkg.applicationInfo.uid;
7848                            bp.sourcePackage = p.info.packageName;
7849                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7850                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7851                                if (r == null) {
7852                                    r = new StringBuilder(256);
7853                                } else {
7854                                    r.append(' ');
7855                                }
7856                                r.append(p.info.name);
7857                            }
7858                        } else {
7859                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7860                                    + p.info.packageName + " ignored: base tree "
7861                                    + tree.name + " is from package "
7862                                    + tree.sourcePackage);
7863                        }
7864                    } else {
7865                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7866                                + p.info.packageName + " ignored: original from "
7867                                + bp.sourcePackage);
7868                    }
7869                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7870                    if (r == null) {
7871                        r = new StringBuilder(256);
7872                    } else {
7873                        r.append(' ');
7874                    }
7875                    r.append("DUP:");
7876                    r.append(p.info.name);
7877                }
7878                if (bp.perm == p) {
7879                    bp.protectionLevel = p.info.protectionLevel;
7880                }
7881            }
7882
7883            if (r != null) {
7884                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7885            }
7886
7887            N = pkg.instrumentation.size();
7888            r = null;
7889            for (i=0; i<N; i++) {
7890                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7891                a.info.packageName = pkg.applicationInfo.packageName;
7892                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7893                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7894                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7895                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7896                a.info.dataDir = pkg.applicationInfo.dataDir;
7897                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7898                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7899
7900                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7901                // need other information about the application, like the ABI and what not ?
7902                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7903                mInstrumentation.put(a.getComponentName(), a);
7904                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7905                    if (r == null) {
7906                        r = new StringBuilder(256);
7907                    } else {
7908                        r.append(' ');
7909                    }
7910                    r.append(a.info.name);
7911                }
7912            }
7913            if (r != null) {
7914                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7915            }
7916
7917            if (pkg.protectedBroadcasts != null) {
7918                N = pkg.protectedBroadcasts.size();
7919                for (i=0; i<N; i++) {
7920                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7921                }
7922            }
7923
7924            pkgSetting.setTimeStamp(scanFileTime);
7925
7926            // Create idmap files for pairs of (packages, overlay packages).
7927            // Note: "android", ie framework-res.apk, is handled by native layers.
7928            if (pkg.mOverlayTarget != null) {
7929                // This is an overlay package.
7930                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7931                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7932                        mOverlays.put(pkg.mOverlayTarget,
7933                                new ArrayMap<String, PackageParser.Package>());
7934                    }
7935                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7936                    map.put(pkg.packageName, pkg);
7937                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7938                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7939                        createIdmapFailed = true;
7940                    }
7941                }
7942            } else if (mOverlays.containsKey(pkg.packageName) &&
7943                    !pkg.packageName.equals("android")) {
7944                // This is a regular package, with one or more known overlay packages.
7945                createIdmapsForPackageLI(pkg);
7946            }
7947        }
7948
7949        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7950
7951        if (createIdmapFailed) {
7952            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7953                    "scanPackageLI failed to createIdmap");
7954        }
7955        return pkg;
7956    }
7957
7958    /**
7959     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7960     * is derived purely on the basis of the contents of {@code scanFile} and
7961     * {@code cpuAbiOverride}.
7962     *
7963     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7964     */
7965    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7966                                 String cpuAbiOverride, boolean extractLibs)
7967            throws PackageManagerException {
7968        // TODO: We can probably be smarter about this stuff. For installed apps,
7969        // we can calculate this information at install time once and for all. For
7970        // system apps, we can probably assume that this information doesn't change
7971        // after the first boot scan. As things stand, we do lots of unnecessary work.
7972
7973        // Give ourselves some initial paths; we'll come back for another
7974        // pass once we've determined ABI below.
7975        setNativeLibraryPaths(pkg);
7976
7977        // We would never need to extract libs for forward-locked and external packages,
7978        // since the container service will do it for us. We shouldn't attempt to
7979        // extract libs from system app when it was not updated.
7980        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7981                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7982            extractLibs = false;
7983        }
7984
7985        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7986        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7987
7988        NativeLibraryHelper.Handle handle = null;
7989        try {
7990            handle = NativeLibraryHelper.Handle.create(pkg);
7991            // TODO(multiArch): This can be null for apps that didn't go through the
7992            // usual installation process. We can calculate it again, like we
7993            // do during install time.
7994            //
7995            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7996            // unnecessary.
7997            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7998
7999            // Null out the abis so that they can be recalculated.
8000            pkg.applicationInfo.primaryCpuAbi = null;
8001            pkg.applicationInfo.secondaryCpuAbi = null;
8002            if (isMultiArch(pkg.applicationInfo)) {
8003                // Warn if we've set an abiOverride for multi-lib packages..
8004                // By definition, we need to copy both 32 and 64 bit libraries for
8005                // such packages.
8006                if (pkg.cpuAbiOverride != null
8007                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8008                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8009                }
8010
8011                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8012                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8013                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8014                    if (extractLibs) {
8015                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8016                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8017                                useIsaSpecificSubdirs);
8018                    } else {
8019                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8020                    }
8021                }
8022
8023                maybeThrowExceptionForMultiArchCopy(
8024                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8025
8026                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8027                    if (extractLibs) {
8028                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8029                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8030                                useIsaSpecificSubdirs);
8031                    } else {
8032                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8033                    }
8034                }
8035
8036                maybeThrowExceptionForMultiArchCopy(
8037                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8038
8039                if (abi64 >= 0) {
8040                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8041                }
8042
8043                if (abi32 >= 0) {
8044                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8045                    if (abi64 >= 0) {
8046                        pkg.applicationInfo.secondaryCpuAbi = abi;
8047                    } else {
8048                        pkg.applicationInfo.primaryCpuAbi = abi;
8049                    }
8050                }
8051                if (cpuAbiOverride != null &&
8052                        cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) {
8053                    pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8054                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8055                }
8056            } else {
8057                String[] abiList = (cpuAbiOverride != null) ?
8058                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8059
8060                // Enable gross and lame hacks for apps that are built with old
8061                // SDK tools. We must scan their APKs for renderscript bitcode and
8062                // not launch them if it's present. Don't bother checking on devices
8063                // that don't have 64 bit support.
8064                boolean needsRenderScriptOverride = false;
8065                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8066                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8067                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8068                    needsRenderScriptOverride = true;
8069                }
8070
8071                final int copyRet;
8072                if (extractLibs) {
8073                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8074                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8075                } else {
8076                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8077                }
8078
8079                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8080                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8081                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8082                }
8083
8084                if (copyRet >= 0) {
8085                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8086                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8087                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8088                } else if (needsRenderScriptOverride) {
8089                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8090                }
8091            }
8092        } catch (IOException ioe) {
8093            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8094        } finally {
8095            IoUtils.closeQuietly(handle);
8096        }
8097
8098        // Now that we've calculated the ABIs and determined if it's an internal app,
8099        // we will go ahead and populate the nativeLibraryPath.
8100        setNativeLibraryPaths(pkg);
8101    }
8102
8103    /**
8104     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8105     * i.e, so that all packages can be run inside a single process if required.
8106     *
8107     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8108     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8109     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8110     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8111     * updating a package that belongs to a shared user.
8112     *
8113     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8114     * adds unnecessary complexity.
8115     */
8116    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8117            PackageParser.Package scannedPackage, boolean bootComplete) {
8118        String requiredInstructionSet = null;
8119        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8120            requiredInstructionSet = VMRuntime.getInstructionSet(
8121                     scannedPackage.applicationInfo.primaryCpuAbi);
8122        }
8123
8124        PackageSetting requirer = null;
8125        for (PackageSetting ps : packagesForUser) {
8126            // If packagesForUser contains scannedPackage, we skip it. This will happen
8127            // when scannedPackage is an update of an existing package. Without this check,
8128            // we will never be able to change the ABI of any package belonging to a shared
8129            // user, even if it's compatible with other packages.
8130            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8131                if (ps.primaryCpuAbiString == null) {
8132                    continue;
8133                }
8134
8135                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8136                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8137                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8138                    // this but there's not much we can do.
8139                    String errorMessage = "Instruction set mismatch, "
8140                            + ((requirer == null) ? "[caller]" : requirer)
8141                            + " requires " + requiredInstructionSet + " whereas " + ps
8142                            + " requires " + instructionSet;
8143                    Slog.w(TAG, errorMessage);
8144                }
8145
8146                if (requiredInstructionSet == null) {
8147                    requiredInstructionSet = instructionSet;
8148                    requirer = ps;
8149                }
8150            }
8151        }
8152
8153        if (requiredInstructionSet != null) {
8154            String adjustedAbi;
8155            if (requirer != null) {
8156                // requirer != null implies that either scannedPackage was null or that scannedPackage
8157                // did not require an ABI, in which case we have to adjust scannedPackage to match
8158                // the ABI of the set (which is the same as requirer's ABI)
8159                adjustedAbi = requirer.primaryCpuAbiString;
8160                if (scannedPackage != null) {
8161                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8162                }
8163            } else {
8164                // requirer == null implies that we're updating all ABIs in the set to
8165                // match scannedPackage.
8166                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8167            }
8168
8169            for (PackageSetting ps : packagesForUser) {
8170                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8171                    if (ps.primaryCpuAbiString != null) {
8172                        continue;
8173                    }
8174
8175                    ps.primaryCpuAbiString = adjustedAbi;
8176                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8177                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8178                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8179                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8180                                + " (requirer="
8181                                + (requirer == null ? "null" : requirer.pkg.packageName)
8182                                + ", scannedPackage="
8183                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8184                                + ")");
8185                        try {
8186                            mInstaller.rmdex(ps.codePathString,
8187                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8188                        } catch (InstallerException ignored) {
8189                        }
8190                    }
8191                }
8192            }
8193        }
8194    }
8195
8196    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8197        synchronized (mPackages) {
8198            mResolverReplaced = true;
8199            // Set up information for custom user intent resolution activity.
8200            mResolveActivity.applicationInfo = pkg.applicationInfo;
8201            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8202            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8203            mResolveActivity.processName = pkg.applicationInfo.packageName;
8204            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8205            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8206                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8207            mResolveActivity.theme = 0;
8208            mResolveActivity.exported = true;
8209            mResolveActivity.enabled = true;
8210            mResolveInfo.activityInfo = mResolveActivity;
8211            mResolveInfo.priority = 0;
8212            mResolveInfo.preferredOrder = 0;
8213            mResolveInfo.match = 0;
8214            mResolveComponentName = mCustomResolverComponentName;
8215            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8216                    mResolveComponentName);
8217        }
8218    }
8219
8220    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8221        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8222
8223        // Set up information for ephemeral installer activity
8224        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8225        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8226        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8227        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8228        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8229        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8230                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8231        mEphemeralInstallerActivity.theme = 0;
8232        mEphemeralInstallerActivity.exported = true;
8233        mEphemeralInstallerActivity.enabled = true;
8234        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8235        mEphemeralInstallerInfo.priority = 0;
8236        mEphemeralInstallerInfo.preferredOrder = 0;
8237        mEphemeralInstallerInfo.match = 0;
8238
8239        if (DEBUG_EPHEMERAL) {
8240            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8241        }
8242    }
8243
8244    private static String calculateBundledApkRoot(final String codePathString) {
8245        final File codePath = new File(codePathString);
8246        final File codeRoot;
8247        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8248            codeRoot = Environment.getRootDirectory();
8249        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8250            codeRoot = Environment.getOemDirectory();
8251        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8252            codeRoot = Environment.getVendorDirectory();
8253        } else {
8254            // Unrecognized code path; take its top real segment as the apk root:
8255            // e.g. /something/app/blah.apk => /something
8256            try {
8257                File f = codePath.getCanonicalFile();
8258                File parent = f.getParentFile();    // non-null because codePath is a file
8259                File tmp;
8260                while ((tmp = parent.getParentFile()) != null) {
8261                    f = parent;
8262                    parent = tmp;
8263                }
8264                codeRoot = f;
8265                Slog.w(TAG, "Unrecognized code path "
8266                        + codePath + " - using " + codeRoot);
8267            } catch (IOException e) {
8268                // Can't canonicalize the code path -- shenanigans?
8269                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8270                return Environment.getRootDirectory().getPath();
8271            }
8272        }
8273        return codeRoot.getPath();
8274    }
8275
8276    /**
8277     * Derive and set the location of native libraries for the given package,
8278     * which varies depending on where and how the package was installed.
8279     */
8280    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8281        final ApplicationInfo info = pkg.applicationInfo;
8282        final String codePath = pkg.codePath;
8283        final File codeFile = new File(codePath);
8284        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8285        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8286
8287        info.nativeLibraryRootDir = null;
8288        info.nativeLibraryRootRequiresIsa = false;
8289        info.nativeLibraryDir = null;
8290        info.secondaryNativeLibraryDir = null;
8291
8292        if (isApkFile(codeFile)) {
8293            // Monolithic install
8294            if (bundledApp) {
8295                // If "/system/lib64/apkname" exists, assume that is the per-package
8296                // native library directory to use; otherwise use "/system/lib/apkname".
8297                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8298                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8299                        getPrimaryInstructionSet(info));
8300
8301                // This is a bundled system app so choose the path based on the ABI.
8302                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8303                // is just the default path.
8304                final String apkName = deriveCodePathName(codePath);
8305                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8306                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8307                        apkName).getAbsolutePath();
8308
8309                if (info.secondaryCpuAbi != null) {
8310                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8311                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8312                            secondaryLibDir, apkName).getAbsolutePath();
8313                }
8314            } else if (asecApp) {
8315                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8316                        .getAbsolutePath();
8317            } else {
8318                final String apkName = deriveCodePathName(codePath);
8319                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8320                        .getAbsolutePath();
8321            }
8322
8323            info.nativeLibraryRootRequiresIsa = false;
8324            info.nativeLibraryDir = info.nativeLibraryRootDir;
8325        } else {
8326            // Cluster install
8327            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8328            info.nativeLibraryRootRequiresIsa = true;
8329
8330            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8331                    getPrimaryInstructionSet(info)).getAbsolutePath();
8332
8333            if (info.secondaryCpuAbi != null) {
8334                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8335                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8336            }
8337        }
8338    }
8339
8340    /**
8341     * Calculate the abis and roots for a bundled app. These can uniquely
8342     * be determined from the contents of the system partition, i.e whether
8343     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8344     * of this information, and instead assume that the system was built
8345     * sensibly.
8346     */
8347    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8348                                           PackageSetting pkgSetting) {
8349        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8350
8351        // If "/system/lib64/apkname" exists, assume that is the per-package
8352        // native library directory to use; otherwise use "/system/lib/apkname".
8353        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8354        setBundledAppAbi(pkg, apkRoot, apkName);
8355        // pkgSetting might be null during rescan following uninstall of updates
8356        // to a bundled app, so accommodate that possibility.  The settings in
8357        // that case will be established later from the parsed package.
8358        //
8359        // If the settings aren't null, sync them up with what we've just derived.
8360        // note that apkRoot isn't stored in the package settings.
8361        if (pkgSetting != null) {
8362            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8363            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8364        }
8365    }
8366
8367    /**
8368     * Deduces the ABI of a bundled app and sets the relevant fields on the
8369     * parsed pkg object.
8370     *
8371     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8372     *        under which system libraries are installed.
8373     * @param apkName the name of the installed package.
8374     */
8375    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8376        final File codeFile = new File(pkg.codePath);
8377
8378        final boolean has64BitLibs;
8379        final boolean has32BitLibs;
8380        if (isApkFile(codeFile)) {
8381            // Monolithic install
8382            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8383            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8384        } else {
8385            // Cluster install
8386            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8387            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8388                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8389                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8390                has64BitLibs = (new File(rootDir, isa)).exists();
8391            } else {
8392                has64BitLibs = false;
8393            }
8394            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8395                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8396                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8397                has32BitLibs = (new File(rootDir, isa)).exists();
8398            } else {
8399                has32BitLibs = false;
8400            }
8401        }
8402
8403        if (has64BitLibs && !has32BitLibs) {
8404            // The package has 64 bit libs, but not 32 bit libs. Its primary
8405            // ABI should be 64 bit. We can safely assume here that the bundled
8406            // native libraries correspond to the most preferred ABI in the list.
8407
8408            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8409            pkg.applicationInfo.secondaryCpuAbi = null;
8410        } else if (has32BitLibs && !has64BitLibs) {
8411            // The package has 32 bit libs but not 64 bit libs. Its primary
8412            // ABI should be 32 bit.
8413
8414            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8415            pkg.applicationInfo.secondaryCpuAbi = null;
8416        } else if (has32BitLibs && has64BitLibs) {
8417            // The application has both 64 and 32 bit bundled libraries. We check
8418            // here that the app declares multiArch support, and warn if it doesn't.
8419            //
8420            // We will be lenient here and record both ABIs. The primary will be the
8421            // ABI that's higher on the list, i.e, a device that's configured to prefer
8422            // 64 bit apps will see a 64 bit primary ABI,
8423
8424            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8425                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8426            }
8427
8428            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8429                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8430                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8431            } else {
8432                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8433                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8434            }
8435        } else {
8436            pkg.applicationInfo.primaryCpuAbi = null;
8437            pkg.applicationInfo.secondaryCpuAbi = null;
8438        }
8439    }
8440
8441    private void killApplication(String pkgName, int appId, String reason) {
8442        // Request the ActivityManager to kill the process(only for existing packages)
8443        // so that we do not end up in a confused state while the user is still using the older
8444        // version of the application while the new one gets installed.
8445        IActivityManager am = ActivityManagerNative.getDefault();
8446        if (am != null) {
8447            try {
8448                am.killApplicationWithAppId(pkgName, appId, reason);
8449            } catch (RemoteException e) {
8450            }
8451        }
8452    }
8453
8454    void removePackageLI(PackageSetting ps, boolean chatty) {
8455        if (DEBUG_INSTALL) {
8456            if (chatty)
8457                Log.d(TAG, "Removing package " + ps.name);
8458        }
8459
8460        // writer
8461        synchronized (mPackages) {
8462            mPackages.remove(ps.name);
8463            final PackageParser.Package pkg = ps.pkg;
8464            if (pkg != null) {
8465                cleanPackageDataStructuresLILPw(pkg, chatty);
8466            }
8467        }
8468    }
8469
8470    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8471        if (DEBUG_INSTALL) {
8472            if (chatty)
8473                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8474        }
8475
8476        // writer
8477        synchronized (mPackages) {
8478            mPackages.remove(pkg.applicationInfo.packageName);
8479            cleanPackageDataStructuresLILPw(pkg, chatty);
8480        }
8481    }
8482
8483    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8484        int N = pkg.providers.size();
8485        StringBuilder r = null;
8486        int i;
8487        for (i=0; i<N; i++) {
8488            PackageParser.Provider p = pkg.providers.get(i);
8489            mProviders.removeProvider(p);
8490            if (p.info.authority == null) {
8491
8492                /* There was another ContentProvider with this authority when
8493                 * this app was installed so this authority is null,
8494                 * Ignore it as we don't have to unregister the provider.
8495                 */
8496                continue;
8497            }
8498            String names[] = p.info.authority.split(";");
8499            for (int j = 0; j < names.length; j++) {
8500                if (mProvidersByAuthority.get(names[j]) == p) {
8501                    mProvidersByAuthority.remove(names[j]);
8502                    if (DEBUG_REMOVE) {
8503                        if (chatty)
8504                            Log.d(TAG, "Unregistered content provider: " + names[j]
8505                                    + ", className = " + p.info.name + ", isSyncable = "
8506                                    + p.info.isSyncable);
8507                    }
8508                }
8509            }
8510            if (DEBUG_REMOVE && chatty) {
8511                if (r == null) {
8512                    r = new StringBuilder(256);
8513                } else {
8514                    r.append(' ');
8515                }
8516                r.append(p.info.name);
8517            }
8518        }
8519        if (r != null) {
8520            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8521        }
8522
8523        N = pkg.services.size();
8524        r = null;
8525        for (i=0; i<N; i++) {
8526            PackageParser.Service s = pkg.services.get(i);
8527            mServices.removeService(s);
8528            if (chatty) {
8529                if (r == null) {
8530                    r = new StringBuilder(256);
8531                } else {
8532                    r.append(' ');
8533                }
8534                r.append(s.info.name);
8535            }
8536        }
8537        if (r != null) {
8538            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8539        }
8540
8541        N = pkg.receivers.size();
8542        r = null;
8543        for (i=0; i<N; i++) {
8544            PackageParser.Activity a = pkg.receivers.get(i);
8545            mReceivers.removeActivity(a, "receiver");
8546            if (DEBUG_REMOVE && chatty) {
8547                if (r == null) {
8548                    r = new StringBuilder(256);
8549                } else {
8550                    r.append(' ');
8551                }
8552                r.append(a.info.name);
8553            }
8554        }
8555        if (r != null) {
8556            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8557        }
8558
8559        N = pkg.activities.size();
8560        r = null;
8561        for (i=0; i<N; i++) {
8562            PackageParser.Activity a = pkg.activities.get(i);
8563            mActivities.removeActivity(a, "activity");
8564            if (DEBUG_REMOVE && chatty) {
8565                if (r == null) {
8566                    r = new StringBuilder(256);
8567                } else {
8568                    r.append(' ');
8569                }
8570                r.append(a.info.name);
8571            }
8572        }
8573        if (r != null) {
8574            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8575        }
8576
8577        N = pkg.permissions.size();
8578        r = null;
8579        for (i=0; i<N; i++) {
8580            PackageParser.Permission p = pkg.permissions.get(i);
8581            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8582            if (bp == null) {
8583                bp = mSettings.mPermissionTrees.get(p.info.name);
8584            }
8585            if (bp != null && bp.perm == p) {
8586                bp.perm = null;
8587                if (DEBUG_REMOVE && chatty) {
8588                    if (r == null) {
8589                        r = new StringBuilder(256);
8590                    } else {
8591                        r.append(' ');
8592                    }
8593                    r.append(p.info.name);
8594                }
8595            }
8596            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8597                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8598                if (appOpPkgs != null) {
8599                    appOpPkgs.remove(pkg.packageName);
8600                }
8601            }
8602        }
8603        if (r != null) {
8604            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8605        }
8606
8607        N = pkg.requestedPermissions.size();
8608        r = null;
8609        for (i=0; i<N; i++) {
8610            String perm = pkg.requestedPermissions.get(i);
8611            BasePermission bp = mSettings.mPermissions.get(perm);
8612            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8613                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8614                if (appOpPkgs != null) {
8615                    appOpPkgs.remove(pkg.packageName);
8616                    if (appOpPkgs.isEmpty()) {
8617                        mAppOpPermissionPackages.remove(perm);
8618                    }
8619                }
8620            }
8621        }
8622        if (r != null) {
8623            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8624        }
8625
8626        N = pkg.instrumentation.size();
8627        r = null;
8628        for (i=0; i<N; i++) {
8629            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8630            mInstrumentation.remove(a.getComponentName());
8631            if (DEBUG_REMOVE && chatty) {
8632                if (r == null) {
8633                    r = new StringBuilder(256);
8634                } else {
8635                    r.append(' ');
8636                }
8637                r.append(a.info.name);
8638            }
8639        }
8640        if (r != null) {
8641            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8642        }
8643
8644        r = null;
8645        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8646            // Only system apps can hold shared libraries.
8647            if (pkg.libraryNames != null) {
8648                for (i=0; i<pkg.libraryNames.size(); i++) {
8649                    String name = pkg.libraryNames.get(i);
8650                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8651                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8652                        mSharedLibraries.remove(name);
8653                        if (DEBUG_REMOVE && chatty) {
8654                            if (r == null) {
8655                                r = new StringBuilder(256);
8656                            } else {
8657                                r.append(' ');
8658                            }
8659                            r.append(name);
8660                        }
8661                    }
8662                }
8663            }
8664        }
8665        if (r != null) {
8666            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8667        }
8668    }
8669
8670    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8671        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8672            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8673                return true;
8674            }
8675        }
8676        return false;
8677    }
8678
8679    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8680    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8681    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8682
8683    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8684            int flags) {
8685        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8686        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8687    }
8688
8689    private void updatePermissionsLPw(String changingPkg,
8690            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8691        // Make sure there are no dangling permission trees.
8692        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8693        while (it.hasNext()) {
8694            final BasePermission bp = it.next();
8695            if (bp.packageSetting == null) {
8696                // We may not yet have parsed the package, so just see if
8697                // we still know about its settings.
8698                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8699            }
8700            if (bp.packageSetting == null) {
8701                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8702                        + " from package " + bp.sourcePackage);
8703                it.remove();
8704            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8705                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8706                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8707                            + " from package " + bp.sourcePackage);
8708                    flags |= UPDATE_PERMISSIONS_ALL;
8709                    it.remove();
8710                }
8711            }
8712        }
8713
8714        // Make sure all dynamic permissions have been assigned to a package,
8715        // and make sure there are no dangling permissions.
8716        it = mSettings.mPermissions.values().iterator();
8717        while (it.hasNext()) {
8718            final BasePermission bp = it.next();
8719            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8720                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8721                        + bp.name + " pkg=" + bp.sourcePackage
8722                        + " info=" + bp.pendingInfo);
8723                if (bp.packageSetting == null && bp.pendingInfo != null) {
8724                    final BasePermission tree = findPermissionTreeLP(bp.name);
8725                    if (tree != null && tree.perm != null) {
8726                        bp.packageSetting = tree.packageSetting;
8727                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8728                                new PermissionInfo(bp.pendingInfo));
8729                        bp.perm.info.packageName = tree.perm.info.packageName;
8730                        bp.perm.info.name = bp.name;
8731                        bp.uid = tree.uid;
8732                    }
8733                }
8734            }
8735            if (bp.packageSetting == null) {
8736                // We may not yet have parsed the package, so just see if
8737                // we still know about its settings.
8738                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8739            }
8740            if (bp.packageSetting == null) {
8741                Slog.w(TAG, "Removing dangling permission: " + bp.name
8742                        + " from package " + bp.sourcePackage);
8743                it.remove();
8744            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8745                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8746                    Slog.i(TAG, "Removing old permission: " + bp.name
8747                            + " from package " + bp.sourcePackage);
8748                    flags |= UPDATE_PERMISSIONS_ALL;
8749                    it.remove();
8750                }
8751            }
8752        }
8753
8754        // Now update the permissions for all packages, in particular
8755        // replace the granted permissions of the system packages.
8756        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8757            for (PackageParser.Package pkg : mPackages.values()) {
8758                if (pkg != pkgInfo) {
8759                    // Only replace for packages on requested volume
8760                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8761                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8762                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8763                    grantPermissionsLPw(pkg, replace, changingPkg);
8764                }
8765            }
8766        }
8767
8768        if (pkgInfo != null) {
8769            // Only replace for packages on requested volume
8770            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8771            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8772                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8773            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8774        }
8775    }
8776
8777    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8778            String packageOfInterest) {
8779        // IMPORTANT: There are two types of permissions: install and runtime.
8780        // Install time permissions are granted when the app is installed to
8781        // all device users and users added in the future. Runtime permissions
8782        // are granted at runtime explicitly to specific users. Normal and signature
8783        // protected permissions are install time permissions. Dangerous permissions
8784        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8785        // otherwise they are runtime permissions. This function does not manage
8786        // runtime permissions except for the case an app targeting Lollipop MR1
8787        // being upgraded to target a newer SDK, in which case dangerous permissions
8788        // are transformed from install time to runtime ones.
8789
8790        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8791        if (ps == null) {
8792            return;
8793        }
8794
8795        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8796
8797        PermissionsState permissionsState = ps.getPermissionsState();
8798        PermissionsState origPermissions = permissionsState;
8799
8800        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8801
8802        boolean runtimePermissionsRevoked = false;
8803        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8804
8805        boolean changedInstallPermission = false;
8806
8807        if (replace) {
8808            ps.installPermissionsFixed = false;
8809            if (!ps.isSharedUser()) {
8810                origPermissions = new PermissionsState(permissionsState);
8811                permissionsState.reset();
8812            } else {
8813                // We need to know only about runtime permission changes since the
8814                // calling code always writes the install permissions state but
8815                // the runtime ones are written only if changed. The only cases of
8816                // changed runtime permissions here are promotion of an install to
8817                // runtime and revocation of a runtime from a shared user.
8818                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8819                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8820                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8821                    runtimePermissionsRevoked = true;
8822                }
8823            }
8824        }
8825
8826        permissionsState.setGlobalGids(mGlobalGids);
8827
8828        final int N = pkg.requestedPermissions.size();
8829        for (int i=0; i<N; i++) {
8830            final String name = pkg.requestedPermissions.get(i);
8831            final BasePermission bp = mSettings.mPermissions.get(name);
8832
8833            if (DEBUG_INSTALL) {
8834                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8835            }
8836
8837            if (bp == null || bp.packageSetting == null) {
8838                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8839                    Slog.w(TAG, "Unknown permission " + name
8840                            + " in package " + pkg.packageName);
8841                }
8842                continue;
8843            }
8844
8845            final String perm = bp.name;
8846            boolean allowedSig = false;
8847            int grant = GRANT_DENIED;
8848
8849            // Keep track of app op permissions.
8850            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8851                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8852                if (pkgs == null) {
8853                    pkgs = new ArraySet<>();
8854                    mAppOpPermissionPackages.put(bp.name, pkgs);
8855                }
8856                pkgs.add(pkg.packageName);
8857            }
8858
8859            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8860            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8861                    >= Build.VERSION_CODES.M;
8862            switch (level) {
8863                case PermissionInfo.PROTECTION_NORMAL: {
8864                    // For all apps normal permissions are install time ones.
8865                    grant = GRANT_INSTALL;
8866                } break;
8867
8868                case PermissionInfo.PROTECTION_DANGEROUS: {
8869                    // If a permission review is required for legacy apps we represent
8870                    // their permissions as always granted runtime ones since we need
8871                    // to keep the review required permission flag per user while an
8872                    // install permission's state is shared across all users.
8873                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8874                        // For legacy apps dangerous permissions are install time ones.
8875                        grant = GRANT_INSTALL;
8876                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8877                        // For legacy apps that became modern, install becomes runtime.
8878                        grant = GRANT_UPGRADE;
8879                    } else if (mPromoteSystemApps
8880                            && isSystemApp(ps)
8881                            && mExistingSystemPackages.contains(ps.name)) {
8882                        // For legacy system apps, install becomes runtime.
8883                        // We cannot check hasInstallPermission() for system apps since those
8884                        // permissions were granted implicitly and not persisted pre-M.
8885                        grant = GRANT_UPGRADE;
8886                    } else {
8887                        // For modern apps keep runtime permissions unchanged.
8888                        grant = GRANT_RUNTIME;
8889                    }
8890                } break;
8891
8892                case PermissionInfo.PROTECTION_SIGNATURE: {
8893                    // For all apps signature permissions are install time ones.
8894                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8895                    if (allowedSig) {
8896                        grant = GRANT_INSTALL;
8897                    }
8898                } break;
8899            }
8900
8901            if (DEBUG_INSTALL) {
8902                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8903            }
8904
8905            if (grant != GRANT_DENIED) {
8906                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8907                    // If this is an existing, non-system package, then
8908                    // we can't add any new permissions to it.
8909                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8910                        // Except...  if this is a permission that was added
8911                        // to the platform (note: need to only do this when
8912                        // updating the platform).
8913                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8914                            grant = GRANT_DENIED;
8915                        }
8916                    }
8917                }
8918
8919                switch (grant) {
8920                    case GRANT_INSTALL: {
8921                        // Revoke this as runtime permission to handle the case of
8922                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8923                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8924                            if (origPermissions.getRuntimePermissionState(
8925                                    bp.name, userId) != null) {
8926                                // Revoke the runtime permission and clear the flags.
8927                                origPermissions.revokeRuntimePermission(bp, userId);
8928                                origPermissions.updatePermissionFlags(bp, userId,
8929                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8930                                // If we revoked a permission permission, we have to write.
8931                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8932                                        changedRuntimePermissionUserIds, userId);
8933                            }
8934                        }
8935                        // Grant an install permission.
8936                        if (permissionsState.grantInstallPermission(bp) !=
8937                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8938                            changedInstallPermission = true;
8939                        }
8940                    } break;
8941
8942                    case GRANT_RUNTIME: {
8943                        // Grant previously granted runtime permissions.
8944                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8945                            PermissionState permissionState = origPermissions
8946                                    .getRuntimePermissionState(bp.name, userId);
8947                            int flags = permissionState != null
8948                                    ? permissionState.getFlags() : 0;
8949                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8950                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8951                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8952                                    // If we cannot put the permission as it was, we have to write.
8953                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8954                                            changedRuntimePermissionUserIds, userId);
8955                                }
8956                                // If the app supports runtime permissions no need for a review.
8957                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8958                                        && appSupportsRuntimePermissions
8959                                        && (flags & PackageManager
8960                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8961                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8962                                    // Since we changed the flags, we have to write.
8963                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8964                                            changedRuntimePermissionUserIds, userId);
8965                                }
8966                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8967                                    && !appSupportsRuntimePermissions) {
8968                                // For legacy apps that need a permission review, every new
8969                                // runtime permission is granted but it is pending a review.
8970                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8971                                    permissionsState.grantRuntimePermission(bp, userId);
8972                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8973                                    // We changed the permission and flags, hence have to write.
8974                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8975                                            changedRuntimePermissionUserIds, userId);
8976                                }
8977                            }
8978                            // Propagate the permission flags.
8979                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8980                        }
8981                    } break;
8982
8983                    case GRANT_UPGRADE: {
8984                        // Grant runtime permissions for a previously held install permission.
8985                        PermissionState permissionState = origPermissions
8986                                .getInstallPermissionState(bp.name);
8987                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8988
8989                        if (origPermissions.revokeInstallPermission(bp)
8990                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8991                            // We will be transferring the permission flags, so clear them.
8992                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8993                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8994                            changedInstallPermission = true;
8995                        }
8996
8997                        // If the permission is not to be promoted to runtime we ignore it and
8998                        // also its other flags as they are not applicable to install permissions.
8999                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9000                            for (int userId : currentUserIds) {
9001                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9002                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9003                                    // Transfer the permission flags.
9004                                    permissionsState.updatePermissionFlags(bp, userId,
9005                                            flags, flags);
9006                                    // If we granted the permission, we have to write.
9007                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9008                                            changedRuntimePermissionUserIds, userId);
9009                                }
9010                            }
9011                        }
9012                    } break;
9013
9014                    default: {
9015                        if (packageOfInterest == null
9016                                || packageOfInterest.equals(pkg.packageName)) {
9017                            Slog.w(TAG, "Not granting permission " + perm
9018                                    + " to package " + pkg.packageName
9019                                    + " because it was previously installed without");
9020                        }
9021                    } break;
9022                }
9023            } else {
9024                if (permissionsState.revokeInstallPermission(bp) !=
9025                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9026                    // Also drop the permission flags.
9027                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9028                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9029                    changedInstallPermission = true;
9030                    Slog.i(TAG, "Un-granting permission " + perm
9031                            + " from package " + pkg.packageName
9032                            + " (protectionLevel=" + bp.protectionLevel
9033                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9034                            + ")");
9035                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9036                    // Don't print warning for app op permissions, since it is fine for them
9037                    // not to be granted, there is a UI for the user to decide.
9038                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9039                        Slog.w(TAG, "Not granting permission " + perm
9040                                + " to package " + pkg.packageName
9041                                + " (protectionLevel=" + bp.protectionLevel
9042                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9043                                + ")");
9044                    }
9045                }
9046            }
9047        }
9048
9049        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9050                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9051            // This is the first that we have heard about this package, so the
9052            // permissions we have now selected are fixed until explicitly
9053            // changed.
9054            ps.installPermissionsFixed = true;
9055        }
9056
9057        // Persist the runtime permissions state for users with changes. If permissions
9058        // were revoked because no app in the shared user declares them we have to
9059        // write synchronously to avoid losing runtime permissions state.
9060        for (int userId : changedRuntimePermissionUserIds) {
9061            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9062        }
9063
9064        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9065    }
9066
9067    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9068        boolean allowed = false;
9069        final int NP = PackageParser.NEW_PERMISSIONS.length;
9070        for (int ip=0; ip<NP; ip++) {
9071            final PackageParser.NewPermissionInfo npi
9072                    = PackageParser.NEW_PERMISSIONS[ip];
9073            if (npi.name.equals(perm)
9074                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9075                allowed = true;
9076                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9077                        + pkg.packageName);
9078                break;
9079            }
9080        }
9081        return allowed;
9082    }
9083
9084    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9085            BasePermission bp, PermissionsState origPermissions) {
9086        boolean allowed;
9087        allowed = (compareSignatures(
9088                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9089                        == PackageManager.SIGNATURE_MATCH)
9090                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9091                        == PackageManager.SIGNATURE_MATCH);
9092        if (!allowed && (bp.protectionLevel
9093                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9094            if (isSystemApp(pkg)) {
9095                // For updated system applications, a system permission
9096                // is granted only if it had been defined by the original application.
9097                if (pkg.isUpdatedSystemApp()) {
9098                    final PackageSetting sysPs = mSettings
9099                            .getDisabledSystemPkgLPr(pkg.packageName);
9100                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9101                        // If the original was granted this permission, we take
9102                        // that grant decision as read and propagate it to the
9103                        // update.
9104                        if (sysPs.isPrivileged()) {
9105                            allowed = true;
9106                        }
9107                    } else {
9108                        // The system apk may have been updated with an older
9109                        // version of the one on the data partition, but which
9110                        // granted a new system permission that it didn't have
9111                        // before.  In this case we do want to allow the app to
9112                        // now get the new permission if the ancestral apk is
9113                        // privileged to get it.
9114                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9115                            for (int j=0;
9116                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9117                                if (perm.equals(
9118                                        sysPs.pkg.requestedPermissions.get(j))) {
9119                                    allowed = true;
9120                                    break;
9121                                }
9122                            }
9123                        }
9124                    }
9125                } else {
9126                    allowed = isPrivilegedApp(pkg);
9127                }
9128            }
9129        }
9130        if (!allowed) {
9131            if (!allowed && (bp.protectionLevel
9132                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9133                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9134                // If this was a previously normal/dangerous permission that got moved
9135                // to a system permission as part of the runtime permission redesign, then
9136                // we still want to blindly grant it to old apps.
9137                allowed = true;
9138            }
9139            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9140                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9141                // If this permission is to be granted to the system installer and
9142                // this app is an installer, then it gets the permission.
9143                allowed = true;
9144            }
9145            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9146                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9147                // If this permission is to be granted to the system verifier and
9148                // this app is a verifier, then it gets the permission.
9149                allowed = true;
9150            }
9151            if (!allowed && (bp.protectionLevel
9152                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9153                    && isSystemApp(pkg)) {
9154                // Any pre-installed system app is allowed to get this permission.
9155                allowed = true;
9156            }
9157            if (!allowed && (bp.protectionLevel
9158                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9159                // For development permissions, a development permission
9160                // is granted only if it was already granted.
9161                allowed = origPermissions.hasInstallPermission(perm);
9162            }
9163        }
9164        return allowed;
9165    }
9166
9167    final class ActivityIntentResolver
9168            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9169        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9170                boolean defaultOnly, int userId) {
9171            if (!sUserManager.exists(userId)) return null;
9172            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9173            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9174        }
9175
9176        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9177                int userId) {
9178            if (!sUserManager.exists(userId)) return null;
9179            mFlags = flags;
9180            return super.queryIntent(intent, resolvedType,
9181                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9182        }
9183
9184        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9185                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9186            if (!sUserManager.exists(userId)) return null;
9187            if (packageActivities == null) {
9188                return null;
9189            }
9190            mFlags = flags;
9191            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9192            final int N = packageActivities.size();
9193            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9194                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9195
9196            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9197            for (int i = 0; i < N; ++i) {
9198                intentFilters = packageActivities.get(i).intents;
9199                if (intentFilters != null && intentFilters.size() > 0) {
9200                    PackageParser.ActivityIntentInfo[] array =
9201                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9202                    intentFilters.toArray(array);
9203                    listCut.add(array);
9204                }
9205            }
9206            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9207        }
9208
9209        public final void addActivity(PackageParser.Activity a, String type) {
9210            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9211            mActivities.put(a.getComponentName(), a);
9212            if (DEBUG_SHOW_INFO)
9213                Log.v(
9214                TAG, "  " + type + " " +
9215                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9216            if (DEBUG_SHOW_INFO)
9217                Log.v(TAG, "    Class=" + a.info.name);
9218            final int NI = a.intents.size();
9219            for (int j=0; j<NI; j++) {
9220                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9221                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9222                    intent.setPriority(0);
9223                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9224                            + a.className + " with priority > 0, forcing to 0");
9225                }
9226                if (DEBUG_SHOW_INFO) {
9227                    Log.v(TAG, "    IntentFilter:");
9228                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9229                }
9230                if (!intent.debugCheck()) {
9231                    Log.w(TAG, "==> For Activity " + a.info.name);
9232                }
9233                addFilter(intent);
9234            }
9235        }
9236
9237        public final void removeActivity(PackageParser.Activity a, String type) {
9238            mActivities.remove(a.getComponentName());
9239            if (DEBUG_SHOW_INFO) {
9240                Log.v(TAG, "  " + type + " "
9241                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9242                                : a.info.name) + ":");
9243                Log.v(TAG, "    Class=" + a.info.name);
9244            }
9245            final int NI = a.intents.size();
9246            for (int j=0; j<NI; j++) {
9247                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9248                if (DEBUG_SHOW_INFO) {
9249                    Log.v(TAG, "    IntentFilter:");
9250                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9251                }
9252                removeFilter(intent);
9253            }
9254        }
9255
9256        @Override
9257        protected boolean allowFilterResult(
9258                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9259            ActivityInfo filterAi = filter.activity.info;
9260            for (int i=dest.size()-1; i>=0; i--) {
9261                ActivityInfo destAi = dest.get(i).activityInfo;
9262                if (destAi.name == filterAi.name
9263                        && destAi.packageName == filterAi.packageName) {
9264                    return false;
9265                }
9266            }
9267            return true;
9268        }
9269
9270        @Override
9271        protected ActivityIntentInfo[] newArray(int size) {
9272            return new ActivityIntentInfo[size];
9273        }
9274
9275        @Override
9276        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9277            if (!sUserManager.exists(userId)) return true;
9278            PackageParser.Package p = filter.activity.owner;
9279            if (p != null) {
9280                PackageSetting ps = (PackageSetting)p.mExtras;
9281                if (ps != null) {
9282                    // System apps are never considered stopped for purposes of
9283                    // filtering, because there may be no way for the user to
9284                    // actually re-launch them.
9285                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9286                            && ps.getStopped(userId);
9287                }
9288            }
9289            return false;
9290        }
9291
9292        @Override
9293        protected boolean isPackageForFilter(String packageName,
9294                PackageParser.ActivityIntentInfo info) {
9295            return packageName.equals(info.activity.owner.packageName);
9296        }
9297
9298        @Override
9299        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9300                int match, int userId) {
9301            if (!sUserManager.exists(userId)) return null;
9302            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9303                return null;
9304            }
9305            final PackageParser.Activity activity = info.activity;
9306            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9307            if (ps == null) {
9308                return null;
9309            }
9310            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9311                    ps.readUserState(userId), userId);
9312            if (ai == null) {
9313                return null;
9314            }
9315            final ResolveInfo res = new ResolveInfo();
9316            res.activityInfo = ai;
9317            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9318                res.filter = info;
9319            }
9320            if (info != null) {
9321                res.handleAllWebDataURI = info.handleAllWebDataURI();
9322            }
9323            res.priority = info.getPriority();
9324            res.preferredOrder = activity.owner.mPreferredOrder;
9325            //System.out.println("Result: " + res.activityInfo.className +
9326            //                   " = " + res.priority);
9327            res.match = match;
9328            res.isDefault = info.hasDefault;
9329            res.labelRes = info.labelRes;
9330            res.nonLocalizedLabel = info.nonLocalizedLabel;
9331            if (userNeedsBadging(userId)) {
9332                res.noResourceId = true;
9333            } else {
9334                res.icon = info.icon;
9335            }
9336            res.iconResourceId = info.icon;
9337            res.system = res.activityInfo.applicationInfo.isSystemApp();
9338            return res;
9339        }
9340
9341        @Override
9342        protected void sortResults(List<ResolveInfo> results) {
9343            Collections.sort(results, mResolvePrioritySorter);
9344        }
9345
9346        @Override
9347        protected void dumpFilter(PrintWriter out, String prefix,
9348                PackageParser.ActivityIntentInfo filter) {
9349            out.print(prefix); out.print(
9350                    Integer.toHexString(System.identityHashCode(filter.activity)));
9351                    out.print(' ');
9352                    filter.activity.printComponentShortName(out);
9353                    out.print(" filter ");
9354                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9355        }
9356
9357        @Override
9358        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9359            return filter.activity;
9360        }
9361
9362        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9363            PackageParser.Activity activity = (PackageParser.Activity)label;
9364            out.print(prefix); out.print(
9365                    Integer.toHexString(System.identityHashCode(activity)));
9366                    out.print(' ');
9367                    activity.printComponentShortName(out);
9368            if (count > 1) {
9369                out.print(" ("); out.print(count); out.print(" filters)");
9370            }
9371            out.println();
9372        }
9373
9374//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9375//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9376//            final List<ResolveInfo> retList = Lists.newArrayList();
9377//            while (i.hasNext()) {
9378//                final ResolveInfo resolveInfo = i.next();
9379//                if (isEnabledLP(resolveInfo.activityInfo)) {
9380//                    retList.add(resolveInfo);
9381//                }
9382//            }
9383//            return retList;
9384//        }
9385
9386        // Keys are String (activity class name), values are Activity.
9387        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9388                = new ArrayMap<ComponentName, PackageParser.Activity>();
9389        private int mFlags;
9390    }
9391
9392    private final class ServiceIntentResolver
9393            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9394        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9395                boolean defaultOnly, int userId) {
9396            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9397            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9398        }
9399
9400        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9401                int userId) {
9402            if (!sUserManager.exists(userId)) return null;
9403            mFlags = flags;
9404            return super.queryIntent(intent, resolvedType,
9405                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9406        }
9407
9408        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9409                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9410            if (!sUserManager.exists(userId)) return null;
9411            if (packageServices == null) {
9412                return null;
9413            }
9414            mFlags = flags;
9415            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9416            final int N = packageServices.size();
9417            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9418                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9419
9420            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9421            for (int i = 0; i < N; ++i) {
9422                intentFilters = packageServices.get(i).intents;
9423                if (intentFilters != null && intentFilters.size() > 0) {
9424                    PackageParser.ServiceIntentInfo[] array =
9425                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9426                    intentFilters.toArray(array);
9427                    listCut.add(array);
9428                }
9429            }
9430            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9431        }
9432
9433        public final void addService(PackageParser.Service s) {
9434            mServices.put(s.getComponentName(), s);
9435            if (DEBUG_SHOW_INFO) {
9436                Log.v(TAG, "  "
9437                        + (s.info.nonLocalizedLabel != null
9438                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9439                Log.v(TAG, "    Class=" + s.info.name);
9440            }
9441            final int NI = s.intents.size();
9442            int j;
9443            for (j=0; j<NI; j++) {
9444                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9445                if (DEBUG_SHOW_INFO) {
9446                    Log.v(TAG, "    IntentFilter:");
9447                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9448                }
9449                if (!intent.debugCheck()) {
9450                    Log.w(TAG, "==> For Service " + s.info.name);
9451                }
9452                addFilter(intent);
9453            }
9454        }
9455
9456        public final void removeService(PackageParser.Service s) {
9457            mServices.remove(s.getComponentName());
9458            if (DEBUG_SHOW_INFO) {
9459                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9460                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9461                Log.v(TAG, "    Class=" + s.info.name);
9462            }
9463            final int NI = s.intents.size();
9464            int j;
9465            for (j=0; j<NI; j++) {
9466                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9467                if (DEBUG_SHOW_INFO) {
9468                    Log.v(TAG, "    IntentFilter:");
9469                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9470                }
9471                removeFilter(intent);
9472            }
9473        }
9474
9475        @Override
9476        protected boolean allowFilterResult(
9477                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9478            ServiceInfo filterSi = filter.service.info;
9479            for (int i=dest.size()-1; i>=0; i--) {
9480                ServiceInfo destAi = dest.get(i).serviceInfo;
9481                if (destAi.name == filterSi.name
9482                        && destAi.packageName == filterSi.packageName) {
9483                    return false;
9484                }
9485            }
9486            return true;
9487        }
9488
9489        @Override
9490        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9491            return new PackageParser.ServiceIntentInfo[size];
9492        }
9493
9494        @Override
9495        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9496            if (!sUserManager.exists(userId)) return true;
9497            PackageParser.Package p = filter.service.owner;
9498            if (p != null) {
9499                PackageSetting ps = (PackageSetting)p.mExtras;
9500                if (ps != null) {
9501                    // System apps are never considered stopped for purposes of
9502                    // filtering, because there may be no way for the user to
9503                    // actually re-launch them.
9504                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9505                            && ps.getStopped(userId);
9506                }
9507            }
9508            return false;
9509        }
9510
9511        @Override
9512        protected boolean isPackageForFilter(String packageName,
9513                PackageParser.ServiceIntentInfo info) {
9514            return packageName.equals(info.service.owner.packageName);
9515        }
9516
9517        @Override
9518        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9519                int match, int userId) {
9520            if (!sUserManager.exists(userId)) return null;
9521            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9522            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9523                return null;
9524            }
9525            final PackageParser.Service service = info.service;
9526            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9527            if (ps == null) {
9528                return null;
9529            }
9530            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9531                    ps.readUserState(userId), userId);
9532            if (si == null) {
9533                return null;
9534            }
9535            final ResolveInfo res = new ResolveInfo();
9536            res.serviceInfo = si;
9537            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9538                res.filter = filter;
9539            }
9540            res.priority = info.getPriority();
9541            res.preferredOrder = service.owner.mPreferredOrder;
9542            res.match = match;
9543            res.isDefault = info.hasDefault;
9544            res.labelRes = info.labelRes;
9545            res.nonLocalizedLabel = info.nonLocalizedLabel;
9546            res.icon = info.icon;
9547            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9548            return res;
9549        }
9550
9551        @Override
9552        protected void sortResults(List<ResolveInfo> results) {
9553            Collections.sort(results, mResolvePrioritySorter);
9554        }
9555
9556        @Override
9557        protected void dumpFilter(PrintWriter out, String prefix,
9558                PackageParser.ServiceIntentInfo filter) {
9559            out.print(prefix); out.print(
9560                    Integer.toHexString(System.identityHashCode(filter.service)));
9561                    out.print(' ');
9562                    filter.service.printComponentShortName(out);
9563                    out.print(" filter ");
9564                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9565        }
9566
9567        @Override
9568        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9569            return filter.service;
9570        }
9571
9572        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9573            PackageParser.Service service = (PackageParser.Service)label;
9574            out.print(prefix); out.print(
9575                    Integer.toHexString(System.identityHashCode(service)));
9576                    out.print(' ');
9577                    service.printComponentShortName(out);
9578            if (count > 1) {
9579                out.print(" ("); out.print(count); out.print(" filters)");
9580            }
9581            out.println();
9582        }
9583
9584//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9585//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9586//            final List<ResolveInfo> retList = Lists.newArrayList();
9587//            while (i.hasNext()) {
9588//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9589//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9590//                    retList.add(resolveInfo);
9591//                }
9592//            }
9593//            return retList;
9594//        }
9595
9596        // Keys are String (activity class name), values are Activity.
9597        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9598                = new ArrayMap<ComponentName, PackageParser.Service>();
9599        private int mFlags;
9600    };
9601
9602    private final class ProviderIntentResolver
9603            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9604        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9605                boolean defaultOnly, int userId) {
9606            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9607            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9608        }
9609
9610        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9611                int userId) {
9612            if (!sUserManager.exists(userId))
9613                return null;
9614            mFlags = flags;
9615            return super.queryIntent(intent, resolvedType,
9616                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9617        }
9618
9619        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9620                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9621            if (!sUserManager.exists(userId))
9622                return null;
9623            if (packageProviders == null) {
9624                return null;
9625            }
9626            mFlags = flags;
9627            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9628            final int N = packageProviders.size();
9629            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9630                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9631
9632            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9633            for (int i = 0; i < N; ++i) {
9634                intentFilters = packageProviders.get(i).intents;
9635                if (intentFilters != null && intentFilters.size() > 0) {
9636                    PackageParser.ProviderIntentInfo[] array =
9637                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9638                    intentFilters.toArray(array);
9639                    listCut.add(array);
9640                }
9641            }
9642            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9643        }
9644
9645        public final void addProvider(PackageParser.Provider p) {
9646            if (mProviders.containsKey(p.getComponentName())) {
9647                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9648                return;
9649            }
9650
9651            mProviders.put(p.getComponentName(), p);
9652            if (DEBUG_SHOW_INFO) {
9653                Log.v(TAG, "  "
9654                        + (p.info.nonLocalizedLabel != null
9655                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9656                Log.v(TAG, "    Class=" + p.info.name);
9657            }
9658            final int NI = p.intents.size();
9659            int j;
9660            for (j = 0; j < NI; j++) {
9661                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9662                if (DEBUG_SHOW_INFO) {
9663                    Log.v(TAG, "    IntentFilter:");
9664                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9665                }
9666                if (!intent.debugCheck()) {
9667                    Log.w(TAG, "==> For Provider " + p.info.name);
9668                }
9669                addFilter(intent);
9670            }
9671        }
9672
9673        public final void removeProvider(PackageParser.Provider p) {
9674            mProviders.remove(p.getComponentName());
9675            if (DEBUG_SHOW_INFO) {
9676                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9677                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9678                Log.v(TAG, "    Class=" + p.info.name);
9679            }
9680            final int NI = p.intents.size();
9681            int j;
9682            for (j = 0; j < NI; j++) {
9683                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9684                if (DEBUG_SHOW_INFO) {
9685                    Log.v(TAG, "    IntentFilter:");
9686                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9687                }
9688                removeFilter(intent);
9689            }
9690        }
9691
9692        @Override
9693        protected boolean allowFilterResult(
9694                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9695            ProviderInfo filterPi = filter.provider.info;
9696            for (int i = dest.size() - 1; i >= 0; i--) {
9697                ProviderInfo destPi = dest.get(i).providerInfo;
9698                if (destPi.name == filterPi.name
9699                        && destPi.packageName == filterPi.packageName) {
9700                    return false;
9701                }
9702            }
9703            return true;
9704        }
9705
9706        @Override
9707        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9708            return new PackageParser.ProviderIntentInfo[size];
9709        }
9710
9711        @Override
9712        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9713            if (!sUserManager.exists(userId))
9714                return true;
9715            PackageParser.Package p = filter.provider.owner;
9716            if (p != null) {
9717                PackageSetting ps = (PackageSetting) p.mExtras;
9718                if (ps != null) {
9719                    // System apps are never considered stopped for purposes of
9720                    // filtering, because there may be no way for the user to
9721                    // actually re-launch them.
9722                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9723                            && ps.getStopped(userId);
9724                }
9725            }
9726            return false;
9727        }
9728
9729        @Override
9730        protected boolean isPackageForFilter(String packageName,
9731                PackageParser.ProviderIntentInfo info) {
9732            return packageName.equals(info.provider.owner.packageName);
9733        }
9734
9735        @Override
9736        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9737                int match, int userId) {
9738            if (!sUserManager.exists(userId))
9739                return null;
9740            final PackageParser.ProviderIntentInfo info = filter;
9741            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9742                return null;
9743            }
9744            final PackageParser.Provider provider = info.provider;
9745            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9746            if (ps == null) {
9747                return null;
9748            }
9749            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9750                    ps.readUserState(userId), userId);
9751            if (pi == null) {
9752                return null;
9753            }
9754            final ResolveInfo res = new ResolveInfo();
9755            res.providerInfo = pi;
9756            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9757                res.filter = filter;
9758            }
9759            res.priority = info.getPriority();
9760            res.preferredOrder = provider.owner.mPreferredOrder;
9761            res.match = match;
9762            res.isDefault = info.hasDefault;
9763            res.labelRes = info.labelRes;
9764            res.nonLocalizedLabel = info.nonLocalizedLabel;
9765            res.icon = info.icon;
9766            res.system = res.providerInfo.applicationInfo.isSystemApp();
9767            return res;
9768        }
9769
9770        @Override
9771        protected void sortResults(List<ResolveInfo> results) {
9772            Collections.sort(results, mResolvePrioritySorter);
9773        }
9774
9775        @Override
9776        protected void dumpFilter(PrintWriter out, String prefix,
9777                PackageParser.ProviderIntentInfo filter) {
9778            out.print(prefix);
9779            out.print(
9780                    Integer.toHexString(System.identityHashCode(filter.provider)));
9781            out.print(' ');
9782            filter.provider.printComponentShortName(out);
9783            out.print(" filter ");
9784            out.println(Integer.toHexString(System.identityHashCode(filter)));
9785        }
9786
9787        @Override
9788        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9789            return filter.provider;
9790        }
9791
9792        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9793            PackageParser.Provider provider = (PackageParser.Provider)label;
9794            out.print(prefix); out.print(
9795                    Integer.toHexString(System.identityHashCode(provider)));
9796                    out.print(' ');
9797                    provider.printComponentShortName(out);
9798            if (count > 1) {
9799                out.print(" ("); out.print(count); out.print(" filters)");
9800            }
9801            out.println();
9802        }
9803
9804        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9805                = new ArrayMap<ComponentName, PackageParser.Provider>();
9806        private int mFlags;
9807    }
9808
9809    private static final class EphemeralIntentResolver
9810            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9811        @Override
9812        protected EphemeralResolveIntentInfo[] newArray(int size) {
9813            return new EphemeralResolveIntentInfo[size];
9814        }
9815
9816        @Override
9817        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9818            return true;
9819        }
9820
9821        @Override
9822        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9823                int userId) {
9824            if (!sUserManager.exists(userId)) {
9825                return null;
9826            }
9827            return info.getEphemeralResolveInfo();
9828        }
9829    }
9830
9831    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9832            new Comparator<ResolveInfo>() {
9833        public int compare(ResolveInfo r1, ResolveInfo r2) {
9834            int v1 = r1.priority;
9835            int v2 = r2.priority;
9836            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9837            if (v1 != v2) {
9838                return (v1 > v2) ? -1 : 1;
9839            }
9840            v1 = r1.preferredOrder;
9841            v2 = r2.preferredOrder;
9842            if (v1 != v2) {
9843                return (v1 > v2) ? -1 : 1;
9844            }
9845            if (r1.isDefault != r2.isDefault) {
9846                return r1.isDefault ? -1 : 1;
9847            }
9848            v1 = r1.match;
9849            v2 = r2.match;
9850            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9851            if (v1 != v2) {
9852                return (v1 > v2) ? -1 : 1;
9853            }
9854            if (r1.system != r2.system) {
9855                return r1.system ? -1 : 1;
9856            }
9857            if (r1.activityInfo != null) {
9858                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9859            }
9860            if (r1.serviceInfo != null) {
9861                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9862            }
9863            if (r1.providerInfo != null) {
9864                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9865            }
9866            return 0;
9867        }
9868    };
9869
9870    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9871            new Comparator<ProviderInfo>() {
9872        public int compare(ProviderInfo p1, ProviderInfo p2) {
9873            final int v1 = p1.initOrder;
9874            final int v2 = p2.initOrder;
9875            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9876        }
9877    };
9878
9879    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9880            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9881            final int[] userIds) {
9882        mHandler.post(new Runnable() {
9883            @Override
9884            public void run() {
9885                try {
9886                    final IActivityManager am = ActivityManagerNative.getDefault();
9887                    if (am == null) return;
9888                    final int[] resolvedUserIds;
9889                    if (userIds == null) {
9890                        resolvedUserIds = am.getRunningUserIds();
9891                    } else {
9892                        resolvedUserIds = userIds;
9893                    }
9894                    for (int id : resolvedUserIds) {
9895                        final Intent intent = new Intent(action,
9896                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9897                        if (extras != null) {
9898                            intent.putExtras(extras);
9899                        }
9900                        if (targetPkg != null) {
9901                            intent.setPackage(targetPkg);
9902                        }
9903                        // Modify the UID when posting to other users
9904                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9905                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9906                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9907                            intent.putExtra(Intent.EXTRA_UID, uid);
9908                        }
9909                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9910                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9911                        if (DEBUG_BROADCASTS) {
9912                            RuntimeException here = new RuntimeException("here");
9913                            here.fillInStackTrace();
9914                            Slog.d(TAG, "Sending to user " + id + ": "
9915                                    + intent.toShortString(false, true, false, false)
9916                                    + " " + intent.getExtras(), here);
9917                        }
9918                        am.broadcastIntent(null, intent, null, finishedReceiver,
9919                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9920                                null, finishedReceiver != null, false, id);
9921                    }
9922                } catch (RemoteException ex) {
9923                }
9924            }
9925        });
9926    }
9927
9928    /**
9929     * Check if the external storage media is available. This is true if there
9930     * is a mounted external storage medium or if the external storage is
9931     * emulated.
9932     */
9933    private boolean isExternalMediaAvailable() {
9934        return mMediaMounted || Environment.isExternalStorageEmulated();
9935    }
9936
9937    @Override
9938    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9939        // writer
9940        synchronized (mPackages) {
9941            if (!isExternalMediaAvailable()) {
9942                // If the external storage is no longer mounted at this point,
9943                // the caller may not have been able to delete all of this
9944                // packages files and can not delete any more.  Bail.
9945                return null;
9946            }
9947            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9948            if (lastPackage != null) {
9949                pkgs.remove(lastPackage);
9950            }
9951            if (pkgs.size() > 0) {
9952                return pkgs.get(0);
9953            }
9954        }
9955        return null;
9956    }
9957
9958    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9959        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9960                userId, andCode ? 1 : 0, packageName);
9961        if (mSystemReady) {
9962            msg.sendToTarget();
9963        } else {
9964            if (mPostSystemReadyMessages == null) {
9965                mPostSystemReadyMessages = new ArrayList<>();
9966            }
9967            mPostSystemReadyMessages.add(msg);
9968        }
9969    }
9970
9971    void startCleaningPackages() {
9972        // reader
9973        synchronized (mPackages) {
9974            if (!isExternalMediaAvailable()) {
9975                return;
9976            }
9977            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9978                return;
9979            }
9980        }
9981        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9982        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9983        IActivityManager am = ActivityManagerNative.getDefault();
9984        if (am != null) {
9985            try {
9986                am.startService(null, intent, null, mContext.getOpPackageName(),
9987                        UserHandle.USER_SYSTEM);
9988            } catch (RemoteException e) {
9989            }
9990        }
9991    }
9992
9993    @Override
9994    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9995            int installFlags, String installerPackageName, VerificationParams verificationParams,
9996            String packageAbiOverride) {
9997        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9998                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9999    }
10000
10001    @Override
10002    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10003            int installFlags, String installerPackageName, VerificationParams verificationParams,
10004            String packageAbiOverride, int userId) {
10005        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10006
10007        final int callingUid = Binder.getCallingUid();
10008        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10009
10010        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10011            try {
10012                if (observer != null) {
10013                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10014                }
10015            } catch (RemoteException re) {
10016            }
10017            return;
10018        }
10019
10020        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10021            installFlags |= PackageManager.INSTALL_FROM_ADB;
10022
10023        } else {
10024            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10025            // about installerPackageName.
10026
10027            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10028            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10029        }
10030
10031        UserHandle user;
10032        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10033            user = UserHandle.ALL;
10034        } else {
10035            user = new UserHandle(userId);
10036        }
10037
10038        // Only system components can circumvent runtime permissions when installing.
10039        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10040                && mContext.checkCallingOrSelfPermission(Manifest.permission
10041                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10042            throw new SecurityException("You need the "
10043                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10044                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10045        }
10046
10047        verificationParams.setInstallerUid(callingUid);
10048
10049        final File originFile = new File(originPath);
10050        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10051
10052        final Message msg = mHandler.obtainMessage(INIT_COPY);
10053        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10054                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10055        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10056        msg.obj = params;
10057
10058        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10059                System.identityHashCode(msg.obj));
10060        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10061                System.identityHashCode(msg.obj));
10062
10063        mHandler.sendMessage(msg);
10064    }
10065
10066    void installStage(String packageName, File stagedDir, String stagedCid,
10067            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10068            String installerPackageName, int installerUid, UserHandle user) {
10069        if (DEBUG_EPHEMERAL) {
10070            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10071                Slog.d(TAG, "Ephemeral install of " + packageName);
10072            }
10073        }
10074        final VerificationParams verifParams = new VerificationParams(
10075                null, sessionParams.originatingUri, sessionParams.referrerUri,
10076                sessionParams.originatingUid);
10077        verifParams.setInstallerUid(installerUid);
10078
10079        final OriginInfo origin;
10080        if (stagedDir != null) {
10081            origin = OriginInfo.fromStagedFile(stagedDir);
10082        } else {
10083            origin = OriginInfo.fromStagedContainer(stagedCid);
10084        }
10085
10086        final Message msg = mHandler.obtainMessage(INIT_COPY);
10087        final InstallParams params = new InstallParams(origin, null, observer,
10088                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10089                verifParams, user, sessionParams.abiOverride,
10090                sessionParams.grantedRuntimePermissions);
10091        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10092        msg.obj = params;
10093
10094        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10095                System.identityHashCode(msg.obj));
10096        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10097                System.identityHashCode(msg.obj));
10098
10099        mHandler.sendMessage(msg);
10100    }
10101
10102    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10103        Bundle extras = new Bundle(1);
10104        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10105
10106        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10107                packageName, extras, 0, null, null, new int[] {userId});
10108        try {
10109            IActivityManager am = ActivityManagerNative.getDefault();
10110            final boolean isSystem =
10111                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10112            if (isSystem && am.isUserRunning(userId, 0)) {
10113                // The just-installed/enabled app is bundled on the system, so presumed
10114                // to be able to run automatically without needing an explicit launch.
10115                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10116                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10117                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10118                        .setPackage(packageName);
10119                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10120                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10121            }
10122        } catch (RemoteException e) {
10123            // shouldn't happen
10124            Slog.w(TAG, "Unable to bootstrap installed package", e);
10125        }
10126    }
10127
10128    @Override
10129    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10130            int userId) {
10131        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10132        PackageSetting pkgSetting;
10133        final int uid = Binder.getCallingUid();
10134        enforceCrossUserPermission(uid, userId, true, true,
10135                "setApplicationHiddenSetting for user " + userId);
10136
10137        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10138            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10139            return false;
10140        }
10141
10142        long callingId = Binder.clearCallingIdentity();
10143        try {
10144            boolean sendAdded = false;
10145            boolean sendRemoved = false;
10146            // writer
10147            synchronized (mPackages) {
10148                pkgSetting = mSettings.mPackages.get(packageName);
10149                if (pkgSetting == null) {
10150                    return false;
10151                }
10152                if (pkgSetting.getHidden(userId) != hidden) {
10153                    pkgSetting.setHidden(hidden, userId);
10154                    mSettings.writePackageRestrictionsLPr(userId);
10155                    if (hidden) {
10156                        sendRemoved = true;
10157                    } else {
10158                        sendAdded = true;
10159                    }
10160                }
10161            }
10162            if (sendAdded) {
10163                sendPackageAddedForUser(packageName, pkgSetting, userId);
10164                return true;
10165            }
10166            if (sendRemoved) {
10167                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10168                        "hiding pkg");
10169                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10170                return true;
10171            }
10172        } finally {
10173            Binder.restoreCallingIdentity(callingId);
10174        }
10175        return false;
10176    }
10177
10178    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10179            int userId) {
10180        final PackageRemovedInfo info = new PackageRemovedInfo();
10181        info.removedPackage = packageName;
10182        info.removedUsers = new int[] {userId};
10183        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10184        info.sendBroadcast(false, false, false);
10185    }
10186
10187    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10188        if (pkgList.length > 0) {
10189            Bundle extras = new Bundle(1);
10190            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10191
10192            sendPackageBroadcast(
10193                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10194                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10195                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10196                    new int[] {userId});
10197        }
10198    }
10199
10200    /**
10201     * Returns true if application is not found or there was an error. Otherwise it returns
10202     * the hidden state of the package for the given user.
10203     */
10204    @Override
10205    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10207        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10208                false, "getApplicationHidden for user " + userId);
10209        PackageSetting pkgSetting;
10210        long callingId = Binder.clearCallingIdentity();
10211        try {
10212            // writer
10213            synchronized (mPackages) {
10214                pkgSetting = mSettings.mPackages.get(packageName);
10215                if (pkgSetting == null) {
10216                    return true;
10217                }
10218                return pkgSetting.getHidden(userId);
10219            }
10220        } finally {
10221            Binder.restoreCallingIdentity(callingId);
10222        }
10223    }
10224
10225    /**
10226     * @hide
10227     */
10228    @Override
10229    public int installExistingPackageAsUser(String packageName, int userId) {
10230        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10231                null);
10232        PackageSetting pkgSetting;
10233        final int uid = Binder.getCallingUid();
10234        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10235                + userId);
10236        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10237            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10238        }
10239
10240        long callingId = Binder.clearCallingIdentity();
10241        try {
10242            boolean installed = false;
10243
10244            // writer
10245            synchronized (mPackages) {
10246                pkgSetting = mSettings.mPackages.get(packageName);
10247                if (pkgSetting == null) {
10248                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10249                }
10250                if (!pkgSetting.getInstalled(userId)) {
10251                    pkgSetting.setInstalled(true, userId);
10252                    pkgSetting.setHidden(false, userId);
10253                    mSettings.writePackageRestrictionsLPr(userId);
10254                    if (pkgSetting.pkg != null) {
10255                        prepareAppDataAfterInstall(pkgSetting.pkg);
10256                    }
10257                    installed = true;
10258                }
10259            }
10260
10261            if (installed) {
10262                sendPackageAddedForUser(packageName, pkgSetting, userId);
10263            }
10264        } finally {
10265            Binder.restoreCallingIdentity(callingId);
10266        }
10267
10268        return PackageManager.INSTALL_SUCCEEDED;
10269    }
10270
10271    boolean isUserRestricted(int userId, String restrictionKey) {
10272        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10273        if (restrictions.getBoolean(restrictionKey, false)) {
10274            Log.w(TAG, "User is restricted: " + restrictionKey);
10275            return true;
10276        }
10277        return false;
10278    }
10279
10280    @Override
10281    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10282        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10283        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10284                "setPackageSuspended for user " + userId);
10285
10286        // TODO: investigate and add more restrictions for suspending crucial packages.
10287        if (isPackageDeviceAdmin(packageName, userId)) {
10288            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10289                    + "\": has active device admin");
10290            return false;
10291        }
10292
10293        long callingId = Binder.clearCallingIdentity();
10294        try {
10295            boolean changed = false;
10296            boolean success = false;
10297            int appId = -1;
10298            synchronized (mPackages) {
10299                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10300                if (pkgSetting != null) {
10301                    if (pkgSetting.getSuspended(userId) != suspended) {
10302                        pkgSetting.setSuspended(suspended, userId);
10303                        mSettings.writePackageRestrictionsLPr(userId);
10304                        appId = pkgSetting.appId;
10305                        changed = true;
10306                    }
10307                    success = true;
10308                }
10309            }
10310
10311            if (changed) {
10312                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10313                if (suspended) {
10314                    killApplication(packageName, UserHandle.getUid(userId, appId),
10315                            "suspending package");
10316                }
10317            }
10318            return success;
10319        } finally {
10320            Binder.restoreCallingIdentity(callingId);
10321        }
10322    }
10323
10324    @Override
10325    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10326        mContext.enforceCallingOrSelfPermission(
10327                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10328                "Only package verification agents can verify applications");
10329
10330        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10331        final PackageVerificationResponse response = new PackageVerificationResponse(
10332                verificationCode, Binder.getCallingUid());
10333        msg.arg1 = id;
10334        msg.obj = response;
10335        mHandler.sendMessage(msg);
10336    }
10337
10338    @Override
10339    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10340            long millisecondsToDelay) {
10341        mContext.enforceCallingOrSelfPermission(
10342                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10343                "Only package verification agents can extend verification timeouts");
10344
10345        final PackageVerificationState state = mPendingVerification.get(id);
10346        final PackageVerificationResponse response = new PackageVerificationResponse(
10347                verificationCodeAtTimeout, Binder.getCallingUid());
10348
10349        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10350            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10351        }
10352        if (millisecondsToDelay < 0) {
10353            millisecondsToDelay = 0;
10354        }
10355        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10356                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10357            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10358        }
10359
10360        if ((state != null) && !state.timeoutExtended()) {
10361            state.extendTimeout();
10362
10363            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10364            msg.arg1 = id;
10365            msg.obj = response;
10366            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10367        }
10368    }
10369
10370    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10371            int verificationCode, UserHandle user) {
10372        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10373        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10374        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10375        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10376        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10377
10378        mContext.sendBroadcastAsUser(intent, user,
10379                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10380    }
10381
10382    private ComponentName matchComponentForVerifier(String packageName,
10383            List<ResolveInfo> receivers) {
10384        ActivityInfo targetReceiver = null;
10385
10386        final int NR = receivers.size();
10387        for (int i = 0; i < NR; i++) {
10388            final ResolveInfo info = receivers.get(i);
10389            if (info.activityInfo == null) {
10390                continue;
10391            }
10392
10393            if (packageName.equals(info.activityInfo.packageName)) {
10394                targetReceiver = info.activityInfo;
10395                break;
10396            }
10397        }
10398
10399        if (targetReceiver == null) {
10400            return null;
10401        }
10402
10403        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10404    }
10405
10406    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10407            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10408        if (pkgInfo.verifiers.length == 0) {
10409            return null;
10410        }
10411
10412        final int N = pkgInfo.verifiers.length;
10413        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10414        for (int i = 0; i < N; i++) {
10415            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10416
10417            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10418                    receivers);
10419            if (comp == null) {
10420                continue;
10421            }
10422
10423            final int verifierUid = getUidForVerifier(verifierInfo);
10424            if (verifierUid == -1) {
10425                continue;
10426            }
10427
10428            if (DEBUG_VERIFY) {
10429                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10430                        + " with the correct signature");
10431            }
10432            sufficientVerifiers.add(comp);
10433            verificationState.addSufficientVerifier(verifierUid);
10434        }
10435
10436        return sufficientVerifiers;
10437    }
10438
10439    private int getUidForVerifier(VerifierInfo verifierInfo) {
10440        synchronized (mPackages) {
10441            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10442            if (pkg == null) {
10443                return -1;
10444            } else if (pkg.mSignatures.length != 1) {
10445                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10446                        + " has more than one signature; ignoring");
10447                return -1;
10448            }
10449
10450            /*
10451             * If the public key of the package's signature does not match
10452             * our expected public key, then this is a different package and
10453             * we should skip.
10454             */
10455
10456            final byte[] expectedPublicKey;
10457            try {
10458                final Signature verifierSig = pkg.mSignatures[0];
10459                final PublicKey publicKey = verifierSig.getPublicKey();
10460                expectedPublicKey = publicKey.getEncoded();
10461            } catch (CertificateException e) {
10462                return -1;
10463            }
10464
10465            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10466
10467            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10468                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10469                        + " does not have the expected public key; ignoring");
10470                return -1;
10471            }
10472
10473            return pkg.applicationInfo.uid;
10474        }
10475    }
10476
10477    @Override
10478    public void finishPackageInstall(int token) {
10479        enforceSystemOrRoot("Only the system is allowed to finish installs");
10480
10481        if (DEBUG_INSTALL) {
10482            Slog.v(TAG, "BM finishing package install for " + token);
10483        }
10484        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10485
10486        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10487        mHandler.sendMessage(msg);
10488    }
10489
10490    /**
10491     * Get the verification agent timeout.
10492     *
10493     * @return verification timeout in milliseconds
10494     */
10495    private long getVerificationTimeout() {
10496        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10497                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10498                DEFAULT_VERIFICATION_TIMEOUT);
10499    }
10500
10501    /**
10502     * Get the default verification agent response code.
10503     *
10504     * @return default verification response code
10505     */
10506    private int getDefaultVerificationResponse() {
10507        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10508                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10509                DEFAULT_VERIFICATION_RESPONSE);
10510    }
10511
10512    /**
10513     * Check whether or not package verification has been enabled.
10514     *
10515     * @return true if verification should be performed
10516     */
10517    private boolean isVerificationEnabled(int userId, int installFlags) {
10518        if (!DEFAULT_VERIFY_ENABLE) {
10519            return false;
10520        }
10521        // Ephemeral apps don't get the full verification treatment
10522        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10523            if (DEBUG_EPHEMERAL) {
10524                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10525            }
10526            return false;
10527        }
10528
10529        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10530
10531        // Check if installing from ADB
10532        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10533            // Do not run verification in a test harness environment
10534            if (ActivityManager.isRunningInTestHarness()) {
10535                return false;
10536            }
10537            if (ensureVerifyAppsEnabled) {
10538                return true;
10539            }
10540            // Check if the developer does not want package verification for ADB installs
10541            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10542                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10543                return false;
10544            }
10545        }
10546
10547        if (ensureVerifyAppsEnabled) {
10548            return true;
10549        }
10550
10551        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10552                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10553    }
10554
10555    @Override
10556    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10557            throws RemoteException {
10558        mContext.enforceCallingOrSelfPermission(
10559                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10560                "Only intentfilter verification agents can verify applications");
10561
10562        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10563        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10564                Binder.getCallingUid(), verificationCode, failedDomains);
10565        msg.arg1 = id;
10566        msg.obj = response;
10567        mHandler.sendMessage(msg);
10568    }
10569
10570    @Override
10571    public int getIntentVerificationStatus(String packageName, int userId) {
10572        synchronized (mPackages) {
10573            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10574        }
10575    }
10576
10577    @Override
10578    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10579        mContext.enforceCallingOrSelfPermission(
10580                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10581
10582        boolean result = false;
10583        synchronized (mPackages) {
10584            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10585        }
10586        if (result) {
10587            scheduleWritePackageRestrictionsLocked(userId);
10588        }
10589        return result;
10590    }
10591
10592    @Override
10593    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10594        synchronized (mPackages) {
10595            return mSettings.getIntentFilterVerificationsLPr(packageName);
10596        }
10597    }
10598
10599    @Override
10600    public List<IntentFilter> getAllIntentFilters(String packageName) {
10601        if (TextUtils.isEmpty(packageName)) {
10602            return Collections.<IntentFilter>emptyList();
10603        }
10604        synchronized (mPackages) {
10605            PackageParser.Package pkg = mPackages.get(packageName);
10606            if (pkg == null || pkg.activities == null) {
10607                return Collections.<IntentFilter>emptyList();
10608            }
10609            final int count = pkg.activities.size();
10610            ArrayList<IntentFilter> result = new ArrayList<>();
10611            for (int n=0; n<count; n++) {
10612                PackageParser.Activity activity = pkg.activities.get(n);
10613                if (activity.intents != null && activity.intents.size() > 0) {
10614                    result.addAll(activity.intents);
10615                }
10616            }
10617            return result;
10618        }
10619    }
10620
10621    @Override
10622    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10623        mContext.enforceCallingOrSelfPermission(
10624                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10625
10626        synchronized (mPackages) {
10627            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10628            if (packageName != null) {
10629                result |= updateIntentVerificationStatus(packageName,
10630                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10631                        userId);
10632                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10633                        packageName, userId);
10634            }
10635            return result;
10636        }
10637    }
10638
10639    @Override
10640    public String getDefaultBrowserPackageName(int userId) {
10641        synchronized (mPackages) {
10642            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10643        }
10644    }
10645
10646    /**
10647     * Get the "allow unknown sources" setting.
10648     *
10649     * @return the current "allow unknown sources" setting
10650     */
10651    private int getUnknownSourcesSettings() {
10652        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10653                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10654                -1);
10655    }
10656
10657    @Override
10658    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10659        final int uid = Binder.getCallingUid();
10660        // writer
10661        synchronized (mPackages) {
10662            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10663            if (targetPackageSetting == null) {
10664                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10665            }
10666
10667            PackageSetting installerPackageSetting;
10668            if (installerPackageName != null) {
10669                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10670                if (installerPackageSetting == null) {
10671                    throw new IllegalArgumentException("Unknown installer package: "
10672                            + installerPackageName);
10673                }
10674            } else {
10675                installerPackageSetting = null;
10676            }
10677
10678            Signature[] callerSignature;
10679            Object obj = mSettings.getUserIdLPr(uid);
10680            if (obj != null) {
10681                if (obj instanceof SharedUserSetting) {
10682                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10683                } else if (obj instanceof PackageSetting) {
10684                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10685                } else {
10686                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10687                }
10688            } else {
10689                throw new SecurityException("Unknown calling UID: " + uid);
10690            }
10691
10692            // Verify: can't set installerPackageName to a package that is
10693            // not signed with the same cert as the caller.
10694            if (installerPackageSetting != null) {
10695                if (compareSignatures(callerSignature,
10696                        installerPackageSetting.signatures.mSignatures)
10697                        != PackageManager.SIGNATURE_MATCH) {
10698                    throw new SecurityException(
10699                            "Caller does not have same cert as new installer package "
10700                            + installerPackageName);
10701                }
10702            }
10703
10704            // Verify: if target already has an installer package, it must
10705            // be signed with the same cert as the caller.
10706            if (targetPackageSetting.installerPackageName != null) {
10707                PackageSetting setting = mSettings.mPackages.get(
10708                        targetPackageSetting.installerPackageName);
10709                // If the currently set package isn't valid, then it's always
10710                // okay to change it.
10711                if (setting != null) {
10712                    if (compareSignatures(callerSignature,
10713                            setting.signatures.mSignatures)
10714                            != PackageManager.SIGNATURE_MATCH) {
10715                        throw new SecurityException(
10716                                "Caller does not have same cert as old installer package "
10717                                + targetPackageSetting.installerPackageName);
10718                    }
10719                }
10720            }
10721
10722            // Okay!
10723            targetPackageSetting.installerPackageName = installerPackageName;
10724            scheduleWriteSettingsLocked();
10725        }
10726    }
10727
10728    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10729        // Queue up an async operation since the package installation may take a little while.
10730        mHandler.post(new Runnable() {
10731            public void run() {
10732                mHandler.removeCallbacks(this);
10733                 // Result object to be returned
10734                PackageInstalledInfo res = new PackageInstalledInfo();
10735                res.returnCode = currentStatus;
10736                res.uid = -1;
10737                res.pkg = null;
10738                res.removedInfo = new PackageRemovedInfo();
10739                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10740                    args.doPreInstall(res.returnCode);
10741                    synchronized (mInstallLock) {
10742                        installPackageTracedLI(args, res);
10743                    }
10744                    args.doPostInstall(res.returnCode, res.uid);
10745                }
10746
10747                // A restore should be performed at this point if (a) the install
10748                // succeeded, (b) the operation is not an update, and (c) the new
10749                // package has not opted out of backup participation.
10750                final boolean update = res.removedInfo.removedPackage != null;
10751                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10752                boolean doRestore = !update
10753                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10754
10755                // Set up the post-install work request bookkeeping.  This will be used
10756                // and cleaned up by the post-install event handling regardless of whether
10757                // there's a restore pass performed.  Token values are >= 1.
10758                int token;
10759                if (mNextInstallToken < 0) mNextInstallToken = 1;
10760                token = mNextInstallToken++;
10761
10762                PostInstallData data = new PostInstallData(args, res);
10763                mRunningInstalls.put(token, data);
10764                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10765
10766                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10767                    // Pass responsibility to the Backup Manager.  It will perform a
10768                    // restore if appropriate, then pass responsibility back to the
10769                    // Package Manager to run the post-install observer callbacks
10770                    // and broadcasts.
10771                    IBackupManager bm = IBackupManager.Stub.asInterface(
10772                            ServiceManager.getService(Context.BACKUP_SERVICE));
10773                    if (bm != null) {
10774                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10775                                + " to BM for possible restore");
10776                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10777                        try {
10778                            // TODO: http://b/22388012
10779                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10780                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10781                            } else {
10782                                doRestore = false;
10783                            }
10784                        } catch (RemoteException e) {
10785                            // can't happen; the backup manager is local
10786                        } catch (Exception e) {
10787                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10788                            doRestore = false;
10789                        }
10790                    } else {
10791                        Slog.e(TAG, "Backup Manager not found!");
10792                        doRestore = false;
10793                    }
10794                }
10795
10796                if (!doRestore) {
10797                    // No restore possible, or the Backup Manager was mysteriously not
10798                    // available -- just fire the post-install work request directly.
10799                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10800
10801                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10802
10803                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10804                    mHandler.sendMessage(msg);
10805                }
10806            }
10807        });
10808    }
10809
10810    private abstract class HandlerParams {
10811        private static final int MAX_RETRIES = 4;
10812
10813        /**
10814         * Number of times startCopy() has been attempted and had a non-fatal
10815         * error.
10816         */
10817        private int mRetries = 0;
10818
10819        /** User handle for the user requesting the information or installation. */
10820        private final UserHandle mUser;
10821        String traceMethod;
10822        int traceCookie;
10823
10824        HandlerParams(UserHandle user) {
10825            mUser = user;
10826        }
10827
10828        UserHandle getUser() {
10829            return mUser;
10830        }
10831
10832        HandlerParams setTraceMethod(String traceMethod) {
10833            this.traceMethod = traceMethod;
10834            return this;
10835        }
10836
10837        HandlerParams setTraceCookie(int traceCookie) {
10838            this.traceCookie = traceCookie;
10839            return this;
10840        }
10841
10842        final boolean startCopy() {
10843            boolean res;
10844            try {
10845                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10846
10847                if (++mRetries > MAX_RETRIES) {
10848                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10849                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10850                    handleServiceError();
10851                    return false;
10852                } else {
10853                    handleStartCopy();
10854                    res = true;
10855                }
10856            } catch (RemoteException e) {
10857                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10858                mHandler.sendEmptyMessage(MCS_RECONNECT);
10859                res = false;
10860            }
10861            handleReturnCode();
10862            return res;
10863        }
10864
10865        final void serviceError() {
10866            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10867            handleServiceError();
10868            handleReturnCode();
10869        }
10870
10871        abstract void handleStartCopy() throws RemoteException;
10872        abstract void handleServiceError();
10873        abstract void handleReturnCode();
10874    }
10875
10876    class MeasureParams extends HandlerParams {
10877        private final PackageStats mStats;
10878        private boolean mSuccess;
10879
10880        private final IPackageStatsObserver mObserver;
10881
10882        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10883            super(new UserHandle(stats.userHandle));
10884            mObserver = observer;
10885            mStats = stats;
10886        }
10887
10888        @Override
10889        public String toString() {
10890            return "MeasureParams{"
10891                + Integer.toHexString(System.identityHashCode(this))
10892                + " " + mStats.packageName + "}";
10893        }
10894
10895        @Override
10896        void handleStartCopy() throws RemoteException {
10897            synchronized (mInstallLock) {
10898                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10899            }
10900
10901            if (mSuccess) {
10902                final boolean mounted;
10903                if (Environment.isExternalStorageEmulated()) {
10904                    mounted = true;
10905                } else {
10906                    final String status = Environment.getExternalStorageState();
10907                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10908                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10909                }
10910
10911                if (mounted) {
10912                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10913
10914                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10915                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10916
10917                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10918                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10919
10920                    // Always subtract cache size, since it's a subdirectory
10921                    mStats.externalDataSize -= mStats.externalCacheSize;
10922
10923                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10924                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10925
10926                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10927                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10928                }
10929            }
10930        }
10931
10932        @Override
10933        void handleReturnCode() {
10934            if (mObserver != null) {
10935                try {
10936                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10937                } catch (RemoteException e) {
10938                    Slog.i(TAG, "Observer no longer exists.");
10939                }
10940            }
10941        }
10942
10943        @Override
10944        void handleServiceError() {
10945            Slog.e(TAG, "Could not measure application " + mStats.packageName
10946                            + " external storage");
10947        }
10948    }
10949
10950    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10951            throws RemoteException {
10952        long result = 0;
10953        for (File path : paths) {
10954            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10955        }
10956        return result;
10957    }
10958
10959    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10960        for (File path : paths) {
10961            try {
10962                mcs.clearDirectory(path.getAbsolutePath());
10963            } catch (RemoteException e) {
10964            }
10965        }
10966    }
10967
10968    static class OriginInfo {
10969        /**
10970         * Location where install is coming from, before it has been
10971         * copied/renamed into place. This could be a single monolithic APK
10972         * file, or a cluster directory. This location may be untrusted.
10973         */
10974        final File file;
10975        final String cid;
10976
10977        /**
10978         * Flag indicating that {@link #file} or {@link #cid} has already been
10979         * staged, meaning downstream users don't need to defensively copy the
10980         * contents.
10981         */
10982        final boolean staged;
10983
10984        /**
10985         * Flag indicating that {@link #file} or {@link #cid} is an already
10986         * installed app that is being moved.
10987         */
10988        final boolean existing;
10989
10990        final String resolvedPath;
10991        final File resolvedFile;
10992
10993        static OriginInfo fromNothing() {
10994            return new OriginInfo(null, null, false, false);
10995        }
10996
10997        static OriginInfo fromUntrustedFile(File file) {
10998            return new OriginInfo(file, null, false, false);
10999        }
11000
11001        static OriginInfo fromExistingFile(File file) {
11002            return new OriginInfo(file, null, false, true);
11003        }
11004
11005        static OriginInfo fromStagedFile(File file) {
11006            return new OriginInfo(file, null, true, false);
11007        }
11008
11009        static OriginInfo fromStagedContainer(String cid) {
11010            return new OriginInfo(null, cid, true, false);
11011        }
11012
11013        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11014            this.file = file;
11015            this.cid = cid;
11016            this.staged = staged;
11017            this.existing = existing;
11018
11019            if (cid != null) {
11020                resolvedPath = PackageHelper.getSdDir(cid);
11021                resolvedFile = new File(resolvedPath);
11022            } else if (file != null) {
11023                resolvedPath = file.getAbsolutePath();
11024                resolvedFile = file;
11025            } else {
11026                resolvedPath = null;
11027                resolvedFile = null;
11028            }
11029        }
11030    }
11031
11032    static class MoveInfo {
11033        final int moveId;
11034        final String fromUuid;
11035        final String toUuid;
11036        final String packageName;
11037        final String dataAppName;
11038        final int appId;
11039        final String seinfo;
11040        final int targetSdkVersion;
11041
11042        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11043                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11044            this.moveId = moveId;
11045            this.fromUuid = fromUuid;
11046            this.toUuid = toUuid;
11047            this.packageName = packageName;
11048            this.dataAppName = dataAppName;
11049            this.appId = appId;
11050            this.seinfo = seinfo;
11051            this.targetSdkVersion = targetSdkVersion;
11052        }
11053    }
11054
11055    class InstallParams extends HandlerParams {
11056        final OriginInfo origin;
11057        final MoveInfo move;
11058        final IPackageInstallObserver2 observer;
11059        int installFlags;
11060        final String installerPackageName;
11061        final String volumeUuid;
11062        final VerificationParams verificationParams;
11063        private InstallArgs mArgs;
11064        private int mRet;
11065        final String packageAbiOverride;
11066        final String[] grantedRuntimePermissions;
11067
11068        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11069                int installFlags, String installerPackageName, String volumeUuid,
11070                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11071                String[] grantedPermissions) {
11072            super(user);
11073            this.origin = origin;
11074            this.move = move;
11075            this.observer = observer;
11076            this.installFlags = installFlags;
11077            this.installerPackageName = installerPackageName;
11078            this.volumeUuid = volumeUuid;
11079            this.verificationParams = verificationParams;
11080            this.packageAbiOverride = packageAbiOverride;
11081            this.grantedRuntimePermissions = grantedPermissions;
11082        }
11083
11084        @Override
11085        public String toString() {
11086            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11087                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11088        }
11089
11090        private int installLocationPolicy(PackageInfoLite pkgLite) {
11091            String packageName = pkgLite.packageName;
11092            int installLocation = pkgLite.installLocation;
11093            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11094            // reader
11095            synchronized (mPackages) {
11096                PackageParser.Package pkg = mPackages.get(packageName);
11097                if (pkg != null) {
11098                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11099                        // Check for downgrading.
11100                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11101                            try {
11102                                checkDowngrade(pkg, pkgLite);
11103                            } catch (PackageManagerException e) {
11104                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11105                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11106                            }
11107                        }
11108                        // Check for updated system application.
11109                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11110                            if (onSd) {
11111                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11112                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11113                            }
11114                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11115                        } else {
11116                            if (onSd) {
11117                                // Install flag overrides everything.
11118                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11119                            }
11120                            // If current upgrade specifies particular preference
11121                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11122                                // Application explicitly specified internal.
11123                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11124                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11125                                // App explictly prefers external. Let policy decide
11126                            } else {
11127                                // Prefer previous location
11128                                if (isExternal(pkg)) {
11129                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11130                                }
11131                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11132                            }
11133                        }
11134                    } else {
11135                        // Invalid install. Return error code
11136                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11137                    }
11138                }
11139            }
11140            // All the special cases have been taken care of.
11141            // Return result based on recommended install location.
11142            if (onSd) {
11143                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11144            }
11145            return pkgLite.recommendedInstallLocation;
11146        }
11147
11148        /*
11149         * Invoke remote method to get package information and install
11150         * location values. Override install location based on default
11151         * policy if needed and then create install arguments based
11152         * on the install location.
11153         */
11154        public void handleStartCopy() throws RemoteException {
11155            int ret = PackageManager.INSTALL_SUCCEEDED;
11156
11157            // If we're already staged, we've firmly committed to an install location
11158            if (origin.staged) {
11159                if (origin.file != null) {
11160                    installFlags |= PackageManager.INSTALL_INTERNAL;
11161                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11162                } else if (origin.cid != null) {
11163                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11164                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11165                } else {
11166                    throw new IllegalStateException("Invalid stage location");
11167                }
11168            }
11169
11170            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11171            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11172            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11173            PackageInfoLite pkgLite = null;
11174
11175            if (onInt && onSd) {
11176                // Check if both bits are set.
11177                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11178                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11179            } else if (onSd && ephemeral) {
11180                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11181                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11182            } else {
11183                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11184                        packageAbiOverride);
11185
11186                if (DEBUG_EPHEMERAL && ephemeral) {
11187                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11188                }
11189
11190                /*
11191                 * If we have too little free space, try to free cache
11192                 * before giving up.
11193                 */
11194                if (!origin.staged && pkgLite.recommendedInstallLocation
11195                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11196                    // TODO: focus freeing disk space on the target device
11197                    final StorageManager storage = StorageManager.from(mContext);
11198                    final long lowThreshold = storage.getStorageLowBytes(
11199                            Environment.getDataDirectory());
11200
11201                    final long sizeBytes = mContainerService.calculateInstalledSize(
11202                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11203
11204                    try {
11205                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11206                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11207                                installFlags, packageAbiOverride);
11208                    } catch (InstallerException e) {
11209                        Slog.w(TAG, "Failed to free cache", e);
11210                    }
11211
11212                    /*
11213                     * The cache free must have deleted the file we
11214                     * downloaded to install.
11215                     *
11216                     * TODO: fix the "freeCache" call to not delete
11217                     *       the file we care about.
11218                     */
11219                    if (pkgLite.recommendedInstallLocation
11220                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11221                        pkgLite.recommendedInstallLocation
11222                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11223                    }
11224                }
11225            }
11226
11227            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11228                int loc = pkgLite.recommendedInstallLocation;
11229                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11230                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11231                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11232                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11233                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11234                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11235                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11236                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11237                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11238                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11239                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11240                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11241                } else {
11242                    // Override with defaults if needed.
11243                    loc = installLocationPolicy(pkgLite);
11244                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11245                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11246                    } else if (!onSd && !onInt) {
11247                        // Override install location with flags
11248                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11249                            // Set the flag to install on external media.
11250                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11251                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11252                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11253                            if (DEBUG_EPHEMERAL) {
11254                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11255                            }
11256                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11257                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11258                                    |PackageManager.INSTALL_INTERNAL);
11259                        } else {
11260                            // Make sure the flag for installing on external
11261                            // media is unset
11262                            installFlags |= PackageManager.INSTALL_INTERNAL;
11263                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11264                        }
11265                    }
11266                }
11267            }
11268
11269            final InstallArgs args = createInstallArgs(this);
11270            mArgs = args;
11271
11272            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11273                // TODO: http://b/22976637
11274                // Apps installed for "all" users use the device owner to verify the app
11275                UserHandle verifierUser = getUser();
11276                if (verifierUser == UserHandle.ALL) {
11277                    verifierUser = UserHandle.SYSTEM;
11278                }
11279
11280                /*
11281                 * Determine if we have any installed package verifiers. If we
11282                 * do, then we'll defer to them to verify the packages.
11283                 */
11284                final int requiredUid = mRequiredVerifierPackage == null ? -1
11285                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11286                                verifierUser.getIdentifier());
11287                if (!origin.existing && requiredUid != -1
11288                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11289                    final Intent verification = new Intent(
11290                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11291                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11292                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11293                            PACKAGE_MIME_TYPE);
11294                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11295
11296                    // Query all live verifiers based on current user state
11297                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11298                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11299
11300                    if (DEBUG_VERIFY) {
11301                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11302                                + verification.toString() + " with " + pkgLite.verifiers.length
11303                                + " optional verifiers");
11304                    }
11305
11306                    final int verificationId = mPendingVerificationToken++;
11307
11308                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11309
11310                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11311                            installerPackageName);
11312
11313                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11314                            installFlags);
11315
11316                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11317                            pkgLite.packageName);
11318
11319                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11320                            pkgLite.versionCode);
11321
11322                    if (verificationParams != null) {
11323                        if (verificationParams.getVerificationURI() != null) {
11324                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11325                                 verificationParams.getVerificationURI());
11326                        }
11327                        if (verificationParams.getOriginatingURI() != null) {
11328                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11329                                  verificationParams.getOriginatingURI());
11330                        }
11331                        if (verificationParams.getReferrer() != null) {
11332                            verification.putExtra(Intent.EXTRA_REFERRER,
11333                                  verificationParams.getReferrer());
11334                        }
11335                        if (verificationParams.getOriginatingUid() >= 0) {
11336                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11337                                  verificationParams.getOriginatingUid());
11338                        }
11339                        if (verificationParams.getInstallerUid() >= 0) {
11340                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11341                                  verificationParams.getInstallerUid());
11342                        }
11343                    }
11344
11345                    final PackageVerificationState verificationState = new PackageVerificationState(
11346                            requiredUid, args);
11347
11348                    mPendingVerification.append(verificationId, verificationState);
11349
11350                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11351                            receivers, verificationState);
11352
11353                    /*
11354                     * If any sufficient verifiers were listed in the package
11355                     * manifest, attempt to ask them.
11356                     */
11357                    if (sufficientVerifiers != null) {
11358                        final int N = sufficientVerifiers.size();
11359                        if (N == 0) {
11360                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11361                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11362                        } else {
11363                            for (int i = 0; i < N; i++) {
11364                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11365
11366                                final Intent sufficientIntent = new Intent(verification);
11367                                sufficientIntent.setComponent(verifierComponent);
11368                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11369                            }
11370                        }
11371                    }
11372
11373                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11374                            mRequiredVerifierPackage, receivers);
11375                    if (ret == PackageManager.INSTALL_SUCCEEDED
11376                            && mRequiredVerifierPackage != null) {
11377                        Trace.asyncTraceBegin(
11378                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11379                        /*
11380                         * Send the intent to the required verification agent,
11381                         * but only start the verification timeout after the
11382                         * target BroadcastReceivers have run.
11383                         */
11384                        verification.setComponent(requiredVerifierComponent);
11385                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11386                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11387                                new BroadcastReceiver() {
11388                                    @Override
11389                                    public void onReceive(Context context, Intent intent) {
11390                                        final Message msg = mHandler
11391                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11392                                        msg.arg1 = verificationId;
11393                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11394                                    }
11395                                }, null, 0, null, null);
11396
11397                        /*
11398                         * We don't want the copy to proceed until verification
11399                         * succeeds, so null out this field.
11400                         */
11401                        mArgs = null;
11402                    }
11403                } else {
11404                    /*
11405                     * No package verification is enabled, so immediately start
11406                     * the remote call to initiate copy using temporary file.
11407                     */
11408                    ret = args.copyApk(mContainerService, true);
11409                }
11410            }
11411
11412            mRet = ret;
11413        }
11414
11415        @Override
11416        void handleReturnCode() {
11417            // If mArgs is null, then MCS couldn't be reached. When it
11418            // reconnects, it will try again to install. At that point, this
11419            // will succeed.
11420            if (mArgs != null) {
11421                processPendingInstall(mArgs, mRet);
11422            }
11423        }
11424
11425        @Override
11426        void handleServiceError() {
11427            mArgs = createInstallArgs(this);
11428            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11429        }
11430
11431        public boolean isForwardLocked() {
11432            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11433        }
11434    }
11435
11436    /**
11437     * Used during creation of InstallArgs
11438     *
11439     * @param installFlags package installation flags
11440     * @return true if should be installed on external storage
11441     */
11442    private static boolean installOnExternalAsec(int installFlags) {
11443        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11444            return false;
11445        }
11446        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11447            return true;
11448        }
11449        return false;
11450    }
11451
11452    /**
11453     * Used during creation of InstallArgs
11454     *
11455     * @param installFlags package installation flags
11456     * @return true if should be installed as forward locked
11457     */
11458    private static boolean installForwardLocked(int installFlags) {
11459        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11460    }
11461
11462    private InstallArgs createInstallArgs(InstallParams params) {
11463        if (params.move != null) {
11464            return new MoveInstallArgs(params);
11465        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11466            return new AsecInstallArgs(params);
11467        } else {
11468            return new FileInstallArgs(params);
11469        }
11470    }
11471
11472    /**
11473     * Create args that describe an existing installed package. Typically used
11474     * when cleaning up old installs, or used as a move source.
11475     */
11476    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11477            String resourcePath, String[] instructionSets) {
11478        final boolean isInAsec;
11479        if (installOnExternalAsec(installFlags)) {
11480            /* Apps on SD card are always in ASEC containers. */
11481            isInAsec = true;
11482        } else if (installForwardLocked(installFlags)
11483                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11484            /*
11485             * Forward-locked apps are only in ASEC containers if they're the
11486             * new style
11487             */
11488            isInAsec = true;
11489        } else {
11490            isInAsec = false;
11491        }
11492
11493        if (isInAsec) {
11494            return new AsecInstallArgs(codePath, instructionSets,
11495                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11496        } else {
11497            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11498        }
11499    }
11500
11501    static abstract class InstallArgs {
11502        /** @see InstallParams#origin */
11503        final OriginInfo origin;
11504        /** @see InstallParams#move */
11505        final MoveInfo move;
11506
11507        final IPackageInstallObserver2 observer;
11508        // Always refers to PackageManager flags only
11509        final int installFlags;
11510        final String installerPackageName;
11511        final String volumeUuid;
11512        final UserHandle user;
11513        final String abiOverride;
11514        final String[] installGrantPermissions;
11515        /** If non-null, drop an async trace when the install completes */
11516        final String traceMethod;
11517        final int traceCookie;
11518
11519        // The list of instruction sets supported by this app. This is currently
11520        // only used during the rmdex() phase to clean up resources. We can get rid of this
11521        // if we move dex files under the common app path.
11522        /* nullable */ String[] instructionSets;
11523
11524        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11525                int installFlags, String installerPackageName, String volumeUuid,
11526                UserHandle user, String[] instructionSets,
11527                String abiOverride, String[] installGrantPermissions,
11528                String traceMethod, int traceCookie) {
11529            this.origin = origin;
11530            this.move = move;
11531            this.installFlags = installFlags;
11532            this.observer = observer;
11533            this.installerPackageName = installerPackageName;
11534            this.volumeUuid = volumeUuid;
11535            this.user = user;
11536            this.instructionSets = instructionSets;
11537            this.abiOverride = abiOverride;
11538            this.installGrantPermissions = installGrantPermissions;
11539            this.traceMethod = traceMethod;
11540            this.traceCookie = traceCookie;
11541        }
11542
11543        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11544        abstract int doPreInstall(int status);
11545
11546        /**
11547         * Rename package into final resting place. All paths on the given
11548         * scanned package should be updated to reflect the rename.
11549         */
11550        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11551        abstract int doPostInstall(int status, int uid);
11552
11553        /** @see PackageSettingBase#codePathString */
11554        abstract String getCodePath();
11555        /** @see PackageSettingBase#resourcePathString */
11556        abstract String getResourcePath();
11557
11558        // Need installer lock especially for dex file removal.
11559        abstract void cleanUpResourcesLI();
11560        abstract boolean doPostDeleteLI(boolean delete);
11561
11562        /**
11563         * Called before the source arguments are copied. This is used mostly
11564         * for MoveParams when it needs to read the source file to put it in the
11565         * destination.
11566         */
11567        int doPreCopy() {
11568            return PackageManager.INSTALL_SUCCEEDED;
11569        }
11570
11571        /**
11572         * Called after the source arguments are copied. This is used mostly for
11573         * MoveParams when it needs to read the source file to put it in the
11574         * destination.
11575         *
11576         * @return
11577         */
11578        int doPostCopy(int uid) {
11579            return PackageManager.INSTALL_SUCCEEDED;
11580        }
11581
11582        protected boolean isFwdLocked() {
11583            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11584        }
11585
11586        protected boolean isExternalAsec() {
11587            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11588        }
11589
11590        protected boolean isEphemeral() {
11591            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11592        }
11593
11594        UserHandle getUser() {
11595            return user;
11596        }
11597    }
11598
11599    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11600        if (!allCodePaths.isEmpty()) {
11601            if (instructionSets == null) {
11602                throw new IllegalStateException("instructionSet == null");
11603            }
11604            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11605            for (String codePath : allCodePaths) {
11606                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11607                    try {
11608                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11609                    } catch (InstallerException ignored) {
11610                    }
11611                }
11612            }
11613        }
11614    }
11615
11616    /**
11617     * Logic to handle installation of non-ASEC applications, including copying
11618     * and renaming logic.
11619     */
11620    class FileInstallArgs extends InstallArgs {
11621        private File codeFile;
11622        private File resourceFile;
11623
11624        // Example topology:
11625        // /data/app/com.example/base.apk
11626        // /data/app/com.example/split_foo.apk
11627        // /data/app/com.example/lib/arm/libfoo.so
11628        // /data/app/com.example/lib/arm64/libfoo.so
11629        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11630
11631        /** New install */
11632        FileInstallArgs(InstallParams params) {
11633            super(params.origin, params.move, params.observer, params.installFlags,
11634                    params.installerPackageName, params.volumeUuid,
11635                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11636                    params.grantedRuntimePermissions,
11637                    params.traceMethod, params.traceCookie);
11638            if (isFwdLocked()) {
11639                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11640            }
11641        }
11642
11643        /** Existing install */
11644        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11645            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11646                    null, null, null, 0);
11647            this.codeFile = (codePath != null) ? new File(codePath) : null;
11648            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11649        }
11650
11651        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11653            try {
11654                return doCopyApk(imcs, temp);
11655            } finally {
11656                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11657            }
11658        }
11659
11660        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11661            if (origin.staged) {
11662                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11663                codeFile = origin.file;
11664                resourceFile = origin.file;
11665                return PackageManager.INSTALL_SUCCEEDED;
11666            }
11667
11668            try {
11669                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11670                final File tempDir =
11671                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11672                codeFile = tempDir;
11673                resourceFile = tempDir;
11674            } catch (IOException e) {
11675                Slog.w(TAG, "Failed to create copy file: " + e);
11676                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11677            }
11678
11679            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11680                @Override
11681                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11682                    if (!FileUtils.isValidExtFilename(name)) {
11683                        throw new IllegalArgumentException("Invalid filename: " + name);
11684                    }
11685                    try {
11686                        final File file = new File(codeFile, name);
11687                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11688                                O_RDWR | O_CREAT, 0644);
11689                        Os.chmod(file.getAbsolutePath(), 0644);
11690                        return new ParcelFileDescriptor(fd);
11691                    } catch (ErrnoException e) {
11692                        throw new RemoteException("Failed to open: " + e.getMessage());
11693                    }
11694                }
11695            };
11696
11697            int ret = PackageManager.INSTALL_SUCCEEDED;
11698            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11699            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11700                Slog.e(TAG, "Failed to copy package");
11701                return ret;
11702            }
11703
11704            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11705            NativeLibraryHelper.Handle handle = null;
11706            try {
11707                handle = NativeLibraryHelper.Handle.create(codeFile);
11708                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11709                        abiOverride);
11710            } catch (IOException e) {
11711                Slog.e(TAG, "Copying native libraries failed", e);
11712                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11713            } finally {
11714                IoUtils.closeQuietly(handle);
11715            }
11716
11717            return ret;
11718        }
11719
11720        int doPreInstall(int status) {
11721            if (status != PackageManager.INSTALL_SUCCEEDED) {
11722                cleanUp();
11723            }
11724            return status;
11725        }
11726
11727        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11728            if (status != PackageManager.INSTALL_SUCCEEDED) {
11729                cleanUp();
11730                return false;
11731            }
11732
11733            final File targetDir = codeFile.getParentFile();
11734            final File beforeCodeFile = codeFile;
11735            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11736
11737            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11738            try {
11739                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11740            } catch (ErrnoException e) {
11741                Slog.w(TAG, "Failed to rename", e);
11742                return false;
11743            }
11744
11745            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11746                Slog.w(TAG, "Failed to restorecon");
11747                return false;
11748            }
11749
11750            // Reflect the rename internally
11751            codeFile = afterCodeFile;
11752            resourceFile = afterCodeFile;
11753
11754            // Reflect the rename in scanned details
11755            pkg.codePath = afterCodeFile.getAbsolutePath();
11756            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11757                    pkg.baseCodePath);
11758            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11759                    pkg.splitCodePaths);
11760
11761            // Reflect the rename in app info
11762            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11763            pkg.applicationInfo.setCodePath(pkg.codePath);
11764            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11765            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11766            pkg.applicationInfo.setResourcePath(pkg.codePath);
11767            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11768            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11769
11770            return true;
11771        }
11772
11773        int doPostInstall(int status, int uid) {
11774            if (status != PackageManager.INSTALL_SUCCEEDED) {
11775                cleanUp();
11776            }
11777            return status;
11778        }
11779
11780        @Override
11781        String getCodePath() {
11782            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11783        }
11784
11785        @Override
11786        String getResourcePath() {
11787            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11788        }
11789
11790        private boolean cleanUp() {
11791            if (codeFile == null || !codeFile.exists()) {
11792                return false;
11793            }
11794
11795            removeCodePathLI(codeFile);
11796
11797            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11798                resourceFile.delete();
11799            }
11800
11801            return true;
11802        }
11803
11804        void cleanUpResourcesLI() {
11805            // Try enumerating all code paths before deleting
11806            List<String> allCodePaths = Collections.EMPTY_LIST;
11807            if (codeFile != null && codeFile.exists()) {
11808                try {
11809                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11810                    allCodePaths = pkg.getAllCodePaths();
11811                } catch (PackageParserException e) {
11812                    // Ignored; we tried our best
11813                }
11814            }
11815
11816            cleanUp();
11817            removeDexFiles(allCodePaths, instructionSets);
11818        }
11819
11820        boolean doPostDeleteLI(boolean delete) {
11821            // XXX err, shouldn't we respect the delete flag?
11822            cleanUpResourcesLI();
11823            return true;
11824        }
11825    }
11826
11827    private boolean isAsecExternal(String cid) {
11828        final String asecPath = PackageHelper.getSdFilesystem(cid);
11829        return !asecPath.startsWith(mAsecInternalPath);
11830    }
11831
11832    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11833            PackageManagerException {
11834        if (copyRet < 0) {
11835            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11836                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11837                throw new PackageManagerException(copyRet, message);
11838            }
11839        }
11840    }
11841
11842    /**
11843     * Extract the MountService "container ID" from the full code path of an
11844     * .apk.
11845     */
11846    static String cidFromCodePath(String fullCodePath) {
11847        int eidx = fullCodePath.lastIndexOf("/");
11848        String subStr1 = fullCodePath.substring(0, eidx);
11849        int sidx = subStr1.lastIndexOf("/");
11850        return subStr1.substring(sidx+1, eidx);
11851    }
11852
11853    /**
11854     * Logic to handle installation of ASEC applications, including copying and
11855     * renaming logic.
11856     */
11857    class AsecInstallArgs extends InstallArgs {
11858        static final String RES_FILE_NAME = "pkg.apk";
11859        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11860
11861        String cid;
11862        String packagePath;
11863        String resourcePath;
11864
11865        /** New install */
11866        AsecInstallArgs(InstallParams params) {
11867            super(params.origin, params.move, params.observer, params.installFlags,
11868                    params.installerPackageName, params.volumeUuid,
11869                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11870                    params.grantedRuntimePermissions,
11871                    params.traceMethod, params.traceCookie);
11872        }
11873
11874        /** Existing install */
11875        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11876                        boolean isExternal, boolean isForwardLocked) {
11877            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11878                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11879                    instructionSets, null, null, null, 0);
11880            // Hackily pretend we're still looking at a full code path
11881            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11882                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11883            }
11884
11885            // Extract cid from fullCodePath
11886            int eidx = fullCodePath.lastIndexOf("/");
11887            String subStr1 = fullCodePath.substring(0, eidx);
11888            int sidx = subStr1.lastIndexOf("/");
11889            cid = subStr1.substring(sidx+1, eidx);
11890            setMountPath(subStr1);
11891        }
11892
11893        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11894            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11895                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11896                    instructionSets, null, null, null, 0);
11897            this.cid = cid;
11898            setMountPath(PackageHelper.getSdDir(cid));
11899        }
11900
11901        void createCopyFile() {
11902            cid = mInstallerService.allocateExternalStageCidLegacy();
11903        }
11904
11905        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11906            if (origin.staged && origin.cid != null) {
11907                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11908                cid = origin.cid;
11909                setMountPath(PackageHelper.getSdDir(cid));
11910                return PackageManager.INSTALL_SUCCEEDED;
11911            }
11912
11913            if (temp) {
11914                createCopyFile();
11915            } else {
11916                /*
11917                 * Pre-emptively destroy the container since it's destroyed if
11918                 * copying fails due to it existing anyway.
11919                 */
11920                PackageHelper.destroySdDir(cid);
11921            }
11922
11923            final String newMountPath = imcs.copyPackageToContainer(
11924                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11925                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11926
11927            if (newMountPath != null) {
11928                setMountPath(newMountPath);
11929                return PackageManager.INSTALL_SUCCEEDED;
11930            } else {
11931                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11932            }
11933        }
11934
11935        @Override
11936        String getCodePath() {
11937            return packagePath;
11938        }
11939
11940        @Override
11941        String getResourcePath() {
11942            return resourcePath;
11943        }
11944
11945        int doPreInstall(int status) {
11946            if (status != PackageManager.INSTALL_SUCCEEDED) {
11947                // Destroy container
11948                PackageHelper.destroySdDir(cid);
11949            } else {
11950                boolean mounted = PackageHelper.isContainerMounted(cid);
11951                if (!mounted) {
11952                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11953                            Process.SYSTEM_UID);
11954                    if (newMountPath != null) {
11955                        setMountPath(newMountPath);
11956                    } else {
11957                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11958                    }
11959                }
11960            }
11961            return status;
11962        }
11963
11964        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11965            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11966            String newMountPath = null;
11967            if (PackageHelper.isContainerMounted(cid)) {
11968                // Unmount the container
11969                if (!PackageHelper.unMountSdDir(cid)) {
11970                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11971                    return false;
11972                }
11973            }
11974            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11975                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11976                        " which might be stale. Will try to clean up.");
11977                // Clean up the stale container and proceed to recreate.
11978                if (!PackageHelper.destroySdDir(newCacheId)) {
11979                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11980                    return false;
11981                }
11982                // Successfully cleaned up stale container. Try to rename again.
11983                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11984                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11985                            + " inspite of cleaning it up.");
11986                    return false;
11987                }
11988            }
11989            if (!PackageHelper.isContainerMounted(newCacheId)) {
11990                Slog.w(TAG, "Mounting container " + newCacheId);
11991                newMountPath = PackageHelper.mountSdDir(newCacheId,
11992                        getEncryptKey(), Process.SYSTEM_UID);
11993            } else {
11994                newMountPath = PackageHelper.getSdDir(newCacheId);
11995            }
11996            if (newMountPath == null) {
11997                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11998                return false;
11999            }
12000            Log.i(TAG, "Succesfully renamed " + cid +
12001                    " to " + newCacheId +
12002                    " at new path: " + newMountPath);
12003            cid = newCacheId;
12004
12005            final File beforeCodeFile = new File(packagePath);
12006            setMountPath(newMountPath);
12007            final File afterCodeFile = new File(packagePath);
12008
12009            // Reflect the rename in scanned details
12010            pkg.codePath = afterCodeFile.getAbsolutePath();
12011            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12012                    pkg.baseCodePath);
12013            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12014                    pkg.splitCodePaths);
12015
12016            // Reflect the rename in app info
12017            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12018            pkg.applicationInfo.setCodePath(pkg.codePath);
12019            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12020            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12021            pkg.applicationInfo.setResourcePath(pkg.codePath);
12022            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12023            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12024
12025            return true;
12026        }
12027
12028        private void setMountPath(String mountPath) {
12029            final File mountFile = new File(mountPath);
12030
12031            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12032            if (monolithicFile.exists()) {
12033                packagePath = monolithicFile.getAbsolutePath();
12034                if (isFwdLocked()) {
12035                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12036                } else {
12037                    resourcePath = packagePath;
12038                }
12039            } else {
12040                packagePath = mountFile.getAbsolutePath();
12041                resourcePath = packagePath;
12042            }
12043        }
12044
12045        int doPostInstall(int status, int uid) {
12046            if (status != PackageManager.INSTALL_SUCCEEDED) {
12047                cleanUp();
12048            } else {
12049                final int groupOwner;
12050                final String protectedFile;
12051                if (isFwdLocked()) {
12052                    groupOwner = UserHandle.getSharedAppGid(uid);
12053                    protectedFile = RES_FILE_NAME;
12054                } else {
12055                    groupOwner = -1;
12056                    protectedFile = null;
12057                }
12058
12059                if (uid < Process.FIRST_APPLICATION_UID
12060                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12061                    Slog.e(TAG, "Failed to finalize " + cid);
12062                    PackageHelper.destroySdDir(cid);
12063                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12064                }
12065
12066                boolean mounted = PackageHelper.isContainerMounted(cid);
12067                if (!mounted) {
12068                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12069                }
12070            }
12071            return status;
12072        }
12073
12074        private void cleanUp() {
12075            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12076
12077            // Destroy secure container
12078            PackageHelper.destroySdDir(cid);
12079        }
12080
12081        private List<String> getAllCodePaths() {
12082            final File codeFile = new File(getCodePath());
12083            if (codeFile != null && codeFile.exists()) {
12084                try {
12085                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12086                    return pkg.getAllCodePaths();
12087                } catch (PackageParserException e) {
12088                    // Ignored; we tried our best
12089                }
12090            }
12091            return Collections.EMPTY_LIST;
12092        }
12093
12094        void cleanUpResourcesLI() {
12095            // Enumerate all code paths before deleting
12096            cleanUpResourcesLI(getAllCodePaths());
12097        }
12098
12099        private void cleanUpResourcesLI(List<String> allCodePaths) {
12100            cleanUp();
12101            removeDexFiles(allCodePaths, instructionSets);
12102        }
12103
12104        String getPackageName() {
12105            return getAsecPackageName(cid);
12106        }
12107
12108        boolean doPostDeleteLI(boolean delete) {
12109            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12110            final List<String> allCodePaths = getAllCodePaths();
12111            boolean mounted = PackageHelper.isContainerMounted(cid);
12112            if (mounted) {
12113                // Unmount first
12114                if (PackageHelper.unMountSdDir(cid)) {
12115                    mounted = false;
12116                }
12117            }
12118            if (!mounted && delete) {
12119                cleanUpResourcesLI(allCodePaths);
12120            }
12121            return !mounted;
12122        }
12123
12124        @Override
12125        int doPreCopy() {
12126            if (isFwdLocked()) {
12127                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12128                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12129                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12130                }
12131            }
12132
12133            return PackageManager.INSTALL_SUCCEEDED;
12134        }
12135
12136        @Override
12137        int doPostCopy(int uid) {
12138            if (isFwdLocked()) {
12139                if (uid < Process.FIRST_APPLICATION_UID
12140                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12141                                RES_FILE_NAME)) {
12142                    Slog.e(TAG, "Failed to finalize " + cid);
12143                    PackageHelper.destroySdDir(cid);
12144                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12145                }
12146            }
12147
12148            return PackageManager.INSTALL_SUCCEEDED;
12149        }
12150    }
12151
12152    /**
12153     * Logic to handle movement of existing installed applications.
12154     */
12155    class MoveInstallArgs extends InstallArgs {
12156        private File codeFile;
12157        private File resourceFile;
12158
12159        /** New install */
12160        MoveInstallArgs(InstallParams params) {
12161            super(params.origin, params.move, params.observer, params.installFlags,
12162                    params.installerPackageName, params.volumeUuid,
12163                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12164                    params.grantedRuntimePermissions,
12165                    params.traceMethod, params.traceCookie);
12166        }
12167
12168        int copyApk(IMediaContainerService imcs, boolean temp) {
12169            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12170                    + move.fromUuid + " to " + move.toUuid);
12171            synchronized (mInstaller) {
12172                try {
12173                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12174                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12175                } catch (InstallerException e) {
12176                    Slog.w(TAG, "Failed to move app", e);
12177                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12178                }
12179            }
12180
12181            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12182            resourceFile = codeFile;
12183            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12184
12185            return PackageManager.INSTALL_SUCCEEDED;
12186        }
12187
12188        int doPreInstall(int status) {
12189            if (status != PackageManager.INSTALL_SUCCEEDED) {
12190                cleanUp(move.toUuid);
12191            }
12192            return status;
12193        }
12194
12195        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12196            if (status != PackageManager.INSTALL_SUCCEEDED) {
12197                cleanUp(move.toUuid);
12198                return false;
12199            }
12200
12201            // Reflect the move in app info
12202            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12203            pkg.applicationInfo.setCodePath(pkg.codePath);
12204            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12205            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12206            pkg.applicationInfo.setResourcePath(pkg.codePath);
12207            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12208            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12209
12210            return true;
12211        }
12212
12213        int doPostInstall(int status, int uid) {
12214            if (status == PackageManager.INSTALL_SUCCEEDED) {
12215                cleanUp(move.fromUuid);
12216            } else {
12217                cleanUp(move.toUuid);
12218            }
12219            return status;
12220        }
12221
12222        @Override
12223        String getCodePath() {
12224            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12225        }
12226
12227        @Override
12228        String getResourcePath() {
12229            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12230        }
12231
12232        private boolean cleanUp(String volumeUuid) {
12233            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12234                    move.dataAppName);
12235            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12236            synchronized (mInstallLock) {
12237                // Clean up both app data and code
12238                removeDataDirsLI(volumeUuid, move.packageName);
12239                removeCodePathLI(codeFile);
12240            }
12241            return true;
12242        }
12243
12244        void cleanUpResourcesLI() {
12245            throw new UnsupportedOperationException();
12246        }
12247
12248        boolean doPostDeleteLI(boolean delete) {
12249            throw new UnsupportedOperationException();
12250        }
12251    }
12252
12253    static String getAsecPackageName(String packageCid) {
12254        int idx = packageCid.lastIndexOf("-");
12255        if (idx == -1) {
12256            return packageCid;
12257        }
12258        return packageCid.substring(0, idx);
12259    }
12260
12261    // Utility method used to create code paths based on package name and available index.
12262    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12263        String idxStr = "";
12264        int idx = 1;
12265        // Fall back to default value of idx=1 if prefix is not
12266        // part of oldCodePath
12267        if (oldCodePath != null) {
12268            String subStr = oldCodePath;
12269            // Drop the suffix right away
12270            if (suffix != null && subStr.endsWith(suffix)) {
12271                subStr = subStr.substring(0, subStr.length() - suffix.length());
12272            }
12273            // If oldCodePath already contains prefix find out the
12274            // ending index to either increment or decrement.
12275            int sidx = subStr.lastIndexOf(prefix);
12276            if (sidx != -1) {
12277                subStr = subStr.substring(sidx + prefix.length());
12278                if (subStr != null) {
12279                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12280                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12281                    }
12282                    try {
12283                        idx = Integer.parseInt(subStr);
12284                        if (idx <= 1) {
12285                            idx++;
12286                        } else {
12287                            idx--;
12288                        }
12289                    } catch(NumberFormatException e) {
12290                    }
12291                }
12292            }
12293        }
12294        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12295        return prefix + idxStr;
12296    }
12297
12298    private File getNextCodePath(File targetDir, String packageName) {
12299        int suffix = 1;
12300        File result;
12301        do {
12302            result = new File(targetDir, packageName + "-" + suffix);
12303            suffix++;
12304        } while (result.exists());
12305        return result;
12306    }
12307
12308    // Utility method that returns the relative package path with respect
12309    // to the installation directory. Like say for /data/data/com.test-1.apk
12310    // string com.test-1 is returned.
12311    static String deriveCodePathName(String codePath) {
12312        if (codePath == null) {
12313            return null;
12314        }
12315        final File codeFile = new File(codePath);
12316        final String name = codeFile.getName();
12317        if (codeFile.isDirectory()) {
12318            return name;
12319        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12320            final int lastDot = name.lastIndexOf('.');
12321            return name.substring(0, lastDot);
12322        } else {
12323            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12324            return null;
12325        }
12326    }
12327
12328    static class PackageInstalledInfo {
12329        String name;
12330        int uid;
12331        // The set of users that originally had this package installed.
12332        int[] origUsers;
12333        // The set of users that now have this package installed.
12334        int[] newUsers;
12335        PackageParser.Package pkg;
12336        int returnCode;
12337        String returnMsg;
12338        PackageRemovedInfo removedInfo;
12339
12340        public void setError(int code, String msg) {
12341            returnCode = code;
12342            returnMsg = msg;
12343            Slog.w(TAG, msg);
12344        }
12345
12346        public void setError(String msg, PackageParserException e) {
12347            returnCode = e.error;
12348            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12349            Slog.w(TAG, msg, e);
12350        }
12351
12352        public void setError(String msg, PackageManagerException e) {
12353            returnCode = e.error;
12354            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12355            Slog.w(TAG, msg, e);
12356        }
12357
12358        // In some error cases we want to convey more info back to the observer
12359        String origPackage;
12360        String origPermission;
12361    }
12362
12363    /*
12364     * Install a non-existing package.
12365     */
12366    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12367            UserHandle user, String installerPackageName, String volumeUuid,
12368            PackageInstalledInfo res) {
12369        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12370
12371        // Remember this for later, in case we need to rollback this install
12372        String pkgName = pkg.packageName;
12373
12374        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12375        // TODO: b/23350563
12376        final boolean dataDirExists = Environment
12377                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12378
12379        synchronized(mPackages) {
12380            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12381                // A package with the same name is already installed, though
12382                // it has been renamed to an older name.  The package we
12383                // are trying to install should be installed as an update to
12384                // the existing one, but that has not been requested, so bail.
12385                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12386                        + " without first uninstalling package running as "
12387                        + mSettings.mRenamedPackages.get(pkgName));
12388                return;
12389            }
12390            if (mPackages.containsKey(pkgName)) {
12391                // Don't allow installation over an existing package with the same name.
12392                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12393                        + " without first uninstalling.");
12394                return;
12395            }
12396        }
12397
12398        try {
12399            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12400                    System.currentTimeMillis(), user);
12401
12402            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12403            prepareAppDataAfterInstall(newPackage);
12404
12405            // delete the partially installed application. the data directory will have to be
12406            // restored if it was already existing
12407            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12408                // remove package from internal structures.  Note that we want deletePackageX to
12409                // delete the package data and cache directories that it created in
12410                // scanPackageLocked, unless those directories existed before we even tried to
12411                // install.
12412                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12413                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12414                                res.removedInfo, true);
12415            }
12416
12417        } catch (PackageManagerException e) {
12418            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12419        }
12420
12421        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12422    }
12423
12424    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12425        // Can't rotate keys during boot or if sharedUser.
12426        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12427                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12428            return false;
12429        }
12430        // app is using upgradeKeySets; make sure all are valid
12431        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12432        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12433        for (int i = 0; i < upgradeKeySets.length; i++) {
12434            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12435                Slog.wtf(TAG, "Package "
12436                         + (oldPs.name != null ? oldPs.name : "<null>")
12437                         + " contains upgrade-key-set reference to unknown key-set: "
12438                         + upgradeKeySets[i]
12439                         + " reverting to signatures check.");
12440                return false;
12441            }
12442        }
12443        return true;
12444    }
12445
12446    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12447        // Upgrade keysets are being used.  Determine if new package has a superset of the
12448        // required keys.
12449        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12450        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12451        for (int i = 0; i < upgradeKeySets.length; i++) {
12452            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12453            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12454                return true;
12455            }
12456        }
12457        return false;
12458    }
12459
12460    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12461            UserHandle user, String installerPackageName, String volumeUuid,
12462            PackageInstalledInfo res) {
12463        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12464
12465        final PackageParser.Package oldPackage;
12466        final String pkgName = pkg.packageName;
12467        final int[] allUsers;
12468        final boolean[] perUserInstalled;
12469
12470        // First find the old package info and check signatures
12471        synchronized(mPackages) {
12472            oldPackage = mPackages.get(pkgName);
12473            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12474            if (isEphemeral && !oldIsEphemeral) {
12475                // can't downgrade from full to ephemeral
12476                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12477                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12478                return;
12479            }
12480            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12481            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12482            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12483                if(!checkUpgradeKeySetLP(ps, pkg)) {
12484                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12485                            "New package not signed by keys specified by upgrade-keysets: "
12486                            + pkgName);
12487                    return;
12488                }
12489            } else {
12490                // default to original signature matching
12491                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12492                    != PackageManager.SIGNATURE_MATCH) {
12493                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12494                            "New package has a different signature: " + pkgName);
12495                    return;
12496                }
12497            }
12498
12499            // In case of rollback, remember per-user/profile install state
12500            allUsers = sUserManager.getUserIds();
12501            perUserInstalled = new boolean[allUsers.length];
12502            for (int i = 0; i < allUsers.length; i++) {
12503                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12504            }
12505        }
12506
12507        boolean sysPkg = (isSystemApp(oldPackage));
12508        if (sysPkg) {
12509            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12510                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12511        } else {
12512            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12513                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12514        }
12515    }
12516
12517    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12518            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12519            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12520            String volumeUuid, PackageInstalledInfo res) {
12521        String pkgName = deletedPackage.packageName;
12522        boolean deletedPkg = true;
12523        boolean updatedSettings = false;
12524
12525        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12526                + deletedPackage);
12527        long origUpdateTime;
12528        if (pkg.mExtras != null) {
12529            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12530        } else {
12531            origUpdateTime = 0;
12532        }
12533
12534        // First delete the existing package while retaining the data directory
12535        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12536                res.removedInfo, true)) {
12537            // If the existing package wasn't successfully deleted
12538            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12539            deletedPkg = false;
12540        } else {
12541            // Successfully deleted the old package; proceed with replace.
12542
12543            // If deleted package lived in a container, give users a chance to
12544            // relinquish resources before killing.
12545            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12546                if (DEBUG_INSTALL) {
12547                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12548                }
12549                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12550                final ArrayList<String> pkgList = new ArrayList<String>(1);
12551                pkgList.add(deletedPackage.applicationInfo.packageName);
12552                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12553            }
12554
12555            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12556            try {
12557                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12558                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12559                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12560                        perUserInstalled, res, user);
12561                prepareAppDataAfterInstall(newPackage);
12562                updatedSettings = true;
12563            } catch (PackageManagerException e) {
12564                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12565            }
12566        }
12567
12568        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12569            // remove package from internal structures.  Note that we want deletePackageX to
12570            // delete the package data and cache directories that it created in
12571            // scanPackageLocked, unless those directories existed before we even tried to
12572            // install.
12573            if(updatedSettings) {
12574                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12575                deletePackageLI(
12576                        pkgName, null, true, allUsers, perUserInstalled,
12577                        PackageManager.DELETE_KEEP_DATA,
12578                                res.removedInfo, true);
12579            }
12580            // Since we failed to install the new package we need to restore the old
12581            // package that we deleted.
12582            if (deletedPkg) {
12583                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12584                File restoreFile = new File(deletedPackage.codePath);
12585                // Parse old package
12586                boolean oldExternal = isExternal(deletedPackage);
12587                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12588                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12589                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12590                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12591                try {
12592                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12593                            null);
12594                } catch (PackageManagerException e) {
12595                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12596                            + e.getMessage());
12597                    return;
12598                }
12599                // Restore of old package succeeded. Update permissions.
12600                // writer
12601                synchronized (mPackages) {
12602                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12603                            UPDATE_PERMISSIONS_ALL);
12604                    // can downgrade to reader
12605                    mSettings.writeLPr();
12606                }
12607                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12608            }
12609        }
12610    }
12611
12612    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12613            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12614            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12615            String volumeUuid, PackageInstalledInfo res) {
12616        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12617                + ", old=" + deletedPackage);
12618        boolean disabledSystem = false;
12619        boolean updatedSettings = false;
12620        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12621        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12622                != 0) {
12623            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12624        }
12625        String packageName = deletedPackage.packageName;
12626        if (packageName == null) {
12627            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12628                    "Attempt to delete null packageName.");
12629            return;
12630        }
12631        PackageParser.Package oldPkg;
12632        PackageSetting oldPkgSetting;
12633        // reader
12634        synchronized (mPackages) {
12635            oldPkg = mPackages.get(packageName);
12636            oldPkgSetting = mSettings.mPackages.get(packageName);
12637            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12638                    (oldPkgSetting == null)) {
12639                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12640                        "Couldn't find package " + packageName + " information");
12641                return;
12642            }
12643        }
12644
12645        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12646
12647        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12648        res.removedInfo.removedPackage = packageName;
12649        // Remove existing system package
12650        removePackageLI(oldPkgSetting, true);
12651        // writer
12652        synchronized (mPackages) {
12653            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12654            if (!disabledSystem && deletedPackage != null) {
12655                // We didn't need to disable the .apk as a current system package,
12656                // which means we are replacing another update that is already
12657                // installed.  We need to make sure to delete the older one's .apk.
12658                res.removedInfo.args = createInstallArgsForExisting(0,
12659                        deletedPackage.applicationInfo.getCodePath(),
12660                        deletedPackage.applicationInfo.getResourcePath(),
12661                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12662            } else {
12663                res.removedInfo.args = null;
12664            }
12665        }
12666
12667        // Successfully disabled the old package. Now proceed with re-installation
12668        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12669
12670        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12671        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12672
12673        PackageParser.Package newPackage = null;
12674        try {
12675            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12676            if (newPackage.mExtras != null) {
12677                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12678                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12679                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12680
12681                // is the update attempting to change shared user? that isn't going to work...
12682                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12683                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12684                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12685                            + " to " + newPkgSetting.sharedUser);
12686                    updatedSettings = true;
12687                }
12688            }
12689
12690            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12691                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12692                        perUserInstalled, res, user);
12693                prepareAppDataAfterInstall(newPackage);
12694                updatedSettings = true;
12695            }
12696
12697        } catch (PackageManagerException e) {
12698            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12699        }
12700
12701        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12702            // Re installation failed. Restore old information
12703            // Remove new pkg information
12704            if (newPackage != null) {
12705                removeInstalledPackageLI(newPackage, true);
12706            }
12707            // Add back the old system package
12708            try {
12709                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12710            } catch (PackageManagerException e) {
12711                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12712            }
12713            // Restore the old system information in Settings
12714            synchronized (mPackages) {
12715                if (disabledSystem) {
12716                    mSettings.enableSystemPackageLPw(packageName);
12717                }
12718                if (updatedSettings) {
12719                    mSettings.setInstallerPackageName(packageName,
12720                            oldPkgSetting.installerPackageName);
12721                }
12722                mSettings.writeLPr();
12723            }
12724        }
12725    }
12726
12727    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12728        // Collect all used permissions in the UID
12729        ArraySet<String> usedPermissions = new ArraySet<>();
12730        final int packageCount = su.packages.size();
12731        for (int i = 0; i < packageCount; i++) {
12732            PackageSetting ps = su.packages.valueAt(i);
12733            if (ps.pkg == null) {
12734                continue;
12735            }
12736            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12737            for (int j = 0; j < requestedPermCount; j++) {
12738                String permission = ps.pkg.requestedPermissions.get(j);
12739                BasePermission bp = mSettings.mPermissions.get(permission);
12740                if (bp != null) {
12741                    usedPermissions.add(permission);
12742                }
12743            }
12744        }
12745
12746        PermissionsState permissionsState = su.getPermissionsState();
12747        // Prune install permissions
12748        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12749        final int installPermCount = installPermStates.size();
12750        for (int i = installPermCount - 1; i >= 0;  i--) {
12751            PermissionState permissionState = installPermStates.get(i);
12752            if (!usedPermissions.contains(permissionState.getName())) {
12753                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12754                if (bp != null) {
12755                    permissionsState.revokeInstallPermission(bp);
12756                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12757                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12758                }
12759            }
12760        }
12761
12762        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12763
12764        // Prune runtime permissions
12765        for (int userId : allUserIds) {
12766            List<PermissionState> runtimePermStates = permissionsState
12767                    .getRuntimePermissionStates(userId);
12768            final int runtimePermCount = runtimePermStates.size();
12769            for (int i = runtimePermCount - 1; i >= 0; i--) {
12770                PermissionState permissionState = runtimePermStates.get(i);
12771                if (!usedPermissions.contains(permissionState.getName())) {
12772                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12773                    if (bp != null) {
12774                        permissionsState.revokeRuntimePermission(bp, userId);
12775                        permissionsState.updatePermissionFlags(bp, userId,
12776                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12777                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12778                                runtimePermissionChangedUserIds, userId);
12779                    }
12780                }
12781            }
12782        }
12783
12784        return runtimePermissionChangedUserIds;
12785    }
12786
12787    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12788            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12789            UserHandle user) {
12790        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12791
12792        String pkgName = newPackage.packageName;
12793        synchronized (mPackages) {
12794            //write settings. the installStatus will be incomplete at this stage.
12795            //note that the new package setting would have already been
12796            //added to mPackages. It hasn't been persisted yet.
12797            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12798            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12799            mSettings.writeLPr();
12800            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12801        }
12802
12803        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12804        synchronized (mPackages) {
12805            updatePermissionsLPw(newPackage.packageName, newPackage,
12806                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12807                            ? UPDATE_PERMISSIONS_ALL : 0));
12808            // For system-bundled packages, we assume that installing an upgraded version
12809            // of the package implies that the user actually wants to run that new code,
12810            // so we enable the package.
12811            PackageSetting ps = mSettings.mPackages.get(pkgName);
12812            if (ps != null) {
12813                if (isSystemApp(newPackage)) {
12814                    // NB: implicit assumption that system package upgrades apply to all users
12815                    if (DEBUG_INSTALL) {
12816                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12817                    }
12818                    if (res.origUsers != null) {
12819                        for (int userHandle : res.origUsers) {
12820                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12821                                    userHandle, installerPackageName);
12822                        }
12823                    }
12824                    // Also convey the prior install/uninstall state
12825                    if (allUsers != null && perUserInstalled != null) {
12826                        for (int i = 0; i < allUsers.length; i++) {
12827                            if (DEBUG_INSTALL) {
12828                                Slog.d(TAG, "    user " + allUsers[i]
12829                                        + " => " + perUserInstalled[i]);
12830                            }
12831                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12832                        }
12833                        // these install state changes will be persisted in the
12834                        // upcoming call to mSettings.writeLPr().
12835                    }
12836                }
12837                // It's implied that when a user requests installation, they want the app to be
12838                // installed and enabled.
12839                int userId = user.getIdentifier();
12840                if (userId != UserHandle.USER_ALL) {
12841                    ps.setInstalled(true, userId);
12842                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12843                }
12844            }
12845            res.name = pkgName;
12846            res.uid = newPackage.applicationInfo.uid;
12847            res.pkg = newPackage;
12848            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12849            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12850            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12851            //to update install status
12852            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12853            mSettings.writeLPr();
12854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12855        }
12856
12857        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12858    }
12859
12860    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12861        try {
12862            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12863            installPackageLI(args, res);
12864        } finally {
12865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12866        }
12867    }
12868
12869    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12870        final int installFlags = args.installFlags;
12871        final String installerPackageName = args.installerPackageName;
12872        final String volumeUuid = args.volumeUuid;
12873        final File tmpPackageFile = new File(args.getCodePath());
12874        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12875        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12876                || (args.volumeUuid != null));
12877        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12878        boolean replace = false;
12879        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12880        if (args.move != null) {
12881            // moving a complete application; perfom an initial scan on the new install location
12882            scanFlags |= SCAN_INITIAL;
12883        }
12884        // Result object to be returned
12885        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12886
12887        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12888
12889        // Sanity check
12890        if (ephemeral && (forwardLocked || onExternal)) {
12891            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12892                    + " external=" + onExternal);
12893            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12894            return;
12895        }
12896
12897        // Retrieve PackageSettings and parse package
12898        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12899                | PackageParser.PARSE_ENFORCE_CODE
12900                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12901                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12902                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12903        PackageParser pp = new PackageParser();
12904        pp.setSeparateProcesses(mSeparateProcesses);
12905        pp.setDisplayMetrics(mMetrics);
12906
12907        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12908        final PackageParser.Package pkg;
12909        try {
12910            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12911        } catch (PackageParserException e) {
12912            res.setError("Failed parse during installPackageLI", e);
12913            return;
12914        } finally {
12915            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12916        }
12917
12918        // If package doesn't declare API override, mark that we have an install
12919        // time CPU ABI override.
12920        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
12921            pkg.cpuAbiOverride = args.abiOverride;
12922        }
12923
12924        String pkgName = res.name = pkg.packageName;
12925        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12926            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12927                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12928                return;
12929            }
12930        }
12931
12932        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12933        try {
12934            pp.collectCertificates(pkg, parseFlags);
12935        } catch (PackageParserException e) {
12936            res.setError("Failed collect during installPackageLI", e);
12937            return;
12938        } finally {
12939            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12940        }
12941
12942        // Get rid of all references to package scan path via parser.
12943        pp = null;
12944        String oldCodePath = null;
12945        boolean systemApp = false;
12946        synchronized (mPackages) {
12947            // Check if installing already existing package
12948            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12949                String oldName = mSettings.mRenamedPackages.get(pkgName);
12950                if (pkg.mOriginalPackages != null
12951                        && pkg.mOriginalPackages.contains(oldName)
12952                        && mPackages.containsKey(oldName)) {
12953                    // This package is derived from an original package,
12954                    // and this device has been updating from that original
12955                    // name.  We must continue using the original name, so
12956                    // rename the new package here.
12957                    pkg.setPackageName(oldName);
12958                    pkgName = pkg.packageName;
12959                    replace = true;
12960                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12961                            + oldName + " pkgName=" + pkgName);
12962                } else if (mPackages.containsKey(pkgName)) {
12963                    // This package, under its official name, already exists
12964                    // on the device; we should replace it.
12965                    replace = true;
12966                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12967                }
12968
12969                // Prevent apps opting out from runtime permissions
12970                if (replace) {
12971                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12972                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12973                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12974                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12975                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12976                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12977                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12978                                        + " doesn't support runtime permissions but the old"
12979                                        + " target SDK " + oldTargetSdk + " does.");
12980                        return;
12981                    }
12982                }
12983            }
12984
12985            PackageSetting ps = mSettings.mPackages.get(pkgName);
12986            if (ps != null) {
12987                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12988
12989                // Quick sanity check that we're signed correctly if updating;
12990                // we'll check this again later when scanning, but we want to
12991                // bail early here before tripping over redefined permissions.
12992                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12993                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12994                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12995                                + pkg.packageName + " upgrade keys do not match the "
12996                                + "previously installed version");
12997                        return;
12998                    }
12999                } else {
13000                    try {
13001                        verifySignaturesLP(ps, pkg);
13002                    } catch (PackageManagerException e) {
13003                        res.setError(e.error, e.getMessage());
13004                        return;
13005                    }
13006                }
13007
13008                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13009                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13010                    systemApp = (ps.pkg.applicationInfo.flags &
13011                            ApplicationInfo.FLAG_SYSTEM) != 0;
13012                }
13013                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13014            }
13015
13016            // Check whether the newly-scanned package wants to define an already-defined perm
13017            int N = pkg.permissions.size();
13018            for (int i = N-1; i >= 0; i--) {
13019                PackageParser.Permission perm = pkg.permissions.get(i);
13020                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13021                if (bp != null) {
13022                    // If the defining package is signed with our cert, it's okay.  This
13023                    // also includes the "updating the same package" case, of course.
13024                    // "updating same package" could also involve key-rotation.
13025                    final boolean sigsOk;
13026                    if (bp.sourcePackage.equals(pkg.packageName)
13027                            && (bp.packageSetting instanceof PackageSetting)
13028                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13029                                    scanFlags))) {
13030                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13031                    } else {
13032                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13033                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13034                    }
13035                    if (!sigsOk) {
13036                        // If the owning package is the system itself, we log but allow
13037                        // install to proceed; we fail the install on all other permission
13038                        // redefinitions.
13039                        if (!bp.sourcePackage.equals("android")) {
13040                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13041                                    + pkg.packageName + " attempting to redeclare permission "
13042                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13043                            res.origPermission = perm.info.name;
13044                            res.origPackage = bp.sourcePackage;
13045                            return;
13046                        } else {
13047                            Slog.w(TAG, "Package " + pkg.packageName
13048                                    + " attempting to redeclare system permission "
13049                                    + perm.info.name + "; ignoring new declaration");
13050                            pkg.permissions.remove(i);
13051                        }
13052                    }
13053                }
13054            }
13055
13056        }
13057
13058        if (systemApp) {
13059            if (onExternal) {
13060                // Abort update; system app can't be replaced with app on sdcard
13061                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13062                        "Cannot install updates to system apps on sdcard");
13063                return;
13064            } else if (ephemeral) {
13065                // Abort update; system app can't be replaced with an ephemeral app
13066                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13067                        "Cannot update a system app with an ephemeral app");
13068                return;
13069            }
13070        }
13071
13072        if (args.move != null) {
13073            // We did an in-place move, so dex is ready to roll
13074            scanFlags |= SCAN_NO_DEX;
13075            scanFlags |= SCAN_MOVE;
13076
13077            synchronized (mPackages) {
13078                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13079                if (ps == null) {
13080                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13081                            "Missing settings for moved package " + pkgName);
13082                }
13083
13084                // We moved the entire application as-is, so bring over the
13085                // previously derived ABI information.
13086                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13087                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13088            }
13089
13090        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13091            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13092            scanFlags |= SCAN_NO_DEX;
13093
13094            try {
13095                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13096                    args.abiOverride : pkg.cpuAbiOverride);
13097                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13098                        true /* extract libs */);
13099            } catch (PackageManagerException pme) {
13100                Slog.e(TAG, "Error deriving application ABI", pme);
13101                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13102                return;
13103            }
13104
13105            // Extract package to save the VM unzipping the APK in memory during
13106            // launch. Only do this if profile-guided compilation is enabled because
13107            // otherwise BackgroundDexOptService will not dexopt the package later.
13108            if (mUseJitProfiles) {
13109                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13110                // Do not run PackageDexOptimizer through the local performDexOpt
13111                // method because `pkg` is not in `mPackages` yet.
13112                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13113                        false /* useProfiles */, true /* extractOnly */);
13114                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13115                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13116                    String msg = "Extracking package failed for " + pkgName;
13117                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13118                    return;
13119                }
13120            }
13121        }
13122
13123        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13124            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13125            return;
13126        }
13127
13128        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13129
13130        if (replace) {
13131            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13132                    installerPackageName, volumeUuid, res);
13133        } else {
13134            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13135                    args.user, installerPackageName, volumeUuid, res);
13136        }
13137        synchronized (mPackages) {
13138            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13139            if (ps != null) {
13140                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13141            }
13142        }
13143    }
13144
13145    private void startIntentFilterVerifications(int userId, boolean replacing,
13146            PackageParser.Package pkg) {
13147        if (mIntentFilterVerifierComponent == null) {
13148            Slog.w(TAG, "No IntentFilter verification will not be done as "
13149                    + "there is no IntentFilterVerifier available!");
13150            return;
13151        }
13152
13153        final int verifierUid = getPackageUid(
13154                mIntentFilterVerifierComponent.getPackageName(),
13155                MATCH_DEBUG_TRIAGED_MISSING,
13156                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13157
13158        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13159        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13160        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13161        mHandler.sendMessage(msg);
13162    }
13163
13164    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13165            PackageParser.Package pkg) {
13166        int size = pkg.activities.size();
13167        if (size == 0) {
13168            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13169                    "No activity, so no need to verify any IntentFilter!");
13170            return;
13171        }
13172
13173        final boolean hasDomainURLs = hasDomainURLs(pkg);
13174        if (!hasDomainURLs) {
13175            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13176                    "No domain URLs, so no need to verify any IntentFilter!");
13177            return;
13178        }
13179
13180        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13181                + " if any IntentFilter from the " + size
13182                + " Activities needs verification ...");
13183
13184        int count = 0;
13185        final String packageName = pkg.packageName;
13186
13187        synchronized (mPackages) {
13188            // If this is a new install and we see that we've already run verification for this
13189            // package, we have nothing to do: it means the state was restored from backup.
13190            if (!replacing) {
13191                IntentFilterVerificationInfo ivi =
13192                        mSettings.getIntentFilterVerificationLPr(packageName);
13193                if (ivi != null) {
13194                    if (DEBUG_DOMAIN_VERIFICATION) {
13195                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13196                                + ivi.getStatusString());
13197                    }
13198                    return;
13199                }
13200            }
13201
13202            // If any filters need to be verified, then all need to be.
13203            boolean needToVerify = false;
13204            for (PackageParser.Activity a : pkg.activities) {
13205                for (ActivityIntentInfo filter : a.intents) {
13206                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13207                        if (DEBUG_DOMAIN_VERIFICATION) {
13208                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13209                        }
13210                        needToVerify = true;
13211                        break;
13212                    }
13213                }
13214            }
13215
13216            if (needToVerify) {
13217                final int verificationId = mIntentFilterVerificationToken++;
13218                for (PackageParser.Activity a : pkg.activities) {
13219                    for (ActivityIntentInfo filter : a.intents) {
13220                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13221                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13222                                    "Verification needed for IntentFilter:" + filter.toString());
13223                            mIntentFilterVerifier.addOneIntentFilterVerification(
13224                                    verifierUid, userId, verificationId, filter, packageName);
13225                            count++;
13226                        }
13227                    }
13228                }
13229            }
13230        }
13231
13232        if (count > 0) {
13233            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13234                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13235                    +  " for userId:" + userId);
13236            mIntentFilterVerifier.startVerifications(userId);
13237        } else {
13238            if (DEBUG_DOMAIN_VERIFICATION) {
13239                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13240            }
13241        }
13242    }
13243
13244    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13245        final ComponentName cn  = filter.activity.getComponentName();
13246        final String packageName = cn.getPackageName();
13247
13248        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13249                packageName);
13250        if (ivi == null) {
13251            return true;
13252        }
13253        int status = ivi.getStatus();
13254        switch (status) {
13255            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13256            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13257                return true;
13258
13259            default:
13260                // Nothing to do
13261                return false;
13262        }
13263    }
13264
13265    private static boolean isMultiArch(ApplicationInfo info) {
13266        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13267    }
13268
13269    private static boolean isExternal(PackageParser.Package pkg) {
13270        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13271    }
13272
13273    private static boolean isExternal(PackageSetting ps) {
13274        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13275    }
13276
13277    private static boolean isEphemeral(PackageParser.Package pkg) {
13278        return pkg.applicationInfo.isEphemeralApp();
13279    }
13280
13281    private static boolean isEphemeral(PackageSetting ps) {
13282        return ps.pkg != null && isEphemeral(ps.pkg);
13283    }
13284
13285    private static boolean isSystemApp(PackageParser.Package pkg) {
13286        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13287    }
13288
13289    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13290        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13291    }
13292
13293    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13294        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13295    }
13296
13297    private static boolean isSystemApp(PackageSetting ps) {
13298        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13299    }
13300
13301    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13302        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13303    }
13304
13305    private int packageFlagsToInstallFlags(PackageSetting ps) {
13306        int installFlags = 0;
13307        if (isEphemeral(ps)) {
13308            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13309        }
13310        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13311            // This existing package was an external ASEC install when we have
13312            // the external flag without a UUID
13313            installFlags |= PackageManager.INSTALL_EXTERNAL;
13314        }
13315        if (ps.isForwardLocked()) {
13316            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13317        }
13318        return installFlags;
13319    }
13320
13321    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13322        if (isExternal(pkg)) {
13323            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13324                return StorageManager.UUID_PRIMARY_PHYSICAL;
13325            } else {
13326                return pkg.volumeUuid;
13327            }
13328        } else {
13329            return StorageManager.UUID_PRIVATE_INTERNAL;
13330        }
13331    }
13332
13333    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13334        if (isExternal(pkg)) {
13335            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13336                return mSettings.getExternalVersion();
13337            } else {
13338                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13339            }
13340        } else {
13341            return mSettings.getInternalVersion();
13342        }
13343    }
13344
13345    private void deleteTempPackageFiles() {
13346        final FilenameFilter filter = new FilenameFilter() {
13347            public boolean accept(File dir, String name) {
13348                return name.startsWith("vmdl") && name.endsWith(".tmp");
13349            }
13350        };
13351        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13352            file.delete();
13353        }
13354    }
13355
13356    @Override
13357    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13358            int flags) {
13359        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13360                flags);
13361    }
13362
13363    @Override
13364    public void deletePackage(final String packageName,
13365            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13366        mContext.enforceCallingOrSelfPermission(
13367                android.Manifest.permission.DELETE_PACKAGES, null);
13368        Preconditions.checkNotNull(packageName);
13369        Preconditions.checkNotNull(observer);
13370        final int uid = Binder.getCallingUid();
13371        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13372        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13373        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13374            mContext.enforceCallingOrSelfPermission(
13375                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13376                    "deletePackage for user " + userId);
13377        }
13378
13379        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13380            try {
13381                observer.onPackageDeleted(packageName,
13382                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13383            } catch (RemoteException re) {
13384            }
13385            return;
13386        }
13387
13388        for (int currentUserId : users) {
13389            if (getBlockUninstallForUser(packageName, currentUserId)) {
13390                try {
13391                    observer.onPackageDeleted(packageName,
13392                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13393                } catch (RemoteException re) {
13394                }
13395                return;
13396            }
13397        }
13398
13399        if (DEBUG_REMOVE) {
13400            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13401        }
13402        // Queue up an async operation since the package deletion may take a little while.
13403        mHandler.post(new Runnable() {
13404            public void run() {
13405                mHandler.removeCallbacks(this);
13406                final int returnCode = deletePackageX(packageName, userId, flags);
13407                try {
13408                    observer.onPackageDeleted(packageName, returnCode, null);
13409                } catch (RemoteException e) {
13410                    Log.i(TAG, "Observer no longer exists.");
13411                } //end catch
13412            } //end run
13413        });
13414    }
13415
13416    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13417        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13418                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13419        try {
13420            if (dpm != null) {
13421                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13422                        /* callingUserOnly =*/ false);
13423                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13424                        : deviceOwnerComponentName.getPackageName();
13425                // Does the package contains the device owner?
13426                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13427                // this check is probably not needed, since DO should be registered as a device
13428                // admin on some user too. (Original bug for this: b/17657954)
13429                if (packageName.equals(deviceOwnerPackageName)) {
13430                    return true;
13431                }
13432                // Does it contain a device admin for any user?
13433                int[] users;
13434                if (userId == UserHandle.USER_ALL) {
13435                    users = sUserManager.getUserIds();
13436                } else {
13437                    users = new int[]{userId};
13438                }
13439                for (int i = 0; i < users.length; ++i) {
13440                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13441                        return true;
13442                    }
13443                }
13444            }
13445        } catch (RemoteException e) {
13446        }
13447        return false;
13448    }
13449
13450    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13451        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13452    }
13453
13454    /**
13455     *  This method is an internal method that could be get invoked either
13456     *  to delete an installed package or to clean up a failed installation.
13457     *  After deleting an installed package, a broadcast is sent to notify any
13458     *  listeners that the package has been installed. For cleaning up a failed
13459     *  installation, the broadcast is not necessary since the package's
13460     *  installation wouldn't have sent the initial broadcast either
13461     *  The key steps in deleting a package are
13462     *  deleting the package information in internal structures like mPackages,
13463     *  deleting the packages base directories through installd
13464     *  updating mSettings to reflect current status
13465     *  persisting settings for later use
13466     *  sending a broadcast if necessary
13467     */
13468    private int deletePackageX(String packageName, int userId, int flags) {
13469        final PackageRemovedInfo info = new PackageRemovedInfo();
13470        final boolean res;
13471
13472        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13473                ? UserHandle.ALL : new UserHandle(userId);
13474
13475        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13476            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13477            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13478        }
13479
13480        boolean removedForAllUsers = false;
13481        boolean systemUpdate = false;
13482
13483        PackageParser.Package uninstalledPkg;
13484
13485        // for the uninstall-updates case and restricted profiles, remember the per-
13486        // userhandle installed state
13487        int[] allUsers;
13488        boolean[] perUserInstalled;
13489        synchronized (mPackages) {
13490            uninstalledPkg = mPackages.get(packageName);
13491            PackageSetting ps = mSettings.mPackages.get(packageName);
13492            allUsers = sUserManager.getUserIds();
13493            perUserInstalled = new boolean[allUsers.length];
13494            for (int i = 0; i < allUsers.length; i++) {
13495                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13496            }
13497        }
13498
13499        synchronized (mInstallLock) {
13500            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13501            res = deletePackageLI(packageName, removeForUser,
13502                    true, allUsers, perUserInstalled,
13503                    flags | REMOVE_CHATTY, info, true);
13504            systemUpdate = info.isRemovedPackageSystemUpdate;
13505            synchronized (mPackages) {
13506                if (res) {
13507                    if (!systemUpdate && mPackages.get(packageName) == null) {
13508                        removedForAllUsers = true;
13509                    }
13510                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13511                }
13512            }
13513            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13514                    + " removedForAllUsers=" + removedForAllUsers);
13515        }
13516
13517        if (res) {
13518            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13519
13520            // If the removed package was a system update, the old system package
13521            // was re-enabled; we need to broadcast this information
13522            if (systemUpdate) {
13523                Bundle extras = new Bundle(1);
13524                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13525                        ? info.removedAppId : info.uid);
13526                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13527
13528                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13529                        extras, 0, null, null, null);
13530                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13531                        extras, 0, null, null, null);
13532                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13533                        null, 0, packageName, null, null);
13534            }
13535        }
13536        // Force a gc here.
13537        Runtime.getRuntime().gc();
13538        // Delete the resources here after sending the broadcast to let
13539        // other processes clean up before deleting resources.
13540        if (info.args != null) {
13541            synchronized (mInstallLock) {
13542                info.args.doPostDeleteLI(true);
13543            }
13544        }
13545
13546        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13547    }
13548
13549    class PackageRemovedInfo {
13550        String removedPackage;
13551        int uid = -1;
13552        int removedAppId = -1;
13553        int[] removedUsers = null;
13554        boolean isRemovedPackageSystemUpdate = false;
13555        // Clean up resources deleted packages.
13556        InstallArgs args = null;
13557
13558        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13559            Bundle extras = new Bundle(1);
13560            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13561            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13562            if (replacing) {
13563                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13564            }
13565            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13566            if (removedPackage != null) {
13567                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13568                        extras, 0, null, null, removedUsers);
13569                if (fullRemove && !replacing) {
13570                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13571                            extras, 0, null, null, removedUsers);
13572                }
13573            }
13574            if (removedAppId >= 0) {
13575                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13576                        removedUsers);
13577            }
13578        }
13579    }
13580
13581    /*
13582     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13583     * flag is not set, the data directory is removed as well.
13584     * make sure this flag is set for partially installed apps. If not its meaningless to
13585     * delete a partially installed application.
13586     */
13587    private void removePackageDataLI(PackageSetting ps,
13588            int[] allUserHandles, boolean[] perUserInstalled,
13589            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13590        String packageName = ps.name;
13591        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13592        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13593        // Retrieve object to delete permissions for shared user later on
13594        final PackageSetting deletedPs;
13595        // reader
13596        synchronized (mPackages) {
13597            deletedPs = mSettings.mPackages.get(packageName);
13598            if (outInfo != null) {
13599                outInfo.removedPackage = packageName;
13600                outInfo.removedUsers = deletedPs != null
13601                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13602                        : null;
13603            }
13604        }
13605        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13606            removeDataDirsLI(ps.volumeUuid, packageName);
13607            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13608        }
13609        // writer
13610        synchronized (mPackages) {
13611            if (deletedPs != null) {
13612                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13613                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13614                    clearDefaultBrowserIfNeeded(packageName);
13615                    if (outInfo != null) {
13616                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13617                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13618                    }
13619                    updatePermissionsLPw(deletedPs.name, null, 0);
13620                    if (deletedPs.sharedUser != null) {
13621                        // Remove permissions associated with package. Since runtime
13622                        // permissions are per user we have to kill the removed package
13623                        // or packages running under the shared user of the removed
13624                        // package if revoking the permissions requested only by the removed
13625                        // package is successful and this causes a change in gids.
13626                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13627                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13628                                    userId);
13629                            if (userIdToKill == UserHandle.USER_ALL
13630                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13631                                // If gids changed for this user, kill all affected packages.
13632                                mHandler.post(new Runnable() {
13633                                    @Override
13634                                    public void run() {
13635                                        // This has to happen with no lock held.
13636                                        killApplication(deletedPs.name, deletedPs.appId,
13637                                                KILL_APP_REASON_GIDS_CHANGED);
13638                                    }
13639                                });
13640                                break;
13641                            }
13642                        }
13643                    }
13644                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13645                }
13646                // make sure to preserve per-user disabled state if this removal was just
13647                // a downgrade of a system app to the factory package
13648                if (allUserHandles != null && perUserInstalled != null) {
13649                    if (DEBUG_REMOVE) {
13650                        Slog.d(TAG, "Propagating install state across downgrade");
13651                    }
13652                    for (int i = 0; i < allUserHandles.length; i++) {
13653                        if (DEBUG_REMOVE) {
13654                            Slog.d(TAG, "    user " + allUserHandles[i]
13655                                    + " => " + perUserInstalled[i]);
13656                        }
13657                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13658                    }
13659                }
13660            }
13661            // can downgrade to reader
13662            if (writeSettings) {
13663                // Save settings now
13664                mSettings.writeLPr();
13665            }
13666        }
13667        if (outInfo != null) {
13668            // A user ID was deleted here. Go through all users and remove it
13669            // from KeyStore.
13670            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13671        }
13672    }
13673
13674    static boolean locationIsPrivileged(File path) {
13675        try {
13676            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13677                    .getCanonicalPath();
13678            return path.getCanonicalPath().startsWith(privilegedAppDir);
13679        } catch (IOException e) {
13680            Slog.e(TAG, "Unable to access code path " + path);
13681        }
13682        return false;
13683    }
13684
13685    /*
13686     * Tries to delete system package.
13687     */
13688    private boolean deleteSystemPackageLI(PackageSetting newPs,
13689            int[] allUserHandles, boolean[] perUserInstalled,
13690            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13691        final boolean applyUserRestrictions
13692                = (allUserHandles != null) && (perUserInstalled != null);
13693        PackageSetting disabledPs = null;
13694        // Confirm if the system package has been updated
13695        // An updated system app can be deleted. This will also have to restore
13696        // the system pkg from system partition
13697        // reader
13698        synchronized (mPackages) {
13699            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13700        }
13701        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13702                + " disabledPs=" + disabledPs);
13703        if (disabledPs == null) {
13704            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13705            return false;
13706        } else if (DEBUG_REMOVE) {
13707            Slog.d(TAG, "Deleting system pkg from data partition");
13708        }
13709        if (DEBUG_REMOVE) {
13710            if (applyUserRestrictions) {
13711                Slog.d(TAG, "Remembering install states:");
13712                for (int i = 0; i < allUserHandles.length; i++) {
13713                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13714                }
13715            }
13716        }
13717        // Delete the updated package
13718        outInfo.isRemovedPackageSystemUpdate = true;
13719        if (disabledPs.versionCode < newPs.versionCode) {
13720            // Delete data for downgrades
13721            flags &= ~PackageManager.DELETE_KEEP_DATA;
13722        } else {
13723            // Preserve data by setting flag
13724            flags |= PackageManager.DELETE_KEEP_DATA;
13725        }
13726        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13727                allUserHandles, perUserInstalled, outInfo, writeSettings);
13728        if (!ret) {
13729            return false;
13730        }
13731        // writer
13732        synchronized (mPackages) {
13733            // Reinstate the old system package
13734            mSettings.enableSystemPackageLPw(newPs.name);
13735            // Remove any native libraries from the upgraded package.
13736            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13737        }
13738        // Install the system package
13739        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13740        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13741        if (locationIsPrivileged(disabledPs.codePath)) {
13742            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13743        }
13744
13745        final PackageParser.Package newPkg;
13746        try {
13747            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13748        } catch (PackageManagerException e) {
13749            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13750            return false;
13751        }
13752
13753        prepareAppDataAfterInstall(newPkg);
13754
13755        // writer
13756        synchronized (mPackages) {
13757            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13758
13759            // Propagate the permissions state as we do not want to drop on the floor
13760            // runtime permissions. The update permissions method below will take
13761            // care of removing obsolete permissions and grant install permissions.
13762            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13763            updatePermissionsLPw(newPkg.packageName, newPkg,
13764                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13765
13766            if (applyUserRestrictions) {
13767                if (DEBUG_REMOVE) {
13768                    Slog.d(TAG, "Propagating install state across reinstall");
13769                }
13770                for (int i = 0; i < allUserHandles.length; i++) {
13771                    if (DEBUG_REMOVE) {
13772                        Slog.d(TAG, "    user " + allUserHandles[i]
13773                                + " => " + perUserInstalled[i]);
13774                    }
13775                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13776
13777                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13778                }
13779                // Regardless of writeSettings we need to ensure that this restriction
13780                // state propagation is persisted
13781                mSettings.writeAllUsersPackageRestrictionsLPr();
13782            }
13783            // can downgrade to reader here
13784            if (writeSettings) {
13785                mSettings.writeLPr();
13786            }
13787        }
13788        return true;
13789    }
13790
13791    private boolean deleteInstalledPackageLI(PackageSetting ps,
13792            boolean deleteCodeAndResources, int flags,
13793            int[] allUserHandles, boolean[] perUserInstalled,
13794            PackageRemovedInfo outInfo, boolean writeSettings) {
13795        if (outInfo != null) {
13796            outInfo.uid = ps.appId;
13797        }
13798
13799        // Delete package data from internal structures and also remove data if flag is set
13800        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13801
13802        // Delete application code and resources
13803        if (deleteCodeAndResources && (outInfo != null)) {
13804            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13805                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13806            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13807        }
13808        return true;
13809    }
13810
13811    @Override
13812    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13813            int userId) {
13814        mContext.enforceCallingOrSelfPermission(
13815                android.Manifest.permission.DELETE_PACKAGES, null);
13816        synchronized (mPackages) {
13817            PackageSetting ps = mSettings.mPackages.get(packageName);
13818            if (ps == null) {
13819                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13820                return false;
13821            }
13822            if (!ps.getInstalled(userId)) {
13823                // Can't block uninstall for an app that is not installed or enabled.
13824                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13825                return false;
13826            }
13827            ps.setBlockUninstall(blockUninstall, userId);
13828            mSettings.writePackageRestrictionsLPr(userId);
13829        }
13830        return true;
13831    }
13832
13833    @Override
13834    public boolean getBlockUninstallForUser(String packageName, int userId) {
13835        synchronized (mPackages) {
13836            PackageSetting ps = mSettings.mPackages.get(packageName);
13837            if (ps == null) {
13838                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13839                return false;
13840            }
13841            return ps.getBlockUninstall(userId);
13842        }
13843    }
13844
13845    @Override
13846    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13847        int callingUid = Binder.getCallingUid();
13848        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13849            throw new SecurityException(
13850                    "setRequiredForSystemUser can only be run by the system or root");
13851        }
13852        synchronized (mPackages) {
13853            PackageSetting ps = mSettings.mPackages.get(packageName);
13854            if (ps == null) {
13855                Log.w(TAG, "Package doesn't exist: " + packageName);
13856                return false;
13857            }
13858            if (systemUserApp) {
13859                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13860            } else {
13861                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13862            }
13863            mSettings.writeLPr();
13864        }
13865        return true;
13866    }
13867
13868    /*
13869     * This method handles package deletion in general
13870     */
13871    private boolean deletePackageLI(String packageName, UserHandle user,
13872            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13873            int flags, PackageRemovedInfo outInfo,
13874            boolean writeSettings) {
13875        if (packageName == null) {
13876            Slog.w(TAG, "Attempt to delete null packageName.");
13877            return false;
13878        }
13879        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13880        PackageSetting ps;
13881        boolean dataOnly = false;
13882        int removeUser = -1;
13883        int appId = -1;
13884        synchronized (mPackages) {
13885            ps = mSettings.mPackages.get(packageName);
13886            if (ps == null) {
13887                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13888                return false;
13889            }
13890            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13891                    && user.getIdentifier() != UserHandle.USER_ALL) {
13892                // The caller is asking that the package only be deleted for a single
13893                // user.  To do this, we just mark its uninstalled state and delete
13894                // its data.  If this is a system app, we only allow this to happen if
13895                // they have set the special DELETE_SYSTEM_APP which requests different
13896                // semantics than normal for uninstalling system apps.
13897                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13898                final int userId = user.getIdentifier();
13899                ps.setUserState(userId,
13900                        COMPONENT_ENABLED_STATE_DEFAULT,
13901                        false, //installed
13902                        true,  //stopped
13903                        true,  //notLaunched
13904                        false, //hidden
13905                        false, //suspended
13906                        null, null, null,
13907                        false, // blockUninstall
13908                        ps.readUserState(userId).domainVerificationStatus, 0);
13909                if (!isSystemApp(ps)) {
13910                    // Do not uninstall the APK if an app should be cached
13911                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13912                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13913                        // Other user still have this package installed, so all
13914                        // we need to do is clear this user's data and save that
13915                        // it is uninstalled.
13916                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13917                        removeUser = user.getIdentifier();
13918                        appId = ps.appId;
13919                        scheduleWritePackageRestrictionsLocked(removeUser);
13920                    } else {
13921                        // We need to set it back to 'installed' so the uninstall
13922                        // broadcasts will be sent correctly.
13923                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13924                        ps.setInstalled(true, user.getIdentifier());
13925                    }
13926                } else {
13927                    // This is a system app, so we assume that the
13928                    // other users still have this package installed, so all
13929                    // we need to do is clear this user's data and save that
13930                    // it is uninstalled.
13931                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13932                    removeUser = user.getIdentifier();
13933                    appId = ps.appId;
13934                    scheduleWritePackageRestrictionsLocked(removeUser);
13935                }
13936            }
13937        }
13938
13939        if (removeUser >= 0) {
13940            // From above, we determined that we are deleting this only
13941            // for a single user.  Continue the work here.
13942            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13943            if (outInfo != null) {
13944                outInfo.removedPackage = packageName;
13945                outInfo.removedAppId = appId;
13946                outInfo.removedUsers = new int[] {removeUser};
13947            }
13948            // TODO: triage flags as part of 26466827
13949            final int installerFlags = StorageManager.FLAG_STORAGE_CE
13950                    | StorageManager.FLAG_STORAGE_DE;
13951            try {
13952                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13953            } catch (InstallerException e) {
13954                Slog.w(TAG, "Failed to delete app data", e);
13955            }
13956            removeKeystoreDataIfNeeded(removeUser, appId);
13957            schedulePackageCleaning(packageName, removeUser, false);
13958            synchronized (mPackages) {
13959                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13960                    scheduleWritePackageRestrictionsLocked(removeUser);
13961                }
13962                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13963            }
13964            return true;
13965        }
13966
13967        if (dataOnly) {
13968            // Delete application data first
13969            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13970            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13971            return true;
13972        }
13973
13974        boolean ret = false;
13975        if (isSystemApp(ps)) {
13976            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13977            // When an updated system application is deleted we delete the existing resources as well and
13978            // fall back to existing code in system partition
13979            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13980                    flags, outInfo, writeSettings);
13981        } else {
13982            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13983            // Kill application pre-emptively especially for apps on sd.
13984            killApplication(packageName, ps.appId, "uninstall pkg");
13985            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13986                    allUserHandles, perUserInstalled,
13987                    outInfo, writeSettings);
13988        }
13989
13990        return ret;
13991    }
13992
13993    private final static class ClearStorageConnection implements ServiceConnection {
13994        IMediaContainerService mContainerService;
13995
13996        @Override
13997        public void onServiceConnected(ComponentName name, IBinder service) {
13998            synchronized (this) {
13999                mContainerService = IMediaContainerService.Stub.asInterface(service);
14000                notifyAll();
14001            }
14002        }
14003
14004        @Override
14005        public void onServiceDisconnected(ComponentName name) {
14006        }
14007    }
14008
14009    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
14010        final boolean mounted;
14011        if (Environment.isExternalStorageEmulated()) {
14012            mounted = true;
14013        } else {
14014            final String status = Environment.getExternalStorageState();
14015
14016            mounted = status.equals(Environment.MEDIA_MOUNTED)
14017                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
14018        }
14019
14020        if (!mounted) {
14021            return;
14022        }
14023
14024        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
14025        int[] users;
14026        if (userId == UserHandle.USER_ALL) {
14027            users = sUserManager.getUserIds();
14028        } else {
14029            users = new int[] { userId };
14030        }
14031        final ClearStorageConnection conn = new ClearStorageConnection();
14032        if (mContext.bindServiceAsUser(
14033                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
14034            try {
14035                for (int curUser : users) {
14036                    long timeout = SystemClock.uptimeMillis() + 5000;
14037                    synchronized (conn) {
14038                        long now = SystemClock.uptimeMillis();
14039                        while (conn.mContainerService == null && now < timeout) {
14040                            try {
14041                                conn.wait(timeout - now);
14042                            } catch (InterruptedException e) {
14043                            }
14044                        }
14045                    }
14046                    if (conn.mContainerService == null) {
14047                        return;
14048                    }
14049
14050                    final UserEnvironment userEnv = new UserEnvironment(curUser);
14051                    clearDirectory(conn.mContainerService,
14052                            userEnv.buildExternalStorageAppCacheDirs(packageName));
14053                    if (allData) {
14054                        clearDirectory(conn.mContainerService,
14055                                userEnv.buildExternalStorageAppDataDirs(packageName));
14056                        clearDirectory(conn.mContainerService,
14057                                userEnv.buildExternalStorageAppMediaDirs(packageName));
14058                    }
14059                }
14060            } finally {
14061                mContext.unbindService(conn);
14062            }
14063        }
14064    }
14065
14066    @Override
14067    public void clearApplicationUserData(final String packageName,
14068            final IPackageDataObserver observer, final int userId) {
14069        mContext.enforceCallingOrSelfPermission(
14070                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14071        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14072        // Queue up an async operation since the package deletion may take a little while.
14073        mHandler.post(new Runnable() {
14074            public void run() {
14075                mHandler.removeCallbacks(this);
14076                final boolean succeeded;
14077                synchronized (mInstallLock) {
14078                    succeeded = clearApplicationUserDataLI(packageName, userId);
14079                }
14080                clearExternalStorageDataSync(packageName, userId, true);
14081                if (succeeded) {
14082                    // invoke DeviceStorageMonitor's update method to clear any notifications
14083                    DeviceStorageMonitorInternal
14084                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14085                    if (dsm != null) {
14086                        dsm.checkMemory();
14087                    }
14088                }
14089                if(observer != null) {
14090                    try {
14091                        observer.onRemoveCompleted(packageName, succeeded);
14092                    } catch (RemoteException e) {
14093                        Log.i(TAG, "Observer no longer exists.");
14094                    }
14095                } //end if observer
14096            } //end run
14097        });
14098    }
14099
14100    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14101        if (packageName == null) {
14102            Slog.w(TAG, "Attempt to delete null packageName.");
14103            return false;
14104        }
14105
14106        // Try finding details about the requested package
14107        PackageParser.Package pkg;
14108        synchronized (mPackages) {
14109            pkg = mPackages.get(packageName);
14110            if (pkg == null) {
14111                final PackageSetting ps = mSettings.mPackages.get(packageName);
14112                if (ps != null) {
14113                    pkg = ps.pkg;
14114                }
14115            }
14116
14117            if (pkg == null) {
14118                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14119                return false;
14120            }
14121
14122            PackageSetting ps = (PackageSetting) pkg.mExtras;
14123            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14124        }
14125
14126        // Always delete data directories for package, even if we found no other
14127        // record of app. This helps users recover from UID mismatches without
14128        // resorting to a full data wipe.
14129        // TODO: triage flags as part of 26466827
14130        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14131        try {
14132            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14133        } catch (InstallerException e) {
14134            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14135            return false;
14136        }
14137
14138        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14139        removeKeystoreDataIfNeeded(userId, appId);
14140
14141        // Create a native library symlink only if we have native libraries
14142        // and if the native libraries are 32 bit libraries. We do not provide
14143        // this symlink for 64 bit libraries.
14144        if (pkg.applicationInfo.primaryCpuAbi != null &&
14145                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14146            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14147            try {
14148                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14149                        nativeLibPath, userId);
14150            } catch (InstallerException e) {
14151                Slog.w(TAG, "Failed linking native library dir", e);
14152                return false;
14153            }
14154        }
14155
14156        return true;
14157    }
14158
14159    /**
14160     * Reverts user permission state changes (permissions and flags) in
14161     * all packages for a given user.
14162     *
14163     * @param userId The device user for which to do a reset.
14164     */
14165    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14166        final int packageCount = mPackages.size();
14167        for (int i = 0; i < packageCount; i++) {
14168            PackageParser.Package pkg = mPackages.valueAt(i);
14169            PackageSetting ps = (PackageSetting) pkg.mExtras;
14170            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14171        }
14172    }
14173
14174    /**
14175     * Reverts user permission state changes (permissions and flags).
14176     *
14177     * @param ps The package for which to reset.
14178     * @param userId The device user for which to do a reset.
14179     */
14180    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14181            final PackageSetting ps, final int userId) {
14182        if (ps.pkg == null) {
14183            return;
14184        }
14185
14186        // These are flags that can change base on user actions.
14187        final int userSettableMask = FLAG_PERMISSION_USER_SET
14188                | FLAG_PERMISSION_USER_FIXED
14189                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14190                | FLAG_PERMISSION_REVIEW_REQUIRED;
14191
14192        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14193                | FLAG_PERMISSION_POLICY_FIXED;
14194
14195        boolean writeInstallPermissions = false;
14196        boolean writeRuntimePermissions = false;
14197
14198        final int permissionCount = ps.pkg.requestedPermissions.size();
14199        for (int i = 0; i < permissionCount; i++) {
14200            String permission = ps.pkg.requestedPermissions.get(i);
14201
14202            BasePermission bp = mSettings.mPermissions.get(permission);
14203            if (bp == null) {
14204                continue;
14205            }
14206
14207            // If shared user we just reset the state to which only this app contributed.
14208            if (ps.sharedUser != null) {
14209                boolean used = false;
14210                final int packageCount = ps.sharedUser.packages.size();
14211                for (int j = 0; j < packageCount; j++) {
14212                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14213                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14214                            && pkg.pkg.requestedPermissions.contains(permission)) {
14215                        used = true;
14216                        break;
14217                    }
14218                }
14219                if (used) {
14220                    continue;
14221                }
14222            }
14223
14224            PermissionsState permissionsState = ps.getPermissionsState();
14225
14226            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14227
14228            // Always clear the user settable flags.
14229            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14230                    bp.name) != null;
14231            // If permission review is enabled and this is a legacy app, mark the
14232            // permission as requiring a review as this is the initial state.
14233            int flags = 0;
14234            if (Build.PERMISSIONS_REVIEW_REQUIRED
14235                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14236                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14237            }
14238            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14239                if (hasInstallState) {
14240                    writeInstallPermissions = true;
14241                } else {
14242                    writeRuntimePermissions = true;
14243                }
14244            }
14245
14246            // Below is only runtime permission handling.
14247            if (!bp.isRuntime()) {
14248                continue;
14249            }
14250
14251            // Never clobber system or policy.
14252            if ((oldFlags & policyOrSystemFlags) != 0) {
14253                continue;
14254            }
14255
14256            // If this permission was granted by default, make sure it is.
14257            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14258                if (permissionsState.grantRuntimePermission(bp, userId)
14259                        != PERMISSION_OPERATION_FAILURE) {
14260                    writeRuntimePermissions = true;
14261                }
14262            // If permission review is enabled the permissions for a legacy apps
14263            // are represented as constantly granted runtime ones, so don't revoke.
14264            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14265                // Otherwise, reset the permission.
14266                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14267                switch (revokeResult) {
14268                    case PERMISSION_OPERATION_SUCCESS: {
14269                        writeRuntimePermissions = true;
14270                    } break;
14271
14272                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14273                        writeRuntimePermissions = true;
14274                        final int appId = ps.appId;
14275                        mHandler.post(new Runnable() {
14276                            @Override
14277                            public void run() {
14278                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14279                            }
14280                        });
14281                    } break;
14282                }
14283            }
14284        }
14285
14286        // Synchronously write as we are taking permissions away.
14287        if (writeRuntimePermissions) {
14288            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14289        }
14290
14291        // Synchronously write as we are taking permissions away.
14292        if (writeInstallPermissions) {
14293            mSettings.writeLPr();
14294        }
14295    }
14296
14297    /**
14298     * Remove entries from the keystore daemon. Will only remove it if the
14299     * {@code appId} is valid.
14300     */
14301    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14302        if (appId < 0) {
14303            return;
14304        }
14305
14306        final KeyStore keyStore = KeyStore.getInstance();
14307        if (keyStore != null) {
14308            if (userId == UserHandle.USER_ALL) {
14309                for (final int individual : sUserManager.getUserIds()) {
14310                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14311                }
14312            } else {
14313                keyStore.clearUid(UserHandle.getUid(userId, appId));
14314            }
14315        } else {
14316            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14317        }
14318    }
14319
14320    @Override
14321    public void deleteApplicationCacheFiles(final String packageName,
14322            final IPackageDataObserver observer) {
14323        mContext.enforceCallingOrSelfPermission(
14324                android.Manifest.permission.DELETE_CACHE_FILES, null);
14325        // Queue up an async operation since the package deletion may take a little while.
14326        final int userId = UserHandle.getCallingUserId();
14327        mHandler.post(new Runnable() {
14328            public void run() {
14329                mHandler.removeCallbacks(this);
14330                final boolean succeded;
14331                synchronized (mInstallLock) {
14332                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14333                }
14334                clearExternalStorageDataSync(packageName, userId, false);
14335                if (observer != null) {
14336                    try {
14337                        observer.onRemoveCompleted(packageName, succeded);
14338                    } catch (RemoteException e) {
14339                        Log.i(TAG, "Observer no longer exists.");
14340                    }
14341                } //end if observer
14342            } //end run
14343        });
14344    }
14345
14346    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14347        if (packageName == null) {
14348            Slog.w(TAG, "Attempt to delete null packageName.");
14349            return false;
14350        }
14351        PackageParser.Package p;
14352        synchronized (mPackages) {
14353            p = mPackages.get(packageName);
14354        }
14355        if (p == null) {
14356            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14357            return false;
14358        }
14359        final ApplicationInfo applicationInfo = p.applicationInfo;
14360        if (applicationInfo == null) {
14361            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14362            return false;
14363        }
14364        // TODO: triage flags as part of 26466827
14365        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14366        try {
14367            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14368                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14369        } catch (InstallerException e) {
14370            Slog.w(TAG, "Couldn't remove cache files for package "
14371                    + packageName + " u" + userId, e);
14372            return false;
14373        }
14374        return true;
14375    }
14376
14377    @Override
14378    public void getPackageSizeInfo(final String packageName, int userHandle,
14379            final IPackageStatsObserver observer) {
14380        mContext.enforceCallingOrSelfPermission(
14381                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14382        if (packageName == null) {
14383            throw new IllegalArgumentException("Attempt to get size of null packageName");
14384        }
14385
14386        PackageStats stats = new PackageStats(packageName, userHandle);
14387
14388        /*
14389         * Queue up an async operation since the package measurement may take a
14390         * little while.
14391         */
14392        Message msg = mHandler.obtainMessage(INIT_COPY);
14393        msg.obj = new MeasureParams(stats, observer);
14394        mHandler.sendMessage(msg);
14395    }
14396
14397    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14398            PackageStats pStats) {
14399        if (packageName == null) {
14400            Slog.w(TAG, "Attempt to get size of null packageName.");
14401            return false;
14402        }
14403        PackageParser.Package p;
14404        boolean dataOnly = false;
14405        String libDirRoot = null;
14406        String asecPath = null;
14407        PackageSetting ps = null;
14408        synchronized (mPackages) {
14409            p = mPackages.get(packageName);
14410            ps = mSettings.mPackages.get(packageName);
14411            if(p == null) {
14412                dataOnly = true;
14413                if((ps == null) || (ps.pkg == null)) {
14414                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14415                    return false;
14416                }
14417                p = ps.pkg;
14418            }
14419            if (ps != null) {
14420                libDirRoot = ps.legacyNativeLibraryPathString;
14421            }
14422            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14423                final long token = Binder.clearCallingIdentity();
14424                try {
14425                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14426                    if (secureContainerId != null) {
14427                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14428                    }
14429                } finally {
14430                    Binder.restoreCallingIdentity(token);
14431                }
14432            }
14433        }
14434        String publicSrcDir = null;
14435        if(!dataOnly) {
14436            final ApplicationInfo applicationInfo = p.applicationInfo;
14437            if (applicationInfo == null) {
14438                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14439                return false;
14440            }
14441            if (p.isForwardLocked()) {
14442                publicSrcDir = applicationInfo.getBaseResourcePath();
14443            }
14444        }
14445        // TODO: extend to measure size of split APKs
14446        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14447        // not just the first level.
14448        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14449        // just the primary.
14450        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14451
14452        String apkPath;
14453        File packageDir = new File(p.codePath);
14454
14455        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14456            apkPath = packageDir.getAbsolutePath();
14457            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14458            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14459                libDirRoot = null;
14460            }
14461        } else {
14462            apkPath = p.baseCodePath;
14463        }
14464
14465        // TODO: triage flags as part of 26466827
14466        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
14467        try {
14468            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14469                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14470        } catch (InstallerException e) {
14471            return false;
14472        }
14473
14474        // Fix-up for forward-locked applications in ASEC containers.
14475        if (!isExternal(p)) {
14476            pStats.codeSize += pStats.externalCodeSize;
14477            pStats.externalCodeSize = 0L;
14478        }
14479
14480        return true;
14481    }
14482
14483
14484    @Override
14485    public void addPackageToPreferred(String packageName) {
14486        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14487    }
14488
14489    @Override
14490    public void removePackageFromPreferred(String packageName) {
14491        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14492    }
14493
14494    @Override
14495    public List<PackageInfo> getPreferredPackages(int flags) {
14496        return new ArrayList<PackageInfo>();
14497    }
14498
14499    private int getUidTargetSdkVersionLockedLPr(int uid) {
14500        Object obj = mSettings.getUserIdLPr(uid);
14501        if (obj instanceof SharedUserSetting) {
14502            final SharedUserSetting sus = (SharedUserSetting) obj;
14503            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14504            final Iterator<PackageSetting> it = sus.packages.iterator();
14505            while (it.hasNext()) {
14506                final PackageSetting ps = it.next();
14507                if (ps.pkg != null) {
14508                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14509                    if (v < vers) vers = v;
14510                }
14511            }
14512            return vers;
14513        } else if (obj instanceof PackageSetting) {
14514            final PackageSetting ps = (PackageSetting) obj;
14515            if (ps.pkg != null) {
14516                return ps.pkg.applicationInfo.targetSdkVersion;
14517            }
14518        }
14519        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14520    }
14521
14522    @Override
14523    public void addPreferredActivity(IntentFilter filter, int match,
14524            ComponentName[] set, ComponentName activity, int userId) {
14525        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14526                "Adding preferred");
14527    }
14528
14529    private void addPreferredActivityInternal(IntentFilter filter, int match,
14530            ComponentName[] set, ComponentName activity, boolean always, int userId,
14531            String opname) {
14532        // writer
14533        int callingUid = Binder.getCallingUid();
14534        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14535        if (filter.countActions() == 0) {
14536            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14537            return;
14538        }
14539        synchronized (mPackages) {
14540            if (mContext.checkCallingOrSelfPermission(
14541                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14542                    != PackageManager.PERMISSION_GRANTED) {
14543                if (getUidTargetSdkVersionLockedLPr(callingUid)
14544                        < Build.VERSION_CODES.FROYO) {
14545                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14546                            + callingUid);
14547                    return;
14548                }
14549                mContext.enforceCallingOrSelfPermission(
14550                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14551            }
14552
14553            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14554            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14555                    + userId + ":");
14556            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14557            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14558            scheduleWritePackageRestrictionsLocked(userId);
14559        }
14560    }
14561
14562    @Override
14563    public void replacePreferredActivity(IntentFilter filter, int match,
14564            ComponentName[] set, ComponentName activity, int userId) {
14565        if (filter.countActions() != 1) {
14566            throw new IllegalArgumentException(
14567                    "replacePreferredActivity expects filter to have only 1 action.");
14568        }
14569        if (filter.countDataAuthorities() != 0
14570                || filter.countDataPaths() != 0
14571                || filter.countDataSchemes() > 1
14572                || filter.countDataTypes() != 0) {
14573            throw new IllegalArgumentException(
14574                    "replacePreferredActivity expects filter to have no data authorities, " +
14575                    "paths, or types; and at most one scheme.");
14576        }
14577
14578        final int callingUid = Binder.getCallingUid();
14579        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14580        synchronized (mPackages) {
14581            if (mContext.checkCallingOrSelfPermission(
14582                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14583                    != PackageManager.PERMISSION_GRANTED) {
14584                if (getUidTargetSdkVersionLockedLPr(callingUid)
14585                        < Build.VERSION_CODES.FROYO) {
14586                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14587                            + Binder.getCallingUid());
14588                    return;
14589                }
14590                mContext.enforceCallingOrSelfPermission(
14591                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14592            }
14593
14594            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14595            if (pir != null) {
14596                // Get all of the existing entries that exactly match this filter.
14597                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14598                if (existing != null && existing.size() == 1) {
14599                    PreferredActivity cur = existing.get(0);
14600                    if (DEBUG_PREFERRED) {
14601                        Slog.i(TAG, "Checking replace of preferred:");
14602                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14603                        if (!cur.mPref.mAlways) {
14604                            Slog.i(TAG, "  -- CUR; not mAlways!");
14605                        } else {
14606                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14607                            Slog.i(TAG, "  -- CUR: mSet="
14608                                    + Arrays.toString(cur.mPref.mSetComponents));
14609                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14610                            Slog.i(TAG, "  -- NEW: mMatch="
14611                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14612                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14613                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14614                        }
14615                    }
14616                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14617                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14618                            && cur.mPref.sameSet(set)) {
14619                        // Setting the preferred activity to what it happens to be already
14620                        if (DEBUG_PREFERRED) {
14621                            Slog.i(TAG, "Replacing with same preferred activity "
14622                                    + cur.mPref.mShortComponent + " for user "
14623                                    + userId + ":");
14624                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14625                        }
14626                        return;
14627                    }
14628                }
14629
14630                if (existing != null) {
14631                    if (DEBUG_PREFERRED) {
14632                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14633                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14634                    }
14635                    for (int i = 0; i < existing.size(); i++) {
14636                        PreferredActivity pa = existing.get(i);
14637                        if (DEBUG_PREFERRED) {
14638                            Slog.i(TAG, "Removing existing preferred activity "
14639                                    + pa.mPref.mComponent + ":");
14640                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14641                        }
14642                        pir.removeFilter(pa);
14643                    }
14644                }
14645            }
14646            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14647                    "Replacing preferred");
14648        }
14649    }
14650
14651    @Override
14652    public void clearPackagePreferredActivities(String packageName) {
14653        final int uid = Binder.getCallingUid();
14654        // writer
14655        synchronized (mPackages) {
14656            PackageParser.Package pkg = mPackages.get(packageName);
14657            if (pkg == null || pkg.applicationInfo.uid != uid) {
14658                if (mContext.checkCallingOrSelfPermission(
14659                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14660                        != PackageManager.PERMISSION_GRANTED) {
14661                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14662                            < Build.VERSION_CODES.FROYO) {
14663                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14664                                + Binder.getCallingUid());
14665                        return;
14666                    }
14667                    mContext.enforceCallingOrSelfPermission(
14668                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14669                }
14670            }
14671
14672            int user = UserHandle.getCallingUserId();
14673            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14674                scheduleWritePackageRestrictionsLocked(user);
14675            }
14676        }
14677    }
14678
14679    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14680    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14681        ArrayList<PreferredActivity> removed = null;
14682        boolean changed = false;
14683        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14684            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14685            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14686            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14687                continue;
14688            }
14689            Iterator<PreferredActivity> it = pir.filterIterator();
14690            while (it.hasNext()) {
14691                PreferredActivity pa = it.next();
14692                // Mark entry for removal only if it matches the package name
14693                // and the entry is of type "always".
14694                if (packageName == null ||
14695                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14696                                && pa.mPref.mAlways)) {
14697                    if (removed == null) {
14698                        removed = new ArrayList<PreferredActivity>();
14699                    }
14700                    removed.add(pa);
14701                }
14702            }
14703            if (removed != null) {
14704                for (int j=0; j<removed.size(); j++) {
14705                    PreferredActivity pa = removed.get(j);
14706                    pir.removeFilter(pa);
14707                }
14708                changed = true;
14709            }
14710        }
14711        return changed;
14712    }
14713
14714    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14715    private void clearIntentFilterVerificationsLPw(int userId) {
14716        final int packageCount = mPackages.size();
14717        for (int i = 0; i < packageCount; i++) {
14718            PackageParser.Package pkg = mPackages.valueAt(i);
14719            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14720        }
14721    }
14722
14723    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14724    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14725        if (userId == UserHandle.USER_ALL) {
14726            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14727                    sUserManager.getUserIds())) {
14728                for (int oneUserId : sUserManager.getUserIds()) {
14729                    scheduleWritePackageRestrictionsLocked(oneUserId);
14730                }
14731            }
14732        } else {
14733            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14734                scheduleWritePackageRestrictionsLocked(userId);
14735            }
14736        }
14737    }
14738
14739    void clearDefaultBrowserIfNeeded(String packageName) {
14740        for (int oneUserId : sUserManager.getUserIds()) {
14741            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14742            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14743            if (packageName.equals(defaultBrowserPackageName)) {
14744                setDefaultBrowserPackageName(null, oneUserId);
14745            }
14746        }
14747    }
14748
14749    @Override
14750    public void resetApplicationPreferences(int userId) {
14751        mContext.enforceCallingOrSelfPermission(
14752                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14753        // writer
14754        synchronized (mPackages) {
14755            final long identity = Binder.clearCallingIdentity();
14756            try {
14757                clearPackagePreferredActivitiesLPw(null, userId);
14758                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14759                // TODO: We have to reset the default SMS and Phone. This requires
14760                // significant refactoring to keep all default apps in the package
14761                // manager (cleaner but more work) or have the services provide
14762                // callbacks to the package manager to request a default app reset.
14763                applyFactoryDefaultBrowserLPw(userId);
14764                clearIntentFilterVerificationsLPw(userId);
14765                primeDomainVerificationsLPw(userId);
14766                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14767                scheduleWritePackageRestrictionsLocked(userId);
14768            } finally {
14769                Binder.restoreCallingIdentity(identity);
14770            }
14771        }
14772    }
14773
14774    @Override
14775    public int getPreferredActivities(List<IntentFilter> outFilters,
14776            List<ComponentName> outActivities, String packageName) {
14777
14778        int num = 0;
14779        final int userId = UserHandle.getCallingUserId();
14780        // reader
14781        synchronized (mPackages) {
14782            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14783            if (pir != null) {
14784                final Iterator<PreferredActivity> it = pir.filterIterator();
14785                while (it.hasNext()) {
14786                    final PreferredActivity pa = it.next();
14787                    if (packageName == null
14788                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14789                                    && pa.mPref.mAlways)) {
14790                        if (outFilters != null) {
14791                            outFilters.add(new IntentFilter(pa));
14792                        }
14793                        if (outActivities != null) {
14794                            outActivities.add(pa.mPref.mComponent);
14795                        }
14796                    }
14797                }
14798            }
14799        }
14800
14801        return num;
14802    }
14803
14804    @Override
14805    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14806            int userId) {
14807        int callingUid = Binder.getCallingUid();
14808        if (callingUid != Process.SYSTEM_UID) {
14809            throw new SecurityException(
14810                    "addPersistentPreferredActivity can only be run by the system");
14811        }
14812        if (filter.countActions() == 0) {
14813            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14814            return;
14815        }
14816        synchronized (mPackages) {
14817            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14818                    ":");
14819            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14820            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14821                    new PersistentPreferredActivity(filter, activity));
14822            scheduleWritePackageRestrictionsLocked(userId);
14823        }
14824    }
14825
14826    @Override
14827    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14828        int callingUid = Binder.getCallingUid();
14829        if (callingUid != Process.SYSTEM_UID) {
14830            throw new SecurityException(
14831                    "clearPackagePersistentPreferredActivities can only be run by the system");
14832        }
14833        ArrayList<PersistentPreferredActivity> removed = null;
14834        boolean changed = false;
14835        synchronized (mPackages) {
14836            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14837                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14838                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14839                        .valueAt(i);
14840                if (userId != thisUserId) {
14841                    continue;
14842                }
14843                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14844                while (it.hasNext()) {
14845                    PersistentPreferredActivity ppa = it.next();
14846                    // Mark entry for removal only if it matches the package name.
14847                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14848                        if (removed == null) {
14849                            removed = new ArrayList<PersistentPreferredActivity>();
14850                        }
14851                        removed.add(ppa);
14852                    }
14853                }
14854                if (removed != null) {
14855                    for (int j=0; j<removed.size(); j++) {
14856                        PersistentPreferredActivity ppa = removed.get(j);
14857                        ppir.removeFilter(ppa);
14858                    }
14859                    changed = true;
14860                }
14861            }
14862
14863            if (changed) {
14864                scheduleWritePackageRestrictionsLocked(userId);
14865            }
14866        }
14867    }
14868
14869    /**
14870     * Common machinery for picking apart a restored XML blob and passing
14871     * it to a caller-supplied functor to be applied to the running system.
14872     */
14873    private void restoreFromXml(XmlPullParser parser, int userId,
14874            String expectedStartTag, BlobXmlRestorer functor)
14875            throws IOException, XmlPullParserException {
14876        int type;
14877        while ((type = parser.next()) != XmlPullParser.START_TAG
14878                && type != XmlPullParser.END_DOCUMENT) {
14879        }
14880        if (type != XmlPullParser.START_TAG) {
14881            // oops didn't find a start tag?!
14882            if (DEBUG_BACKUP) {
14883                Slog.e(TAG, "Didn't find start tag during restore");
14884            }
14885            return;
14886        }
14887Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
14888        // this is supposed to be TAG_PREFERRED_BACKUP
14889        if (!expectedStartTag.equals(parser.getName())) {
14890            if (DEBUG_BACKUP) {
14891                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14892            }
14893            return;
14894        }
14895
14896        // skip interfering stuff, then we're aligned with the backing implementation
14897        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14898Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
14899        functor.apply(parser, userId);
14900    }
14901
14902    private interface BlobXmlRestorer {
14903        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14904    }
14905
14906    /**
14907     * Non-Binder method, support for the backup/restore mechanism: write the
14908     * full set of preferred activities in its canonical XML format.  Returns the
14909     * XML output as a byte array, or null if there is none.
14910     */
14911    @Override
14912    public byte[] getPreferredActivityBackup(int userId) {
14913        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14914            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14915        }
14916
14917        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14918        try {
14919            final XmlSerializer serializer = new FastXmlSerializer();
14920            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14921            serializer.startDocument(null, true);
14922            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14923
14924            synchronized (mPackages) {
14925                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14926            }
14927
14928            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14929            serializer.endDocument();
14930            serializer.flush();
14931        } catch (Exception e) {
14932            if (DEBUG_BACKUP) {
14933                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14934            }
14935            return null;
14936        }
14937
14938        return dataStream.toByteArray();
14939    }
14940
14941    @Override
14942    public void restorePreferredActivities(byte[] backup, int userId) {
14943        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14944            throw new SecurityException("Only the system may call restorePreferredActivities()");
14945        }
14946
14947        try {
14948            final XmlPullParser parser = Xml.newPullParser();
14949            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14950            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14951                    new BlobXmlRestorer() {
14952                        @Override
14953                        public void apply(XmlPullParser parser, int userId)
14954                                throws XmlPullParserException, IOException {
14955                            synchronized (mPackages) {
14956                                mSettings.readPreferredActivitiesLPw(parser, userId);
14957                            }
14958                        }
14959                    } );
14960        } catch (Exception e) {
14961            if (DEBUG_BACKUP) {
14962                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14963            }
14964        }
14965    }
14966
14967    /**
14968     * Non-Binder method, support for the backup/restore mechanism: write the
14969     * default browser (etc) settings in its canonical XML format.  Returns the default
14970     * browser XML representation as a byte array, or null if there is none.
14971     */
14972    @Override
14973    public byte[] getDefaultAppsBackup(int userId) {
14974        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14975            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14976        }
14977
14978        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14979        try {
14980            final XmlSerializer serializer = new FastXmlSerializer();
14981            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14982            serializer.startDocument(null, true);
14983            serializer.startTag(null, TAG_DEFAULT_APPS);
14984
14985            synchronized (mPackages) {
14986                mSettings.writeDefaultAppsLPr(serializer, userId);
14987            }
14988
14989            serializer.endTag(null, TAG_DEFAULT_APPS);
14990            serializer.endDocument();
14991            serializer.flush();
14992        } catch (Exception e) {
14993            if (DEBUG_BACKUP) {
14994                Slog.e(TAG, "Unable to write default apps for backup", e);
14995            }
14996            return null;
14997        }
14998
14999        return dataStream.toByteArray();
15000    }
15001
15002    @Override
15003    public void restoreDefaultApps(byte[] backup, int userId) {
15004        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15005            throw new SecurityException("Only the system may call restoreDefaultApps()");
15006        }
15007
15008        try {
15009            final XmlPullParser parser = Xml.newPullParser();
15010            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15011            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
15012                    new BlobXmlRestorer() {
15013                        @Override
15014                        public void apply(XmlPullParser parser, int userId)
15015                                throws XmlPullParserException, IOException {
15016                            synchronized (mPackages) {
15017                                mSettings.readDefaultAppsLPw(parser, userId);
15018                            }
15019                        }
15020                    } );
15021        } catch (Exception e) {
15022            if (DEBUG_BACKUP) {
15023                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
15024            }
15025        }
15026    }
15027
15028    @Override
15029    public byte[] getIntentFilterVerificationBackup(int userId) {
15030        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15031            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
15032        }
15033
15034        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15035        try {
15036            final XmlSerializer serializer = new FastXmlSerializer();
15037            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15038            serializer.startDocument(null, true);
15039            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
15040
15041            synchronized (mPackages) {
15042                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
15043            }
15044
15045            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
15046            serializer.endDocument();
15047            serializer.flush();
15048        } catch (Exception e) {
15049            if (DEBUG_BACKUP) {
15050                Slog.e(TAG, "Unable to write default apps for backup", e);
15051            }
15052            return null;
15053        }
15054
15055        return dataStream.toByteArray();
15056    }
15057
15058    @Override
15059    public void restoreIntentFilterVerification(byte[] backup, int userId) {
15060        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15061            throw new SecurityException("Only the system may call restorePreferredActivities()");
15062        }
15063
15064        try {
15065            final XmlPullParser parser = Xml.newPullParser();
15066            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15067            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15068                    new BlobXmlRestorer() {
15069                        @Override
15070                        public void apply(XmlPullParser parser, int userId)
15071                                throws XmlPullParserException, IOException {
15072                            synchronized (mPackages) {
15073                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15074                                mSettings.writeLPr();
15075                            }
15076                        }
15077                    } );
15078        } catch (Exception e) {
15079            if (DEBUG_BACKUP) {
15080                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15081            }
15082        }
15083    }
15084
15085    @Override
15086    public byte[] getPermissionGrantBackup(int userId) {
15087        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15088            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
15089        }
15090
15091        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
15092        try {
15093            final XmlSerializer serializer = new FastXmlSerializer();
15094            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
15095            serializer.startDocument(null, true);
15096            serializer.startTag(null, TAG_PERMISSION_BACKUP);
15097
15098            synchronized (mPackages) {
15099                serializeRuntimePermissionGrantsLPr(serializer, userId);
15100            }
15101
15102            serializer.endTag(null, TAG_PERMISSION_BACKUP);
15103            serializer.endDocument();
15104            serializer.flush();
15105        } catch (Exception e) {
15106            if (DEBUG_BACKUP) {
15107                Slog.e(TAG, "Unable to write default apps for backup", e);
15108            }
15109            return null;
15110        }
15111
15112        return dataStream.toByteArray();
15113    }
15114
15115    @Override
15116    public void restorePermissionGrants(byte[] backup, int userId) {
15117        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
15118            throw new SecurityException("Only the system may call restorePermissionGrants()");
15119        }
15120
15121        try {
15122            final XmlPullParser parser = Xml.newPullParser();
15123            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15124            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
15125                    new BlobXmlRestorer() {
15126                        @Override
15127                        public void apply(XmlPullParser parser, int userId)
15128                                throws XmlPullParserException, IOException {
15129                            synchronized (mPackages) {
15130                                processRestoredPermissionGrantsLPr(parser, userId);
15131                            }
15132                        }
15133                    } );
15134        } catch (Exception e) {
15135            if (DEBUG_BACKUP) {
15136                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15137            }
15138        }
15139    }
15140
15141    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
15142            throws IOException {
15143        serializer.startTag(null, TAG_ALL_GRANTS);
15144
15145        final int N = mSettings.mPackages.size();
15146        for (int i = 0; i < N; i++) {
15147            final PackageSetting ps = mSettings.mPackages.valueAt(i);
15148            boolean pkgGrantsKnown = false;
15149
15150            PermissionsState packagePerms = ps.getPermissionsState();
15151
15152            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
15153                final int grantFlags = state.getFlags();
15154                // only look at grants that are not system/policy fixed
15155                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
15156                    final boolean isGranted = state.isGranted();
15157                    // And only back up the user-twiddled state bits
15158                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
15159                        final String packageName = mSettings.mPackages.keyAt(i);
15160                        if (!pkgGrantsKnown) {
15161                            serializer.startTag(null, TAG_GRANT);
15162                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
15163                            pkgGrantsKnown = true;
15164                        }
15165
15166                        final boolean userSet =
15167                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
15168                        final boolean userFixed =
15169                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
15170                        final boolean revoke =
15171                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
15172
15173                        serializer.startTag(null, TAG_PERMISSION);
15174                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
15175                        if (isGranted) {
15176                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
15177                        }
15178                        if (userSet) {
15179                            serializer.attribute(null, ATTR_USER_SET, "true");
15180                        }
15181                        if (userFixed) {
15182                            serializer.attribute(null, ATTR_USER_FIXED, "true");
15183                        }
15184                        if (revoke) {
15185                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
15186                        }
15187                        serializer.endTag(null, TAG_PERMISSION);
15188                    }
15189                }
15190            }
15191
15192            if (pkgGrantsKnown) {
15193                serializer.endTag(null, TAG_GRANT);
15194            }
15195        }
15196
15197        serializer.endTag(null, TAG_ALL_GRANTS);
15198    }
15199
15200    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
15201            throws XmlPullParserException, IOException {
15202        String pkgName = null;
15203        int outerDepth = parser.getDepth();
15204        int type;
15205        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
15206                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
15207            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
15208                continue;
15209            }
15210
15211            final String tagName = parser.getName();
15212            if (tagName.equals(TAG_GRANT)) {
15213                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
15214                if (DEBUG_BACKUP) {
15215                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
15216                }
15217            } else if (tagName.equals(TAG_PERMISSION)) {
15218
15219                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
15220                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
15221
15222                int newFlagSet = 0;
15223                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
15224                    newFlagSet |= FLAG_PERMISSION_USER_SET;
15225                }
15226                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
15227                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
15228                }
15229                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
15230                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
15231                }
15232                if (DEBUG_BACKUP) {
15233                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
15234                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
15235                }
15236                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15237                if (ps != null) {
15238                    // Already installed so we apply the grant immediately
15239                    if (DEBUG_BACKUP) {
15240                        Slog.v(TAG, "        + already installed; applying");
15241                    }
15242                    PermissionsState perms = ps.getPermissionsState();
15243                    BasePermission bp = mSettings.mPermissions.get(permName);
15244                    if (bp != null) {
15245                        if (isGranted) {
15246                            perms.grantRuntimePermission(bp, userId);
15247                        }
15248                        if (newFlagSet != 0) {
15249                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
15250                        }
15251                    }
15252                } else {
15253                    // Need to wait for post-restore install to apply the grant
15254                    if (DEBUG_BACKUP) {
15255                        Slog.v(TAG, "        - not yet installed; saving for later");
15256                    }
15257                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
15258                            isGranted, newFlagSet, userId);
15259                }
15260            } else {
15261                PackageManagerService.reportSettingsProblem(Log.WARN,
15262                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
15263                XmlUtils.skipCurrentTag(parser);
15264            }
15265        }
15266
15267        scheduleWriteSettingsLocked();
15268        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15269    }
15270
15271    @Override
15272    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15273            int sourceUserId, int targetUserId, int flags) {
15274        mContext.enforceCallingOrSelfPermission(
15275                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15276        int callingUid = Binder.getCallingUid();
15277        enforceOwnerRights(ownerPackage, callingUid);
15278        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15279        if (intentFilter.countActions() == 0) {
15280            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15281            return;
15282        }
15283        synchronized (mPackages) {
15284            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15285                    ownerPackage, targetUserId, flags);
15286            CrossProfileIntentResolver resolver =
15287                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15288            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15289            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15290            if (existing != null) {
15291                int size = existing.size();
15292                for (int i = 0; i < size; i++) {
15293                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15294                        return;
15295                    }
15296                }
15297            }
15298            resolver.addFilter(newFilter);
15299            scheduleWritePackageRestrictionsLocked(sourceUserId);
15300        }
15301    }
15302
15303    @Override
15304    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15305        mContext.enforceCallingOrSelfPermission(
15306                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15307        int callingUid = Binder.getCallingUid();
15308        enforceOwnerRights(ownerPackage, callingUid);
15309        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15310        synchronized (mPackages) {
15311            CrossProfileIntentResolver resolver =
15312                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15313            ArraySet<CrossProfileIntentFilter> set =
15314                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15315            for (CrossProfileIntentFilter filter : set) {
15316                if (filter.getOwnerPackage().equals(ownerPackage)) {
15317                    resolver.removeFilter(filter);
15318                }
15319            }
15320            scheduleWritePackageRestrictionsLocked(sourceUserId);
15321        }
15322    }
15323
15324    // Enforcing that callingUid is owning pkg on userId
15325    private void enforceOwnerRights(String pkg, int callingUid) {
15326        // The system owns everything.
15327        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15328            return;
15329        }
15330        int callingUserId = UserHandle.getUserId(callingUid);
15331        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15332        if (pi == null) {
15333            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15334                    + callingUserId);
15335        }
15336        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15337            throw new SecurityException("Calling uid " + callingUid
15338                    + " does not own package " + pkg);
15339        }
15340    }
15341
15342    @Override
15343    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15344        Intent intent = new Intent(Intent.ACTION_MAIN);
15345        intent.addCategory(Intent.CATEGORY_HOME);
15346
15347        final int callingUserId = UserHandle.getCallingUserId();
15348        List<ResolveInfo> list = queryIntentActivities(intent, null,
15349                PackageManager.GET_META_DATA, callingUserId);
15350        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15351                true, false, false, callingUserId);
15352
15353        allHomeCandidates.clear();
15354        if (list != null) {
15355            for (ResolveInfo ri : list) {
15356                allHomeCandidates.add(ri);
15357            }
15358        }
15359        return (preferred == null || preferred.activityInfo == null)
15360                ? null
15361                : new ComponentName(preferred.activityInfo.packageName,
15362                        preferred.activityInfo.name);
15363    }
15364
15365    @Override
15366    public void setApplicationEnabledSetting(String appPackageName,
15367            int newState, int flags, int userId, String callingPackage) {
15368        if (!sUserManager.exists(userId)) return;
15369        if (callingPackage == null) {
15370            callingPackage = Integer.toString(Binder.getCallingUid());
15371        }
15372        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15373    }
15374
15375    @Override
15376    public void setComponentEnabledSetting(ComponentName componentName,
15377            int newState, int flags, int userId) {
15378        if (!sUserManager.exists(userId)) return;
15379        setEnabledSetting(componentName.getPackageName(),
15380                componentName.getClassName(), newState, flags, userId, null);
15381    }
15382
15383    private void setEnabledSetting(final String packageName, String className, int newState,
15384            final int flags, int userId, String callingPackage) {
15385        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15386              || newState == COMPONENT_ENABLED_STATE_ENABLED
15387              || newState == COMPONENT_ENABLED_STATE_DISABLED
15388              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15389              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15390            throw new IllegalArgumentException("Invalid new component state: "
15391                    + newState);
15392        }
15393        PackageSetting pkgSetting;
15394        final int uid = Binder.getCallingUid();
15395        final int permission = mContext.checkCallingOrSelfPermission(
15396                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15397        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15398        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15399        boolean sendNow = false;
15400        boolean isApp = (className == null);
15401        String componentName = isApp ? packageName : className;
15402        int packageUid = -1;
15403        ArrayList<String> components;
15404
15405        // writer
15406        synchronized (mPackages) {
15407            pkgSetting = mSettings.mPackages.get(packageName);
15408            if (pkgSetting == null) {
15409                if (className == null) {
15410                    throw new IllegalArgumentException("Unknown package: " + packageName);
15411                }
15412                throw new IllegalArgumentException(
15413                        "Unknown component: " + packageName + "/" + className);
15414            }
15415            // Allow root and verify that userId is not being specified by a different user
15416            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15417                throw new SecurityException(
15418                        "Permission Denial: attempt to change component state from pid="
15419                        + Binder.getCallingPid()
15420                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15421            }
15422            if (className == null) {
15423                // We're dealing with an application/package level state change
15424                if (pkgSetting.getEnabled(userId) == newState) {
15425                    // Nothing to do
15426                    return;
15427                }
15428                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15429                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15430                    // Don't care about who enables an app.
15431                    callingPackage = null;
15432                }
15433                pkgSetting.setEnabled(newState, userId, callingPackage);
15434                // pkgSetting.pkg.mSetEnabled = newState;
15435            } else {
15436                // We're dealing with a component level state change
15437                // First, verify that this is a valid class name.
15438                PackageParser.Package pkg = pkgSetting.pkg;
15439                if (pkg == null || !pkg.hasComponentClassName(className)) {
15440                    if (pkg != null &&
15441                            pkg.applicationInfo.targetSdkVersion >=
15442                                    Build.VERSION_CODES.JELLY_BEAN) {
15443                        throw new IllegalArgumentException("Component class " + className
15444                                + " does not exist in " + packageName);
15445                    } else {
15446                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15447                                + className + " does not exist in " + packageName);
15448                    }
15449                }
15450                switch (newState) {
15451                case COMPONENT_ENABLED_STATE_ENABLED:
15452                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15453                        return;
15454                    }
15455                    break;
15456                case COMPONENT_ENABLED_STATE_DISABLED:
15457                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15458                        return;
15459                    }
15460                    break;
15461                case COMPONENT_ENABLED_STATE_DEFAULT:
15462                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15463                        return;
15464                    }
15465                    break;
15466                default:
15467                    Slog.e(TAG, "Invalid new component state: " + newState);
15468                    return;
15469                }
15470            }
15471            scheduleWritePackageRestrictionsLocked(userId);
15472            components = mPendingBroadcasts.get(userId, packageName);
15473            final boolean newPackage = components == null;
15474            if (newPackage) {
15475                components = new ArrayList<String>();
15476            }
15477            if (!components.contains(componentName)) {
15478                components.add(componentName);
15479            }
15480            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15481                sendNow = true;
15482                // Purge entry from pending broadcast list if another one exists already
15483                // since we are sending one right away.
15484                mPendingBroadcasts.remove(userId, packageName);
15485            } else {
15486                if (newPackage) {
15487                    mPendingBroadcasts.put(userId, packageName, components);
15488                }
15489                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15490                    // Schedule a message
15491                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15492                }
15493            }
15494        }
15495
15496        long callingId = Binder.clearCallingIdentity();
15497        try {
15498            if (sendNow) {
15499                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15500                sendPackageChangedBroadcast(packageName,
15501                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15502            }
15503        } finally {
15504            Binder.restoreCallingIdentity(callingId);
15505        }
15506    }
15507
15508    private void sendPackageChangedBroadcast(String packageName,
15509            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15510        if (DEBUG_INSTALL)
15511            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15512                    + componentNames);
15513        Bundle extras = new Bundle(4);
15514        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15515        String nameList[] = new String[componentNames.size()];
15516        componentNames.toArray(nameList);
15517        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15518        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15519        extras.putInt(Intent.EXTRA_UID, packageUid);
15520        // If this is not reporting a change of the overall package, then only send it
15521        // to registered receivers.  We don't want to launch a swath of apps for every
15522        // little component state change.
15523        final int flags = !componentNames.contains(packageName)
15524                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15525        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15526                new int[] {UserHandle.getUserId(packageUid)});
15527    }
15528
15529    @Override
15530    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15531        if (!sUserManager.exists(userId)) return;
15532        final int uid = Binder.getCallingUid();
15533        final int permission = mContext.checkCallingOrSelfPermission(
15534                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15535        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15536        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15537        // writer
15538        synchronized (mPackages) {
15539            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15540                    allowedByPermission, uid, userId)) {
15541                scheduleWritePackageRestrictionsLocked(userId);
15542            }
15543        }
15544    }
15545
15546    @Override
15547    public String getInstallerPackageName(String packageName) {
15548        // reader
15549        synchronized (mPackages) {
15550            return mSettings.getInstallerPackageNameLPr(packageName);
15551        }
15552    }
15553
15554    @Override
15555    public int getApplicationEnabledSetting(String packageName, int userId) {
15556        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15557        int uid = Binder.getCallingUid();
15558        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15559        // reader
15560        synchronized (mPackages) {
15561            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15562        }
15563    }
15564
15565    @Override
15566    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15567        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15568        int uid = Binder.getCallingUid();
15569        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15570        // reader
15571        synchronized (mPackages) {
15572            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15573        }
15574    }
15575
15576    @Override
15577    public void enterSafeMode() {
15578        enforceSystemOrRoot("Only the system can request entering safe mode");
15579
15580        if (!mSystemReady) {
15581            mSafeMode = true;
15582        }
15583    }
15584
15585    @Override
15586    public void systemReady() {
15587        mSystemReady = true;
15588
15589        // Read the compatibilty setting when the system is ready.
15590        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15591                mContext.getContentResolver(),
15592                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15593        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15594        if (DEBUG_SETTINGS) {
15595            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15596        }
15597
15598        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15599
15600        synchronized (mPackages) {
15601            // Verify that all of the preferred activity components actually
15602            // exist.  It is possible for applications to be updated and at
15603            // that point remove a previously declared activity component that
15604            // had been set as a preferred activity.  We try to clean this up
15605            // the next time we encounter that preferred activity, but it is
15606            // possible for the user flow to never be able to return to that
15607            // situation so here we do a sanity check to make sure we haven't
15608            // left any junk around.
15609            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15610            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15611                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15612                removed.clear();
15613                for (PreferredActivity pa : pir.filterSet()) {
15614                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15615                        removed.add(pa);
15616                    }
15617                }
15618                if (removed.size() > 0) {
15619                    for (int r=0; r<removed.size(); r++) {
15620                        PreferredActivity pa = removed.get(r);
15621                        Slog.w(TAG, "Removing dangling preferred activity: "
15622                                + pa.mPref.mComponent);
15623                        pir.removeFilter(pa);
15624                    }
15625                    mSettings.writePackageRestrictionsLPr(
15626                            mSettings.mPreferredActivities.keyAt(i));
15627                }
15628            }
15629
15630            for (int userId : UserManagerService.getInstance().getUserIds()) {
15631                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15632                    grantPermissionsUserIds = ArrayUtils.appendInt(
15633                            grantPermissionsUserIds, userId);
15634                }
15635            }
15636        }
15637        sUserManager.systemReady();
15638
15639        // If we upgraded grant all default permissions before kicking off.
15640        for (int userId : grantPermissionsUserIds) {
15641            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15642        }
15643
15644        // Kick off any messages waiting for system ready
15645        if (mPostSystemReadyMessages != null) {
15646            for (Message msg : mPostSystemReadyMessages) {
15647                msg.sendToTarget();
15648            }
15649            mPostSystemReadyMessages = null;
15650        }
15651
15652        // Watch for external volumes that come and go over time
15653        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15654        storage.registerListener(mStorageListener);
15655
15656        mInstallerService.systemReady();
15657        mPackageDexOptimizer.systemReady();
15658
15659        MountServiceInternal mountServiceInternal = LocalServices.getService(
15660                MountServiceInternal.class);
15661        mountServiceInternal.addExternalStoragePolicy(
15662                new MountServiceInternal.ExternalStorageMountPolicy() {
15663            @Override
15664            public int getMountMode(int uid, String packageName) {
15665                if (Process.isIsolated(uid)) {
15666                    return Zygote.MOUNT_EXTERNAL_NONE;
15667                }
15668                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15669                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15670                }
15671                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15672                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15673                }
15674                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15675                    return Zygote.MOUNT_EXTERNAL_READ;
15676                }
15677                return Zygote.MOUNT_EXTERNAL_WRITE;
15678            }
15679
15680            @Override
15681            public boolean hasExternalStorage(int uid, String packageName) {
15682                return true;
15683            }
15684        });
15685    }
15686
15687    @Override
15688    public boolean isSafeMode() {
15689        return mSafeMode;
15690    }
15691
15692    @Override
15693    public boolean hasSystemUidErrors() {
15694        return mHasSystemUidErrors;
15695    }
15696
15697    static String arrayToString(int[] array) {
15698        StringBuffer buf = new StringBuffer(128);
15699        buf.append('[');
15700        if (array != null) {
15701            for (int i=0; i<array.length; i++) {
15702                if (i > 0) buf.append(", ");
15703                buf.append(array[i]);
15704            }
15705        }
15706        buf.append(']');
15707        return buf.toString();
15708    }
15709
15710    static class DumpState {
15711        public static final int DUMP_LIBS = 1 << 0;
15712        public static final int DUMP_FEATURES = 1 << 1;
15713        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15714        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15715        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15716        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15717        public static final int DUMP_PERMISSIONS = 1 << 6;
15718        public static final int DUMP_PACKAGES = 1 << 7;
15719        public static final int DUMP_SHARED_USERS = 1 << 8;
15720        public static final int DUMP_MESSAGES = 1 << 9;
15721        public static final int DUMP_PROVIDERS = 1 << 10;
15722        public static final int DUMP_VERIFIERS = 1 << 11;
15723        public static final int DUMP_PREFERRED = 1 << 12;
15724        public static final int DUMP_PREFERRED_XML = 1 << 13;
15725        public static final int DUMP_KEYSETS = 1 << 14;
15726        public static final int DUMP_VERSION = 1 << 15;
15727        public static final int DUMP_INSTALLS = 1 << 16;
15728        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15729        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15730
15731        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15732
15733        private int mTypes;
15734
15735        private int mOptions;
15736
15737        private boolean mTitlePrinted;
15738
15739        private SharedUserSetting mSharedUser;
15740
15741        public boolean isDumping(int type) {
15742            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15743                return true;
15744            }
15745
15746            return (mTypes & type) != 0;
15747        }
15748
15749        public void setDump(int type) {
15750            mTypes |= type;
15751        }
15752
15753        public boolean isOptionEnabled(int option) {
15754            return (mOptions & option) != 0;
15755        }
15756
15757        public void setOptionEnabled(int option) {
15758            mOptions |= option;
15759        }
15760
15761        public boolean onTitlePrinted() {
15762            final boolean printed = mTitlePrinted;
15763            mTitlePrinted = true;
15764            return printed;
15765        }
15766
15767        public boolean getTitlePrinted() {
15768            return mTitlePrinted;
15769        }
15770
15771        public void setTitlePrinted(boolean enabled) {
15772            mTitlePrinted = enabled;
15773        }
15774
15775        public SharedUserSetting getSharedUser() {
15776            return mSharedUser;
15777        }
15778
15779        public void setSharedUser(SharedUserSetting user) {
15780            mSharedUser = user;
15781        }
15782    }
15783
15784    @Override
15785    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15786            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15787        (new PackageManagerShellCommand(this)).exec(
15788                this, in, out, err, args, resultReceiver);
15789    }
15790
15791    @Override
15792    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15793        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15794                != PackageManager.PERMISSION_GRANTED) {
15795            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15796                    + Binder.getCallingPid()
15797                    + ", uid=" + Binder.getCallingUid()
15798                    + " without permission "
15799                    + android.Manifest.permission.DUMP);
15800            return;
15801        }
15802
15803        DumpState dumpState = new DumpState();
15804        boolean fullPreferred = false;
15805        boolean checkin = false;
15806
15807        String packageName = null;
15808        ArraySet<String> permissionNames = null;
15809
15810        int opti = 0;
15811        while (opti < args.length) {
15812            String opt = args[opti];
15813            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15814                break;
15815            }
15816            opti++;
15817
15818            if ("-a".equals(opt)) {
15819                // Right now we only know how to print all.
15820            } else if ("-h".equals(opt)) {
15821                pw.println("Package manager dump options:");
15822                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15823                pw.println("    --checkin: dump for a checkin");
15824                pw.println("    -f: print details of intent filters");
15825                pw.println("    -h: print this help");
15826                pw.println("  cmd may be one of:");
15827                pw.println("    l[ibraries]: list known shared libraries");
15828                pw.println("    f[eatures]: list device features");
15829                pw.println("    k[eysets]: print known keysets");
15830                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15831                pw.println("    perm[issions]: dump permissions");
15832                pw.println("    permission [name ...]: dump declaration and use of given permission");
15833                pw.println("    pref[erred]: print preferred package settings");
15834                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15835                pw.println("    prov[iders]: dump content providers");
15836                pw.println("    p[ackages]: dump installed packages");
15837                pw.println("    s[hared-users]: dump shared user IDs");
15838                pw.println("    m[essages]: print collected runtime messages");
15839                pw.println("    v[erifiers]: print package verifier info");
15840                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15841                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15842                pw.println("    version: print database version info");
15843                pw.println("    write: write current settings now");
15844                pw.println("    installs: details about install sessions");
15845                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15846                pw.println("    <package.name>: info about given package");
15847                return;
15848            } else if ("--checkin".equals(opt)) {
15849                checkin = true;
15850            } else if ("-f".equals(opt)) {
15851                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15852            } else {
15853                pw.println("Unknown argument: " + opt + "; use -h for help");
15854            }
15855        }
15856
15857        // Is the caller requesting to dump a particular piece of data?
15858        if (opti < args.length) {
15859            String cmd = args[opti];
15860            opti++;
15861            // Is this a package name?
15862            if ("android".equals(cmd) || cmd.contains(".")) {
15863                packageName = cmd;
15864                // When dumping a single package, we always dump all of its
15865                // filter information since the amount of data will be reasonable.
15866                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15867            } else if ("check-permission".equals(cmd)) {
15868                if (opti >= args.length) {
15869                    pw.println("Error: check-permission missing permission argument");
15870                    return;
15871                }
15872                String perm = args[opti];
15873                opti++;
15874                if (opti >= args.length) {
15875                    pw.println("Error: check-permission missing package argument");
15876                    return;
15877                }
15878                String pkg = args[opti];
15879                opti++;
15880                int user = UserHandle.getUserId(Binder.getCallingUid());
15881                if (opti < args.length) {
15882                    try {
15883                        user = Integer.parseInt(args[opti]);
15884                    } catch (NumberFormatException e) {
15885                        pw.println("Error: check-permission user argument is not a number: "
15886                                + args[opti]);
15887                        return;
15888                    }
15889                }
15890                pw.println(checkPermission(perm, pkg, user));
15891                return;
15892            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15893                dumpState.setDump(DumpState.DUMP_LIBS);
15894            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15895                dumpState.setDump(DumpState.DUMP_FEATURES);
15896            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15897                if (opti >= args.length) {
15898                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15899                            | DumpState.DUMP_SERVICE_RESOLVERS
15900                            | DumpState.DUMP_RECEIVER_RESOLVERS
15901                            | DumpState.DUMP_CONTENT_RESOLVERS);
15902                } else {
15903                    while (opti < args.length) {
15904                        String name = args[opti];
15905                        if ("a".equals(name) || "activity".equals(name)) {
15906                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15907                        } else if ("s".equals(name) || "service".equals(name)) {
15908                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15909                        } else if ("r".equals(name) || "receiver".equals(name)) {
15910                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15911                        } else if ("c".equals(name) || "content".equals(name)) {
15912                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15913                        } else {
15914                            pw.println("Error: unknown resolver table type: " + name);
15915                            return;
15916                        }
15917                        opti++;
15918                    }
15919                }
15920            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15921                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15922            } else if ("permission".equals(cmd)) {
15923                if (opti >= args.length) {
15924                    pw.println("Error: permission requires permission name");
15925                    return;
15926                }
15927                permissionNames = new ArraySet<>();
15928                while (opti < args.length) {
15929                    permissionNames.add(args[opti]);
15930                    opti++;
15931                }
15932                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15933                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15934            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15935                dumpState.setDump(DumpState.DUMP_PREFERRED);
15936            } else if ("preferred-xml".equals(cmd)) {
15937                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15938                if (opti < args.length && "--full".equals(args[opti])) {
15939                    fullPreferred = true;
15940                    opti++;
15941                }
15942            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15943                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15944            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15945                dumpState.setDump(DumpState.DUMP_PACKAGES);
15946            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15947                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15948            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15949                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15950            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15951                dumpState.setDump(DumpState.DUMP_MESSAGES);
15952            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15953                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15954            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15955                    || "intent-filter-verifiers".equals(cmd)) {
15956                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15957            } else if ("version".equals(cmd)) {
15958                dumpState.setDump(DumpState.DUMP_VERSION);
15959            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15960                dumpState.setDump(DumpState.DUMP_KEYSETS);
15961            } else if ("installs".equals(cmd)) {
15962                dumpState.setDump(DumpState.DUMP_INSTALLS);
15963            } else if ("write".equals(cmd)) {
15964                synchronized (mPackages) {
15965                    mSettings.writeLPr();
15966                    pw.println("Settings written.");
15967                    return;
15968                }
15969            }
15970        }
15971
15972        if (checkin) {
15973            pw.println("vers,1");
15974        }
15975
15976        // reader
15977        synchronized (mPackages) {
15978            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15979                if (!checkin) {
15980                    if (dumpState.onTitlePrinted())
15981                        pw.println();
15982                    pw.println("Database versions:");
15983                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15984                }
15985            }
15986
15987            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15988                if (!checkin) {
15989                    if (dumpState.onTitlePrinted())
15990                        pw.println();
15991                    pw.println("Verifiers:");
15992                    pw.print("  Required: ");
15993                    pw.print(mRequiredVerifierPackage);
15994                    pw.print(" (uid=");
15995                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15996                            UserHandle.USER_SYSTEM));
15997                    pw.println(")");
15998                } else if (mRequiredVerifierPackage != null) {
15999                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
16000                    pw.print(",");
16001                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
16002                            UserHandle.USER_SYSTEM));
16003                }
16004            }
16005
16006            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
16007                    packageName == null) {
16008                if (mIntentFilterVerifierComponent != null) {
16009                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
16010                    if (!checkin) {
16011                        if (dumpState.onTitlePrinted())
16012                            pw.println();
16013                        pw.println("Intent Filter Verifier:");
16014                        pw.print("  Using: ");
16015                        pw.print(verifierPackageName);
16016                        pw.print(" (uid=");
16017                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16018                                UserHandle.USER_SYSTEM));
16019                        pw.println(")");
16020                    } else if (verifierPackageName != null) {
16021                        pw.print("ifv,"); pw.print(verifierPackageName);
16022                        pw.print(",");
16023                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
16024                                UserHandle.USER_SYSTEM));
16025                    }
16026                } else {
16027                    pw.println();
16028                    pw.println("No Intent Filter Verifier available!");
16029                }
16030            }
16031
16032            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
16033                boolean printedHeader = false;
16034                final Iterator<String> it = mSharedLibraries.keySet().iterator();
16035                while (it.hasNext()) {
16036                    String name = it.next();
16037                    SharedLibraryEntry ent = mSharedLibraries.get(name);
16038                    if (!checkin) {
16039                        if (!printedHeader) {
16040                            if (dumpState.onTitlePrinted())
16041                                pw.println();
16042                            pw.println("Libraries:");
16043                            printedHeader = true;
16044                        }
16045                        pw.print("  ");
16046                    } else {
16047                        pw.print("lib,");
16048                    }
16049                    pw.print(name);
16050                    if (!checkin) {
16051                        pw.print(" -> ");
16052                    }
16053                    if (ent.path != null) {
16054                        if (!checkin) {
16055                            pw.print("(jar) ");
16056                            pw.print(ent.path);
16057                        } else {
16058                            pw.print(",jar,");
16059                            pw.print(ent.path);
16060                        }
16061                    } else {
16062                        if (!checkin) {
16063                            pw.print("(apk) ");
16064                            pw.print(ent.apk);
16065                        } else {
16066                            pw.print(",apk,");
16067                            pw.print(ent.apk);
16068                        }
16069                    }
16070                    pw.println();
16071                }
16072            }
16073
16074            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
16075                if (dumpState.onTitlePrinted())
16076                    pw.println();
16077                if (!checkin) {
16078                    pw.println("Features:");
16079                }
16080                Iterator<String> it = mAvailableFeatures.keySet().iterator();
16081                while (it.hasNext()) {
16082                    String name = it.next();
16083                    if (!checkin) {
16084                        pw.print("  ");
16085                    } else {
16086                        pw.print("feat,");
16087                    }
16088                    pw.println(name);
16089                }
16090            }
16091
16092            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
16093                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
16094                        : "Activity Resolver Table:", "  ", packageName,
16095                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16096                    dumpState.setTitlePrinted(true);
16097                }
16098            }
16099            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
16100                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
16101                        : "Receiver Resolver Table:", "  ", packageName,
16102                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16103                    dumpState.setTitlePrinted(true);
16104                }
16105            }
16106            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
16107                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
16108                        : "Service Resolver Table:", "  ", packageName,
16109                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16110                    dumpState.setTitlePrinted(true);
16111                }
16112            }
16113            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
16114                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
16115                        : "Provider Resolver Table:", "  ", packageName,
16116                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
16117                    dumpState.setTitlePrinted(true);
16118                }
16119            }
16120
16121            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
16122                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16123                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16124                    int user = mSettings.mPreferredActivities.keyAt(i);
16125                    if (pir.dump(pw,
16126                            dumpState.getTitlePrinted()
16127                                ? "\nPreferred Activities User " + user + ":"
16128                                : "Preferred Activities User " + user + ":", "  ",
16129                            packageName, true, false)) {
16130                        dumpState.setTitlePrinted(true);
16131                    }
16132                }
16133            }
16134
16135            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
16136                pw.flush();
16137                FileOutputStream fout = new FileOutputStream(fd);
16138                BufferedOutputStream str = new BufferedOutputStream(fout);
16139                XmlSerializer serializer = new FastXmlSerializer();
16140                try {
16141                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
16142                    serializer.startDocument(null, true);
16143                    serializer.setFeature(
16144                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
16145                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
16146                    serializer.endDocument();
16147                    serializer.flush();
16148                } catch (IllegalArgumentException e) {
16149                    pw.println("Failed writing: " + e);
16150                } catch (IllegalStateException e) {
16151                    pw.println("Failed writing: " + e);
16152                } catch (IOException e) {
16153                    pw.println("Failed writing: " + e);
16154                }
16155            }
16156
16157            if (!checkin
16158                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
16159                    && packageName == null) {
16160                pw.println();
16161                int count = mSettings.mPackages.size();
16162                if (count == 0) {
16163                    pw.println("No applications!");
16164                    pw.println();
16165                } else {
16166                    final String prefix = "  ";
16167                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
16168                    if (allPackageSettings.size() == 0) {
16169                        pw.println("No domain preferred apps!");
16170                        pw.println();
16171                    } else {
16172                        pw.println("App verification status:");
16173                        pw.println();
16174                        count = 0;
16175                        for (PackageSetting ps : allPackageSettings) {
16176                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
16177                            if (ivi == null || ivi.getPackageName() == null) continue;
16178                            pw.println(prefix + "Package: " + ivi.getPackageName());
16179                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
16180                            pw.println(prefix + "Status:  " + ivi.getStatusString());
16181                            pw.println();
16182                            count++;
16183                        }
16184                        if (count == 0) {
16185                            pw.println(prefix + "No app verification established.");
16186                            pw.println();
16187                        }
16188                        for (int userId : sUserManager.getUserIds()) {
16189                            pw.println("App linkages for user " + userId + ":");
16190                            pw.println();
16191                            count = 0;
16192                            for (PackageSetting ps : allPackageSettings) {
16193                                final long status = ps.getDomainVerificationStatusForUser(userId);
16194                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
16195                                    continue;
16196                                }
16197                                pw.println(prefix + "Package: " + ps.name);
16198                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
16199                                String statusStr = IntentFilterVerificationInfo.
16200                                        getStatusStringFromValue(status);
16201                                pw.println(prefix + "Status:  " + statusStr);
16202                                pw.println();
16203                                count++;
16204                            }
16205                            if (count == 0) {
16206                                pw.println(prefix + "No configured app linkages.");
16207                                pw.println();
16208                            }
16209                        }
16210                    }
16211                }
16212            }
16213
16214            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
16215                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
16216                if (packageName == null && permissionNames == null) {
16217                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
16218                        if (iperm == 0) {
16219                            if (dumpState.onTitlePrinted())
16220                                pw.println();
16221                            pw.println("AppOp Permissions:");
16222                        }
16223                        pw.print("  AppOp Permission ");
16224                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
16225                        pw.println(":");
16226                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
16227                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
16228                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
16229                        }
16230                    }
16231                }
16232            }
16233
16234            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
16235                boolean printedSomething = false;
16236                for (PackageParser.Provider p : mProviders.mProviders.values()) {
16237                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16238                        continue;
16239                    }
16240                    if (!printedSomething) {
16241                        if (dumpState.onTitlePrinted())
16242                            pw.println();
16243                        pw.println("Registered ContentProviders:");
16244                        printedSomething = true;
16245                    }
16246                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
16247                    pw.print("    "); pw.println(p.toString());
16248                }
16249                printedSomething = false;
16250                for (Map.Entry<String, PackageParser.Provider> entry :
16251                        mProvidersByAuthority.entrySet()) {
16252                    PackageParser.Provider p = entry.getValue();
16253                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16254                        continue;
16255                    }
16256                    if (!printedSomething) {
16257                        if (dumpState.onTitlePrinted())
16258                            pw.println();
16259                        pw.println("ContentProvider Authorities:");
16260                        printedSomething = true;
16261                    }
16262                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16263                    pw.print("    "); pw.println(p.toString());
16264                    if (p.info != null && p.info.applicationInfo != null) {
16265                        final String appInfo = p.info.applicationInfo.toString();
16266                        pw.print("      applicationInfo="); pw.println(appInfo);
16267                    }
16268                }
16269            }
16270
16271            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16272                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16273            }
16274
16275            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16276                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16277            }
16278
16279            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16280                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16281            }
16282
16283            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
16284                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
16285            }
16286
16287            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16288                // XXX should handle packageName != null by dumping only install data that
16289                // the given package is involved with.
16290                if (dumpState.onTitlePrinted()) pw.println();
16291                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16292            }
16293
16294            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16295                if (dumpState.onTitlePrinted()) pw.println();
16296                mSettings.dumpReadMessagesLPr(pw, dumpState);
16297
16298                pw.println();
16299                pw.println("Package warning messages:");
16300                BufferedReader in = null;
16301                String line = null;
16302                try {
16303                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16304                    while ((line = in.readLine()) != null) {
16305                        if (line.contains("ignored: updated version")) continue;
16306                        pw.println(line);
16307                    }
16308                } catch (IOException ignored) {
16309                } finally {
16310                    IoUtils.closeQuietly(in);
16311                }
16312            }
16313
16314            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16315                BufferedReader in = null;
16316                String line = null;
16317                try {
16318                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16319                    while ((line = in.readLine()) != null) {
16320                        if (line.contains("ignored: updated version")) continue;
16321                        pw.print("msg,");
16322                        pw.println(line);
16323                    }
16324                } catch (IOException ignored) {
16325                } finally {
16326                    IoUtils.closeQuietly(in);
16327                }
16328            }
16329        }
16330    }
16331
16332    private String dumpDomainString(String packageName) {
16333        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16334        List<IntentFilter> filters = getAllIntentFilters(packageName);
16335
16336        ArraySet<String> result = new ArraySet<>();
16337        if (iviList.size() > 0) {
16338            for (IntentFilterVerificationInfo ivi : iviList) {
16339                for (String host : ivi.getDomains()) {
16340                    result.add(host);
16341                }
16342            }
16343        }
16344        if (filters != null && filters.size() > 0) {
16345            for (IntentFilter filter : filters) {
16346                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16347                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16348                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16349                    result.addAll(filter.getHostsList());
16350                }
16351            }
16352        }
16353
16354        StringBuilder sb = new StringBuilder(result.size() * 16);
16355        for (String domain : result) {
16356            if (sb.length() > 0) sb.append(" ");
16357            sb.append(domain);
16358        }
16359        return sb.toString();
16360    }
16361
16362    // ------- apps on sdcard specific code -------
16363    static final boolean DEBUG_SD_INSTALL = false;
16364
16365    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16366
16367    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16368
16369    private boolean mMediaMounted = false;
16370
16371    static String getEncryptKey() {
16372        try {
16373            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16374                    SD_ENCRYPTION_KEYSTORE_NAME);
16375            if (sdEncKey == null) {
16376                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16377                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16378                if (sdEncKey == null) {
16379                    Slog.e(TAG, "Failed to create encryption keys");
16380                    return null;
16381                }
16382            }
16383            return sdEncKey;
16384        } catch (NoSuchAlgorithmException nsae) {
16385            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16386            return null;
16387        } catch (IOException ioe) {
16388            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16389            return null;
16390        }
16391    }
16392
16393    /*
16394     * Update media status on PackageManager.
16395     */
16396    @Override
16397    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16398        int callingUid = Binder.getCallingUid();
16399        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16400            throw new SecurityException("Media status can only be updated by the system");
16401        }
16402        // reader; this apparently protects mMediaMounted, but should probably
16403        // be a different lock in that case.
16404        synchronized (mPackages) {
16405            Log.i(TAG, "Updating external media status from "
16406                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16407                    + (mediaStatus ? "mounted" : "unmounted"));
16408            if (DEBUG_SD_INSTALL)
16409                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16410                        + ", mMediaMounted=" + mMediaMounted);
16411            if (mediaStatus == mMediaMounted) {
16412                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16413                        : 0, -1);
16414                mHandler.sendMessage(msg);
16415                return;
16416            }
16417            mMediaMounted = mediaStatus;
16418        }
16419        // Queue up an async operation since the package installation may take a
16420        // little while.
16421        mHandler.post(new Runnable() {
16422            public void run() {
16423                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16424            }
16425        });
16426    }
16427
16428    /**
16429     * Called by MountService when the initial ASECs to scan are available.
16430     * Should block until all the ASEC containers are finished being scanned.
16431     */
16432    public void scanAvailableAsecs() {
16433        updateExternalMediaStatusInner(true, false, false);
16434    }
16435
16436    /*
16437     * Collect information of applications on external media, map them against
16438     * existing containers and update information based on current mount status.
16439     * Please note that we always have to report status if reportStatus has been
16440     * set to true especially when unloading packages.
16441     */
16442    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16443            boolean externalStorage) {
16444        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16445        int[] uidArr = EmptyArray.INT;
16446
16447        final String[] list = PackageHelper.getSecureContainerList();
16448        if (ArrayUtils.isEmpty(list)) {
16449            Log.i(TAG, "No secure containers found");
16450        } else {
16451            // Process list of secure containers and categorize them
16452            // as active or stale based on their package internal state.
16453
16454            // reader
16455            synchronized (mPackages) {
16456                for (String cid : list) {
16457                    // Leave stages untouched for now; installer service owns them
16458                    if (PackageInstallerService.isStageName(cid)) continue;
16459
16460                    if (DEBUG_SD_INSTALL)
16461                        Log.i(TAG, "Processing container " + cid);
16462                    String pkgName = getAsecPackageName(cid);
16463                    if (pkgName == null) {
16464                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16465                        continue;
16466                    }
16467                    if (DEBUG_SD_INSTALL)
16468                        Log.i(TAG, "Looking for pkg : " + pkgName);
16469
16470                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16471                    if (ps == null) {
16472                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16473                        continue;
16474                    }
16475
16476                    /*
16477                     * Skip packages that are not external if we're unmounting
16478                     * external storage.
16479                     */
16480                    if (externalStorage && !isMounted && !isExternal(ps)) {
16481                        continue;
16482                    }
16483
16484                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16485                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16486                    // The package status is changed only if the code path
16487                    // matches between settings and the container id.
16488                    if (ps.codePathString != null
16489                            && ps.codePathString.startsWith(args.getCodePath())) {
16490                        if (DEBUG_SD_INSTALL) {
16491                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16492                                    + " at code path: " + ps.codePathString);
16493                        }
16494
16495                        // We do have a valid package installed on sdcard
16496                        processCids.put(args, ps.codePathString);
16497                        final int uid = ps.appId;
16498                        if (uid != -1) {
16499                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16500                        }
16501                    } else {
16502                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16503                                + ps.codePathString);
16504                    }
16505                }
16506            }
16507
16508            Arrays.sort(uidArr);
16509        }
16510
16511        // Process packages with valid entries.
16512        if (isMounted) {
16513            if (DEBUG_SD_INSTALL)
16514                Log.i(TAG, "Loading packages");
16515            loadMediaPackages(processCids, uidArr, externalStorage);
16516            startCleaningPackages();
16517            mInstallerService.onSecureContainersAvailable();
16518        } else {
16519            if (DEBUG_SD_INSTALL)
16520                Log.i(TAG, "Unloading packages");
16521            unloadMediaPackages(processCids, uidArr, reportStatus);
16522        }
16523    }
16524
16525    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16526            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16527        final int size = infos.size();
16528        final String[] packageNames = new String[size];
16529        final int[] packageUids = new int[size];
16530        for (int i = 0; i < size; i++) {
16531            final ApplicationInfo info = infos.get(i);
16532            packageNames[i] = info.packageName;
16533            packageUids[i] = info.uid;
16534        }
16535        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16536                finishedReceiver);
16537    }
16538
16539    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16540            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16541        sendResourcesChangedBroadcast(mediaStatus, replacing,
16542                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16543    }
16544
16545    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16546            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16547        int size = pkgList.length;
16548        if (size > 0) {
16549            // Send broadcasts here
16550            Bundle extras = new Bundle();
16551            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16552            if (uidArr != null) {
16553                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16554            }
16555            if (replacing) {
16556                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16557            }
16558            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16559                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16560            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16561        }
16562    }
16563
16564   /*
16565     * Look at potentially valid container ids from processCids If package
16566     * information doesn't match the one on record or package scanning fails,
16567     * the cid is added to list of removeCids. We currently don't delete stale
16568     * containers.
16569     */
16570    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16571            boolean externalStorage) {
16572        ArrayList<String> pkgList = new ArrayList<String>();
16573        Set<AsecInstallArgs> keys = processCids.keySet();
16574
16575        for (AsecInstallArgs args : keys) {
16576            String codePath = processCids.get(args);
16577            if (DEBUG_SD_INSTALL)
16578                Log.i(TAG, "Loading container : " + args.cid);
16579            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16580            try {
16581                // Make sure there are no container errors first.
16582                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16583                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16584                            + " when installing from sdcard");
16585                    continue;
16586                }
16587                // Check code path here.
16588                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16589                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16590                            + " does not match one in settings " + codePath);
16591                    continue;
16592                }
16593                // Parse package
16594                int parseFlags = mDefParseFlags;
16595                if (args.isExternalAsec()) {
16596                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16597                }
16598                if (args.isFwdLocked()) {
16599                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16600                }
16601
16602                synchronized (mInstallLock) {
16603                    PackageParser.Package pkg = null;
16604                    try {
16605                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16606                    } catch (PackageManagerException e) {
16607                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16608                    }
16609                    // Scan the package
16610                    if (pkg != null) {
16611                        /*
16612                         * TODO why is the lock being held? doPostInstall is
16613                         * called in other places without the lock. This needs
16614                         * to be straightened out.
16615                         */
16616                        // writer
16617                        synchronized (mPackages) {
16618                            retCode = PackageManager.INSTALL_SUCCEEDED;
16619                            pkgList.add(pkg.packageName);
16620                            // Post process args
16621                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16622                                    pkg.applicationInfo.uid);
16623                        }
16624                    } else {
16625                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16626                    }
16627                }
16628
16629            } finally {
16630                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16631                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16632                }
16633            }
16634        }
16635        // writer
16636        synchronized (mPackages) {
16637            // If the platform SDK has changed since the last time we booted,
16638            // we need to re-grant app permission to catch any new ones that
16639            // appear. This is really a hack, and means that apps can in some
16640            // cases get permissions that the user didn't initially explicitly
16641            // allow... it would be nice to have some better way to handle
16642            // this situation.
16643            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16644                    : mSettings.getInternalVersion();
16645            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16646                    : StorageManager.UUID_PRIVATE_INTERNAL;
16647
16648            int updateFlags = UPDATE_PERMISSIONS_ALL;
16649            if (ver.sdkVersion != mSdkVersion) {
16650                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16651                        + mSdkVersion + "; regranting permissions for external");
16652                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16653            }
16654            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16655
16656            // Yay, everything is now upgraded
16657            ver.forceCurrent();
16658
16659            // can downgrade to reader
16660            // Persist settings
16661            mSettings.writeLPr();
16662        }
16663        // Send a broadcast to let everyone know we are done processing
16664        if (pkgList.size() > 0) {
16665            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16666        }
16667    }
16668
16669   /*
16670     * Utility method to unload a list of specified containers
16671     */
16672    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16673        // Just unmount all valid containers.
16674        for (AsecInstallArgs arg : cidArgs) {
16675            synchronized (mInstallLock) {
16676                arg.doPostDeleteLI(false);
16677           }
16678       }
16679   }
16680
16681    /*
16682     * Unload packages mounted on external media. This involves deleting package
16683     * data from internal structures, sending broadcasts about diabled packages,
16684     * gc'ing to free up references, unmounting all secure containers
16685     * corresponding to packages on external media, and posting a
16686     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16687     * that we always have to post this message if status has been requested no
16688     * matter what.
16689     */
16690    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16691            final boolean reportStatus) {
16692        if (DEBUG_SD_INSTALL)
16693            Log.i(TAG, "unloading media packages");
16694        ArrayList<String> pkgList = new ArrayList<String>();
16695        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16696        final Set<AsecInstallArgs> keys = processCids.keySet();
16697        for (AsecInstallArgs args : keys) {
16698            String pkgName = args.getPackageName();
16699            if (DEBUG_SD_INSTALL)
16700                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16701            // Delete package internally
16702            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16703            synchronized (mInstallLock) {
16704                boolean res = deletePackageLI(pkgName, null, false, null, null,
16705                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16706                if (res) {
16707                    pkgList.add(pkgName);
16708                } else {
16709                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16710                    failedList.add(args);
16711                }
16712            }
16713        }
16714
16715        // reader
16716        synchronized (mPackages) {
16717            // We didn't update the settings after removing each package;
16718            // write them now for all packages.
16719            mSettings.writeLPr();
16720        }
16721
16722        // We have to absolutely send UPDATED_MEDIA_STATUS only
16723        // after confirming that all the receivers processed the ordered
16724        // broadcast when packages get disabled, force a gc to clean things up.
16725        // and unload all the containers.
16726        if (pkgList.size() > 0) {
16727            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16728                    new IIntentReceiver.Stub() {
16729                public void performReceive(Intent intent, int resultCode, String data,
16730                        Bundle extras, boolean ordered, boolean sticky,
16731                        int sendingUser) throws RemoteException {
16732                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16733                            reportStatus ? 1 : 0, 1, keys);
16734                    mHandler.sendMessage(msg);
16735                }
16736            });
16737        } else {
16738            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16739                    keys);
16740            mHandler.sendMessage(msg);
16741        }
16742    }
16743
16744    private void loadPrivatePackages(final VolumeInfo vol) {
16745        mHandler.post(new Runnable() {
16746            @Override
16747            public void run() {
16748                loadPrivatePackagesInner(vol);
16749            }
16750        });
16751    }
16752
16753    private void loadPrivatePackagesInner(VolumeInfo vol) {
16754        final String volumeUuid = vol.fsUuid;
16755        if (TextUtils.isEmpty(volumeUuid)) {
16756            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16757            return;
16758        }
16759
16760        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16761        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16762
16763        final VersionInfo ver;
16764        final List<PackageSetting> packages;
16765        synchronized (mPackages) {
16766            ver = mSettings.findOrCreateVersion(volumeUuid);
16767            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16768        }
16769
16770        // TODO: introduce a new concept similar to "frozen" to prevent these
16771        // apps from being launched until after data has been fully reconciled
16772        for (PackageSetting ps : packages) {
16773            synchronized (mInstallLock) {
16774                final PackageParser.Package pkg;
16775                try {
16776                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16777                    loaded.add(pkg.applicationInfo);
16778
16779                } catch (PackageManagerException e) {
16780                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16781                }
16782
16783                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16784                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16785                }
16786            }
16787        }
16788
16789        // Reconcile app data for all started/unlocked users
16790        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16791        final UserManager um = mContext.getSystemService(UserManager.class);
16792        for (UserInfo user : um.getUsers()) {
16793            final int flags;
16794            if (um.isUserUnlocked(user.id)) {
16795                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16796            } else if (um.isUserRunning(user.id)) {
16797                flags = StorageManager.FLAG_STORAGE_DE;
16798            } else {
16799                continue;
16800            }
16801
16802            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
16803            reconcileAppsData(volumeUuid, user.id, flags);
16804        }
16805
16806        synchronized (mPackages) {
16807            int updateFlags = UPDATE_PERMISSIONS_ALL;
16808            if (ver.sdkVersion != mSdkVersion) {
16809                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16810                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16811                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16812            }
16813            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16814
16815            // Yay, everything is now upgraded
16816            ver.forceCurrent();
16817
16818            mSettings.writeLPr();
16819        }
16820
16821        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16822        sendResourcesChangedBroadcast(true, false, loaded, null);
16823    }
16824
16825    private void unloadPrivatePackages(final VolumeInfo vol) {
16826        mHandler.post(new Runnable() {
16827            @Override
16828            public void run() {
16829                unloadPrivatePackagesInner(vol);
16830            }
16831        });
16832    }
16833
16834    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16835        final String volumeUuid = vol.fsUuid;
16836        if (TextUtils.isEmpty(volumeUuid)) {
16837            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16838            return;
16839        }
16840
16841        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16842        synchronized (mInstallLock) {
16843        synchronized (mPackages) {
16844            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16845            for (PackageSetting ps : packages) {
16846                if (ps.pkg == null) continue;
16847
16848                final ApplicationInfo info = ps.pkg.applicationInfo;
16849                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16850                if (deletePackageLI(ps.name, null, false, null, null,
16851                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16852                    unloaded.add(info);
16853                } else {
16854                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16855                }
16856            }
16857
16858            mSettings.writeLPr();
16859        }
16860        }
16861
16862        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16863        sendResourcesChangedBroadcast(false, false, unloaded, null);
16864    }
16865
16866    /**
16867     * Examine all users present on given mounted volume, and destroy data
16868     * belonging to users that are no longer valid, or whose user ID has been
16869     * recycled.
16870     */
16871    private void reconcileUsers(String volumeUuid) {
16872        final File[] files = FileUtils
16873                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16874        for (File file : files) {
16875            if (!file.isDirectory()) continue;
16876
16877            final int userId;
16878            final UserInfo info;
16879            try {
16880                userId = Integer.parseInt(file.getName());
16881                info = sUserManager.getUserInfo(userId);
16882            } catch (NumberFormatException e) {
16883                Slog.w(TAG, "Invalid user directory " + file);
16884                continue;
16885            }
16886
16887            boolean destroyUser = false;
16888            if (info == null) {
16889                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16890                        + " because no matching user was found");
16891                destroyUser = true;
16892            } else {
16893                try {
16894                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16895                } catch (IOException e) {
16896                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16897                            + " because we failed to enforce serial number: " + e);
16898                    destroyUser = true;
16899                }
16900            }
16901
16902            if (destroyUser) {
16903                synchronized (mInstallLock) {
16904                    try {
16905                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16906                    } catch (InstallerException e) {
16907                        Slog.w(TAG, "Failed to clean up user dirs", e);
16908                    }
16909                }
16910            }
16911        }
16912    }
16913
16914    private void assertPackageKnown(String volumeUuid, String packageName)
16915            throws PackageManagerException {
16916        synchronized (mPackages) {
16917            final PackageSetting ps = mSettings.mPackages.get(packageName);
16918            if (ps == null) {
16919                throw new PackageManagerException("Package " + packageName + " is unknown");
16920            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16921                throw new PackageManagerException(
16922                        "Package " + packageName + " found on unknown volume " + volumeUuid
16923                                + "; expected volume " + ps.volumeUuid);
16924            }
16925        }
16926    }
16927
16928    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16929            throws PackageManagerException {
16930        synchronized (mPackages) {
16931            final PackageSetting ps = mSettings.mPackages.get(packageName);
16932            if (ps == null) {
16933                throw new PackageManagerException("Package " + packageName + " is unknown");
16934            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16935                throw new PackageManagerException(
16936                        "Package " + packageName + " found on unknown volume " + volumeUuid
16937                                + "; expected volume " + ps.volumeUuid);
16938            } else if (!ps.getInstalled(userId)) {
16939                throw new PackageManagerException(
16940                        "Package " + packageName + " not installed for user " + userId);
16941            }
16942        }
16943    }
16944
16945    /**
16946     * Examine all apps present on given mounted volume, and destroy apps that
16947     * aren't expected, either due to uninstallation or reinstallation on
16948     * another volume.
16949     */
16950    private void reconcileApps(String volumeUuid) {
16951        final File[] files = FileUtils
16952                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16953        for (File file : files) {
16954            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16955                    && !PackageInstallerService.isStageName(file.getName());
16956            if (!isPackage) {
16957                // Ignore entries which are not packages
16958                continue;
16959            }
16960
16961            try {
16962                final PackageLite pkg = PackageParser.parsePackageLite(file,
16963                        PackageParser.PARSE_MUST_BE_APK);
16964                assertPackageKnown(volumeUuid, pkg.packageName);
16965
16966            } catch (PackageParserException | PackageManagerException e) {
16967                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16968                synchronized (mInstallLock) {
16969                    removeCodePathLI(file);
16970                }
16971            }
16972        }
16973    }
16974
16975    /**
16976     * Reconcile all app data for the given user.
16977     * <p>
16978     * Verifies that directories exist and that ownership and labeling is
16979     * correct for all installed apps on all mounted volumes.
16980     */
16981    void reconcileAppsData(int userId, int flags) {
16982        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16983        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16984            final String volumeUuid = vol.getFsUuid();
16985            reconcileAppsData(volumeUuid, userId, flags);
16986        }
16987    }
16988
16989    /**
16990     * Reconcile all app data on given mounted volume.
16991     * <p>
16992     * Destroys app data that isn't expected, either due to uninstallation or
16993     * reinstallation on another volume.
16994     * <p>
16995     * Verifies that directories exist and that ownership and labeling is
16996     * correct for all installed apps.
16997     */
16998    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
16999        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17000                + Integer.toHexString(flags));
17001
17002        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
17003        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
17004
17005        boolean restoreconNeeded = false;
17006
17007        // First look for stale data that doesn't belong, and check if things
17008        // have changed since we did our last restorecon
17009        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17010            if (!isUserKeyUnlocked(userId)) {
17011                throw new RuntimeException(
17012                        "Yikes, someone asked us to reconcile CE storage while " + userId
17013                                + " was still locked; this would have caused massive data loss!");
17014            }
17015
17016            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17017
17018            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17019            for (File file : files) {
17020                final String packageName = file.getName();
17021                try {
17022                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17023                } catch (PackageManagerException e) {
17024                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17025                    synchronized (mInstallLock) {
17026                        destroyAppDataLI(volumeUuid, packageName, userId,
17027                                StorageManager.FLAG_STORAGE_CE);
17028                    }
17029                }
17030            }
17031        }
17032        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17033            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17034
17035            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17036            for (File file : files) {
17037                final String packageName = file.getName();
17038                try {
17039                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17040                } catch (PackageManagerException e) {
17041                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17042                    synchronized (mInstallLock) {
17043                        destroyAppDataLI(volumeUuid, packageName, userId,
17044                                StorageManager.FLAG_STORAGE_DE);
17045                    }
17046                }
17047            }
17048        }
17049
17050        // Ensure that data directories are ready to roll for all packages
17051        // installed for this volume and user
17052        final List<PackageSetting> packages;
17053        synchronized (mPackages) {
17054            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17055        }
17056        int preparedCount = 0;
17057        for (PackageSetting ps : packages) {
17058            final String packageName = ps.name;
17059            if (ps.pkg == null) {
17060                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17061                // TODO: might be due to legacy ASEC apps; we should circle back
17062                // and reconcile again once they're scanned
17063                continue;
17064            }
17065
17066            if (ps.getInstalled(userId)) {
17067                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17068                preparedCount++;
17069            }
17070        }
17071
17072        if (restoreconNeeded) {
17073            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17074                SELinuxMMAC.setRestoreconDone(ceDir);
17075            }
17076            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
17077                SELinuxMMAC.setRestoreconDone(deDir);
17078            }
17079        }
17080
17081        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17082                + " packages; restoreconNeeded was " + restoreconNeeded);
17083    }
17084
17085    /**
17086     * Prepare app data for the given app just after it was installed or
17087     * upgraded. This method carefully only touches users that it's installed
17088     * for, and it forces a restorecon to handle any seinfo changes.
17089     * <p>
17090     * Verifies that directories exist and that ownership and labeling is
17091     * correct for all installed apps. If there is an ownership mismatch, it
17092     * will try recovering system apps by wiping data; third-party app data is
17093     * left intact.
17094     */
17095    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17096        final PackageSetting ps;
17097        synchronized (mPackages) {
17098            ps = mSettings.mPackages.get(pkg.packageName);
17099        }
17100
17101        final UserManager um = mContext.getSystemService(UserManager.class);
17102        for (UserInfo user : um.getUsers()) {
17103            final int flags;
17104            if (um.isUserUnlocked(user.id)) {
17105                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17106            } else if (um.isUserRunning(user.id)) {
17107                flags = StorageManager.FLAG_STORAGE_DE;
17108            } else {
17109                continue;
17110            }
17111
17112            if (ps.getInstalled(user.id)) {
17113                // Whenever an app changes, force a restorecon of its data
17114                // TODO: when user data is locked, mark that we're still dirty
17115                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17116            }
17117        }
17118    }
17119
17120    /**
17121     * Prepare app data for the given app.
17122     * <p>
17123     * Verifies that directories exist and that ownership and labeling is
17124     * correct for all installed apps. If there is an ownership mismatch, this
17125     * will try recovering system apps by wiping data; third-party app data is
17126     * left intact.
17127     */
17128    private void prepareAppData(String volumeUuid, int userId, int flags,
17129            PackageParser.Package pkg, boolean restoreconNeeded) {
17130        if (DEBUG_APP_DATA) {
17131            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17132                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17133        }
17134
17135        final String packageName = pkg.packageName;
17136        final ApplicationInfo app = pkg.applicationInfo;
17137        final int appId = UserHandle.getAppId(app.uid);
17138
17139        Preconditions.checkNotNull(app.seinfo);
17140
17141        synchronized (mInstallLock) {
17142            try {
17143                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17144                        appId, app.seinfo, app.targetSdkVersion);
17145            } catch (InstallerException e) {
17146                if (app.isSystemApp()) {
17147                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17148                            + ", but trying to recover: " + e);
17149                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17150                    try {
17151                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17152                                appId, app.seinfo, app.targetSdkVersion);
17153                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17154                    } catch (InstallerException e2) {
17155                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17156                    }
17157                } else {
17158                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17159                }
17160            }
17161
17162            if (restoreconNeeded) {
17163                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17164            }
17165
17166            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
17167                // Create a native library symlink only if we have native libraries
17168                // and if the native libraries are 32 bit libraries. We do not provide
17169                // this symlink for 64 bit libraries.
17170                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17171                    final String nativeLibPath = app.nativeLibraryDir;
17172                    try {
17173                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17174                                nativeLibPath, userId);
17175                    } catch (InstallerException e) {
17176                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17177                    }
17178                }
17179            }
17180        }
17181    }
17182
17183    private void unfreezePackage(String packageName) {
17184        synchronized (mPackages) {
17185            final PackageSetting ps = mSettings.mPackages.get(packageName);
17186            if (ps != null) {
17187                ps.frozen = false;
17188            }
17189        }
17190    }
17191
17192    @Override
17193    public int movePackage(final String packageName, final String volumeUuid) {
17194        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17195
17196        final int moveId = mNextMoveId.getAndIncrement();
17197        mHandler.post(new Runnable() {
17198            @Override
17199            public void run() {
17200                try {
17201                    movePackageInternal(packageName, volumeUuid, moveId);
17202                } catch (PackageManagerException e) {
17203                    Slog.w(TAG, "Failed to move " + packageName, e);
17204                    mMoveCallbacks.notifyStatusChanged(moveId,
17205                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17206                }
17207            }
17208        });
17209        return moveId;
17210    }
17211
17212    private void movePackageInternal(final String packageName, final String volumeUuid,
17213            final int moveId) throws PackageManagerException {
17214        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17215        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17216        final PackageManager pm = mContext.getPackageManager();
17217
17218        final boolean currentAsec;
17219        final String currentVolumeUuid;
17220        final File codeFile;
17221        final String installerPackageName;
17222        final String packageAbiOverride;
17223        final int appId;
17224        final String seinfo;
17225        final String label;
17226        final int targetSdkVersion;
17227
17228        // reader
17229        synchronized (mPackages) {
17230            final PackageParser.Package pkg = mPackages.get(packageName);
17231            final PackageSetting ps = mSettings.mPackages.get(packageName);
17232            if (pkg == null || ps == null) {
17233                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17234            }
17235
17236            if (pkg.applicationInfo.isSystemApp()) {
17237                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17238                        "Cannot move system application");
17239            }
17240
17241            if (pkg.applicationInfo.isExternalAsec()) {
17242                currentAsec = true;
17243                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17244            } else if (pkg.applicationInfo.isForwardLocked()) {
17245                currentAsec = true;
17246                currentVolumeUuid = "forward_locked";
17247            } else {
17248                currentAsec = false;
17249                currentVolumeUuid = ps.volumeUuid;
17250
17251                final File probe = new File(pkg.codePath);
17252                final File probeOat = new File(probe, "oat");
17253                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17254                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17255                            "Move only supported for modern cluster style installs");
17256                }
17257            }
17258
17259            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17260                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17261                        "Package already moved to " + volumeUuid);
17262            }
17263
17264            if (ps.frozen) {
17265                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17266                        "Failed to move already frozen package");
17267            }
17268            ps.frozen = true;
17269
17270            codeFile = new File(pkg.codePath);
17271            installerPackageName = ps.installerPackageName;
17272            packageAbiOverride = ps.cpuAbiOverrideString;
17273            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17274            seinfo = pkg.applicationInfo.seinfo;
17275            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17276            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17277        }
17278
17279        // Now that we're guarded by frozen state, kill app during move
17280        final long token = Binder.clearCallingIdentity();
17281        try {
17282            killApplication(packageName, appId, "move pkg");
17283        } finally {
17284            Binder.restoreCallingIdentity(token);
17285        }
17286
17287        final Bundle extras = new Bundle();
17288        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17289        extras.putString(Intent.EXTRA_TITLE, label);
17290        mMoveCallbacks.notifyCreated(moveId, extras);
17291
17292        int installFlags;
17293        final boolean moveCompleteApp;
17294        final File measurePath;
17295
17296        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17297            installFlags = INSTALL_INTERNAL;
17298            moveCompleteApp = !currentAsec;
17299            measurePath = Environment.getDataAppDirectory(volumeUuid);
17300        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17301            installFlags = INSTALL_EXTERNAL;
17302            moveCompleteApp = false;
17303            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17304        } else {
17305            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17306            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17307                    || !volume.isMountedWritable()) {
17308                unfreezePackage(packageName);
17309                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17310                        "Move location not mounted private volume");
17311            }
17312
17313            Preconditions.checkState(!currentAsec);
17314
17315            installFlags = INSTALL_INTERNAL;
17316            moveCompleteApp = true;
17317            measurePath = Environment.getDataAppDirectory(volumeUuid);
17318        }
17319
17320        final PackageStats stats = new PackageStats(null, -1);
17321        synchronized (mInstaller) {
17322            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17323                unfreezePackage(packageName);
17324                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17325                        "Failed to measure package size");
17326            }
17327        }
17328
17329        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17330                + stats.dataSize);
17331
17332        final long startFreeBytes = measurePath.getFreeSpace();
17333        final long sizeBytes;
17334        if (moveCompleteApp) {
17335            sizeBytes = stats.codeSize + stats.dataSize;
17336        } else {
17337            sizeBytes = stats.codeSize;
17338        }
17339
17340        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17341            unfreezePackage(packageName);
17342            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17343                    "Not enough free space to move");
17344        }
17345
17346        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17347
17348        final CountDownLatch installedLatch = new CountDownLatch(1);
17349        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17350            @Override
17351            public void onUserActionRequired(Intent intent) throws RemoteException {
17352                throw new IllegalStateException();
17353            }
17354
17355            @Override
17356            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17357                    Bundle extras) throws RemoteException {
17358                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17359                        + PackageManager.installStatusToString(returnCode, msg));
17360
17361                installedLatch.countDown();
17362
17363                // Regardless of success or failure of the move operation,
17364                // always unfreeze the package
17365                unfreezePackage(packageName);
17366
17367                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17368                switch (status) {
17369                    case PackageInstaller.STATUS_SUCCESS:
17370                        mMoveCallbacks.notifyStatusChanged(moveId,
17371                                PackageManager.MOVE_SUCCEEDED);
17372                        break;
17373                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17374                        mMoveCallbacks.notifyStatusChanged(moveId,
17375                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17376                        break;
17377                    default:
17378                        mMoveCallbacks.notifyStatusChanged(moveId,
17379                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17380                        break;
17381                }
17382            }
17383        };
17384
17385        final MoveInfo move;
17386        if (moveCompleteApp) {
17387            // Kick off a thread to report progress estimates
17388            new Thread() {
17389                @Override
17390                public void run() {
17391                    while (true) {
17392                        try {
17393                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17394                                break;
17395                            }
17396                        } catch (InterruptedException ignored) {
17397                        }
17398
17399                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17400                        final int progress = 10 + (int) MathUtils.constrain(
17401                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17402                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17403                    }
17404                }
17405            }.start();
17406
17407            final String dataAppName = codeFile.getName();
17408            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17409                    dataAppName, appId, seinfo, targetSdkVersion);
17410        } else {
17411            move = null;
17412        }
17413
17414        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17415
17416        final Message msg = mHandler.obtainMessage(INIT_COPY);
17417        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17418        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17419                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17420        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17421        msg.obj = params;
17422
17423        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17424                System.identityHashCode(msg.obj));
17425        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17426                System.identityHashCode(msg.obj));
17427
17428        mHandler.sendMessage(msg);
17429    }
17430
17431    @Override
17432    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17433        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17434
17435        final int realMoveId = mNextMoveId.getAndIncrement();
17436        final Bundle extras = new Bundle();
17437        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17438        mMoveCallbacks.notifyCreated(realMoveId, extras);
17439
17440        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17441            @Override
17442            public void onCreated(int moveId, Bundle extras) {
17443                // Ignored
17444            }
17445
17446            @Override
17447            public void onStatusChanged(int moveId, int status, long estMillis) {
17448                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17449            }
17450        };
17451
17452        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17453        storage.setPrimaryStorageUuid(volumeUuid, callback);
17454        return realMoveId;
17455    }
17456
17457    @Override
17458    public int getMoveStatus(int moveId) {
17459        mContext.enforceCallingOrSelfPermission(
17460                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17461        return mMoveCallbacks.mLastStatus.get(moveId);
17462    }
17463
17464    @Override
17465    public void registerMoveCallback(IPackageMoveObserver callback) {
17466        mContext.enforceCallingOrSelfPermission(
17467                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17468        mMoveCallbacks.register(callback);
17469    }
17470
17471    @Override
17472    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17473        mContext.enforceCallingOrSelfPermission(
17474                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17475        mMoveCallbacks.unregister(callback);
17476    }
17477
17478    @Override
17479    public boolean setInstallLocation(int loc) {
17480        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17481                null);
17482        if (getInstallLocation() == loc) {
17483            return true;
17484        }
17485        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17486                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17487            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17488                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17489            return true;
17490        }
17491        return false;
17492   }
17493
17494    @Override
17495    public int getInstallLocation() {
17496        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17497                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17498                PackageHelper.APP_INSTALL_AUTO);
17499    }
17500
17501    /** Called by UserManagerService */
17502    void cleanUpUser(UserManagerService userManager, int userHandle) {
17503        synchronized (mPackages) {
17504            mDirtyUsers.remove(userHandle);
17505            mUserNeedsBadging.delete(userHandle);
17506            mSettings.removeUserLPw(userHandle);
17507            mPendingBroadcasts.remove(userHandle);
17508            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17509        }
17510        synchronized (mInstallLock) {
17511            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17512            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17513                final String volumeUuid = vol.getFsUuid();
17514                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17515                try {
17516                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17517                } catch (InstallerException e) {
17518                    Slog.w(TAG, "Failed to remove user data", e);
17519                }
17520            }
17521            synchronized (mPackages) {
17522                removeUnusedPackagesLILPw(userManager, userHandle);
17523            }
17524        }
17525    }
17526
17527    /**
17528     * We're removing userHandle and would like to remove any downloaded packages
17529     * that are no longer in use by any other user.
17530     * @param userHandle the user being removed
17531     */
17532    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17533        final boolean DEBUG_CLEAN_APKS = false;
17534        int [] users = userManager.getUserIds();
17535        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17536        while (psit.hasNext()) {
17537            PackageSetting ps = psit.next();
17538            if (ps.pkg == null) {
17539                continue;
17540            }
17541            final String packageName = ps.pkg.packageName;
17542            // Skip over if system app
17543            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17544                continue;
17545            }
17546            if (DEBUG_CLEAN_APKS) {
17547                Slog.i(TAG, "Checking package " + packageName);
17548            }
17549            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17550            if (keep) {
17551                if (DEBUG_CLEAN_APKS) {
17552                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17553                }
17554            } else {
17555                for (int i = 0; i < users.length; i++) {
17556                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17557                        keep = true;
17558                        if (DEBUG_CLEAN_APKS) {
17559                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17560                                    + users[i]);
17561                        }
17562                        break;
17563                    }
17564                }
17565            }
17566            if (!keep) {
17567                if (DEBUG_CLEAN_APKS) {
17568                    Slog.i(TAG, "  Removing package " + packageName);
17569                }
17570                mHandler.post(new Runnable() {
17571                    public void run() {
17572                        deletePackageX(packageName, userHandle, 0);
17573                    } //end run
17574                });
17575            }
17576        }
17577    }
17578
17579    /** Called by UserManagerService */
17580    void createNewUser(int userHandle) {
17581        synchronized (mInstallLock) {
17582            try {
17583                mInstaller.createUserConfig(userHandle);
17584            } catch (InstallerException e) {
17585                Slog.w(TAG, "Failed to create user config", e);
17586            }
17587            mSettings.createNewUserLI(this, mInstaller, userHandle);
17588        }
17589        synchronized (mPackages) {
17590            applyFactoryDefaultBrowserLPw(userHandle);
17591            primeDomainVerificationsLPw(userHandle);
17592        }
17593    }
17594
17595    void newUserCreated(final int userHandle) {
17596        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17597        // If permission review for legacy apps is required, we represent
17598        // dagerous permissions for such apps as always granted runtime
17599        // permissions to keep per user flag state whether review is needed.
17600        // Hence, if a new user is added we have to propagate dangerous
17601        // permission grants for these legacy apps.
17602        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17603            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17604                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17605        }
17606    }
17607
17608    @Override
17609    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17610        mContext.enforceCallingOrSelfPermission(
17611                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17612                "Only package verification agents can read the verifier device identity");
17613
17614        synchronized (mPackages) {
17615            return mSettings.getVerifierDeviceIdentityLPw();
17616        }
17617    }
17618
17619    @Override
17620    public void setPermissionEnforced(String permission, boolean enforced) {
17621        // TODO: Now that we no longer change GID for storage, this should to away.
17622        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17623                "setPermissionEnforced");
17624        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17625            synchronized (mPackages) {
17626                if (mSettings.mReadExternalStorageEnforced == null
17627                        || mSettings.mReadExternalStorageEnforced != enforced) {
17628                    mSettings.mReadExternalStorageEnforced = enforced;
17629                    mSettings.writeLPr();
17630                }
17631            }
17632            // kill any non-foreground processes so we restart them and
17633            // grant/revoke the GID.
17634            final IActivityManager am = ActivityManagerNative.getDefault();
17635            if (am != null) {
17636                final long token = Binder.clearCallingIdentity();
17637                try {
17638                    am.killProcessesBelowForeground("setPermissionEnforcement");
17639                } catch (RemoteException e) {
17640                } finally {
17641                    Binder.restoreCallingIdentity(token);
17642                }
17643            }
17644        } else {
17645            throw new IllegalArgumentException("No selective enforcement for " + permission);
17646        }
17647    }
17648
17649    @Override
17650    @Deprecated
17651    public boolean isPermissionEnforced(String permission) {
17652        return true;
17653    }
17654
17655    @Override
17656    public boolean isStorageLow() {
17657        final long token = Binder.clearCallingIdentity();
17658        try {
17659            final DeviceStorageMonitorInternal
17660                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17661            if (dsm != null) {
17662                return dsm.isMemoryLow();
17663            } else {
17664                return false;
17665            }
17666        } finally {
17667            Binder.restoreCallingIdentity(token);
17668        }
17669    }
17670
17671    @Override
17672    public IPackageInstaller getPackageInstaller() {
17673        return mInstallerService;
17674    }
17675
17676    private boolean userNeedsBadging(int userId) {
17677        int index = mUserNeedsBadging.indexOfKey(userId);
17678        if (index < 0) {
17679            final UserInfo userInfo;
17680            final long token = Binder.clearCallingIdentity();
17681            try {
17682                userInfo = sUserManager.getUserInfo(userId);
17683            } finally {
17684                Binder.restoreCallingIdentity(token);
17685            }
17686            final boolean b;
17687            if (userInfo != null && userInfo.isManagedProfile()) {
17688                b = true;
17689            } else {
17690                b = false;
17691            }
17692            mUserNeedsBadging.put(userId, b);
17693            return b;
17694        }
17695        return mUserNeedsBadging.valueAt(index);
17696    }
17697
17698    @Override
17699    public KeySet getKeySetByAlias(String packageName, String alias) {
17700        if (packageName == null || alias == null) {
17701            return null;
17702        }
17703        synchronized(mPackages) {
17704            final PackageParser.Package pkg = mPackages.get(packageName);
17705            if (pkg == null) {
17706                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17707                throw new IllegalArgumentException("Unknown package: " + packageName);
17708            }
17709            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17710            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17711        }
17712    }
17713
17714    @Override
17715    public KeySet getSigningKeySet(String packageName) {
17716        if (packageName == null) {
17717            return null;
17718        }
17719        synchronized(mPackages) {
17720            final PackageParser.Package pkg = mPackages.get(packageName);
17721            if (pkg == null) {
17722                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17723                throw new IllegalArgumentException("Unknown package: " + packageName);
17724            }
17725            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17726                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17727                throw new SecurityException("May not access signing KeySet of other apps.");
17728            }
17729            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17730            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17731        }
17732    }
17733
17734    @Override
17735    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17736        if (packageName == null || ks == null) {
17737            return false;
17738        }
17739        synchronized(mPackages) {
17740            final PackageParser.Package pkg = mPackages.get(packageName);
17741            if (pkg == null) {
17742                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17743                throw new IllegalArgumentException("Unknown package: " + packageName);
17744            }
17745            IBinder ksh = ks.getToken();
17746            if (ksh instanceof KeySetHandle) {
17747                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17748                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17749            }
17750            return false;
17751        }
17752    }
17753
17754    @Override
17755    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17756        if (packageName == null || ks == null) {
17757            return false;
17758        }
17759        synchronized(mPackages) {
17760            final PackageParser.Package pkg = mPackages.get(packageName);
17761            if (pkg == null) {
17762                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17763                throw new IllegalArgumentException("Unknown package: " + packageName);
17764            }
17765            IBinder ksh = ks.getToken();
17766            if (ksh instanceof KeySetHandle) {
17767                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17768                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17769            }
17770            return false;
17771        }
17772    }
17773
17774    private void deletePackageIfUnusedLPr(final String packageName) {
17775        PackageSetting ps = mSettings.mPackages.get(packageName);
17776        if (ps == null) {
17777            return;
17778        }
17779        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17780            // TODO Implement atomic delete if package is unused
17781            // It is currently possible that the package will be deleted even if it is installed
17782            // after this method returns.
17783            mHandler.post(new Runnable() {
17784                public void run() {
17785                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17786                }
17787            });
17788        }
17789    }
17790
17791    /**
17792     * Check and throw if the given before/after packages would be considered a
17793     * downgrade.
17794     */
17795    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17796            throws PackageManagerException {
17797        if (after.versionCode < before.mVersionCode) {
17798            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17799                    "Update version code " + after.versionCode + " is older than current "
17800                    + before.mVersionCode);
17801        } else if (after.versionCode == before.mVersionCode) {
17802            if (after.baseRevisionCode < before.baseRevisionCode) {
17803                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17804                        "Update base revision code " + after.baseRevisionCode
17805                        + " is older than current " + before.baseRevisionCode);
17806            }
17807
17808            if (!ArrayUtils.isEmpty(after.splitNames)) {
17809                for (int i = 0; i < after.splitNames.length; i++) {
17810                    final String splitName = after.splitNames[i];
17811                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17812                    if (j != -1) {
17813                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17814                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17815                                    "Update split " + splitName + " revision code "
17816                                    + after.splitRevisionCodes[i] + " is older than current "
17817                                    + before.splitRevisionCodes[j]);
17818                        }
17819                    }
17820                }
17821            }
17822        }
17823    }
17824
17825    private static class MoveCallbacks extends Handler {
17826        private static final int MSG_CREATED = 1;
17827        private static final int MSG_STATUS_CHANGED = 2;
17828
17829        private final RemoteCallbackList<IPackageMoveObserver>
17830                mCallbacks = new RemoteCallbackList<>();
17831
17832        private final SparseIntArray mLastStatus = new SparseIntArray();
17833
17834        public MoveCallbacks(Looper looper) {
17835            super(looper);
17836        }
17837
17838        public void register(IPackageMoveObserver callback) {
17839            mCallbacks.register(callback);
17840        }
17841
17842        public void unregister(IPackageMoveObserver callback) {
17843            mCallbacks.unregister(callback);
17844        }
17845
17846        @Override
17847        public void handleMessage(Message msg) {
17848            final SomeArgs args = (SomeArgs) msg.obj;
17849            final int n = mCallbacks.beginBroadcast();
17850            for (int i = 0; i < n; i++) {
17851                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17852                try {
17853                    invokeCallback(callback, msg.what, args);
17854                } catch (RemoteException ignored) {
17855                }
17856            }
17857            mCallbacks.finishBroadcast();
17858            args.recycle();
17859        }
17860
17861        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17862                throws RemoteException {
17863            switch (what) {
17864                case MSG_CREATED: {
17865                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17866                    break;
17867                }
17868                case MSG_STATUS_CHANGED: {
17869                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17870                    break;
17871                }
17872            }
17873        }
17874
17875        private void notifyCreated(int moveId, Bundle extras) {
17876            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17877
17878            final SomeArgs args = SomeArgs.obtain();
17879            args.argi1 = moveId;
17880            args.arg2 = extras;
17881            obtainMessage(MSG_CREATED, args).sendToTarget();
17882        }
17883
17884        private void notifyStatusChanged(int moveId, int status) {
17885            notifyStatusChanged(moveId, status, -1);
17886        }
17887
17888        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17889            Slog.v(TAG, "Move " + moveId + " status " + status);
17890
17891            final SomeArgs args = SomeArgs.obtain();
17892            args.argi1 = moveId;
17893            args.argi2 = status;
17894            args.arg3 = estMillis;
17895            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17896
17897            synchronized (mLastStatus) {
17898                mLastStatus.put(moveId, status);
17899            }
17900        }
17901    }
17902
17903    private final static class OnPermissionChangeListeners extends Handler {
17904        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17905
17906        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17907                new RemoteCallbackList<>();
17908
17909        public OnPermissionChangeListeners(Looper looper) {
17910            super(looper);
17911        }
17912
17913        @Override
17914        public void handleMessage(Message msg) {
17915            switch (msg.what) {
17916                case MSG_ON_PERMISSIONS_CHANGED: {
17917                    final int uid = msg.arg1;
17918                    handleOnPermissionsChanged(uid);
17919                } break;
17920            }
17921        }
17922
17923        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17924            mPermissionListeners.register(listener);
17925
17926        }
17927
17928        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17929            mPermissionListeners.unregister(listener);
17930        }
17931
17932        public void onPermissionsChanged(int uid) {
17933            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17934                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17935            }
17936        }
17937
17938        private void handleOnPermissionsChanged(int uid) {
17939            final int count = mPermissionListeners.beginBroadcast();
17940            try {
17941                for (int i = 0; i < count; i++) {
17942                    IOnPermissionsChangeListener callback = mPermissionListeners
17943                            .getBroadcastItem(i);
17944                    try {
17945                        callback.onPermissionsChanged(uid);
17946                    } catch (RemoteException e) {
17947                        Log.e(TAG, "Permission listener is dead", e);
17948                    }
17949                }
17950            } finally {
17951                mPermissionListeners.finishBroadcast();
17952            }
17953        }
17954    }
17955
17956    private class PackageManagerInternalImpl extends PackageManagerInternal {
17957        @Override
17958        public void setLocationPackagesProvider(PackagesProvider provider) {
17959            synchronized (mPackages) {
17960                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17961            }
17962        }
17963
17964        @Override
17965        public void setImePackagesProvider(PackagesProvider provider) {
17966            synchronized (mPackages) {
17967                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17968            }
17969        }
17970
17971        @Override
17972        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17973            synchronized (mPackages) {
17974                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17975            }
17976        }
17977
17978        @Override
17979        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17980            synchronized (mPackages) {
17981                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17982            }
17983        }
17984
17985        @Override
17986        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17987            synchronized (mPackages) {
17988                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17989            }
17990        }
17991
17992        @Override
17993        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17994            synchronized (mPackages) {
17995                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17996            }
17997        }
17998
17999        @Override
18000        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18001            synchronized (mPackages) {
18002                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18003            }
18004        }
18005
18006        @Override
18007        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18008            synchronized (mPackages) {
18009                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18010                        packageName, userId);
18011            }
18012        }
18013
18014        @Override
18015        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18016            synchronized (mPackages) {
18017                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18018                        packageName, userId);
18019            }
18020        }
18021
18022        @Override
18023        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18024            synchronized (mPackages) {
18025                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18026                        packageName, userId);
18027            }
18028        }
18029
18030        @Override
18031        public void setKeepUninstalledPackages(final List<String> packageList) {
18032            Preconditions.checkNotNull(packageList);
18033            List<String> removedFromList = null;
18034            synchronized (mPackages) {
18035                if (mKeepUninstalledPackages != null) {
18036                    final int packagesCount = mKeepUninstalledPackages.size();
18037                    for (int i = 0; i < packagesCount; i++) {
18038                        String oldPackage = mKeepUninstalledPackages.get(i);
18039                        if (packageList != null && packageList.contains(oldPackage)) {
18040                            continue;
18041                        }
18042                        if (removedFromList == null) {
18043                            removedFromList = new ArrayList<>();
18044                        }
18045                        removedFromList.add(oldPackage);
18046                    }
18047                }
18048                mKeepUninstalledPackages = new ArrayList<>(packageList);
18049                if (removedFromList != null) {
18050                    final int removedCount = removedFromList.size();
18051                    for (int i = 0; i < removedCount; i++) {
18052                        deletePackageIfUnusedLPr(removedFromList.get(i));
18053                    }
18054                }
18055            }
18056        }
18057
18058        @Override
18059        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18060            synchronized (mPackages) {
18061                // If we do not support permission review, done.
18062                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18063                    return false;
18064                }
18065
18066                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18067                if (packageSetting == null) {
18068                    return false;
18069                }
18070
18071                // Permission review applies only to apps not supporting the new permission model.
18072                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18073                    return false;
18074                }
18075
18076                // Legacy apps have the permission and get user consent on launch.
18077                PermissionsState permissionsState = packageSetting.getPermissionsState();
18078                return permissionsState.isPermissionReviewRequired(userId);
18079            }
18080        }
18081    }
18082
18083    @Override
18084    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18085        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18086        synchronized (mPackages) {
18087            final long identity = Binder.clearCallingIdentity();
18088            try {
18089                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18090                        packageNames, userId);
18091            } finally {
18092                Binder.restoreCallingIdentity(identity);
18093            }
18094        }
18095    }
18096
18097    private static void enforceSystemOrPhoneCaller(String tag) {
18098        int callingUid = Binder.getCallingUid();
18099        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18100            throw new SecurityException(
18101                    "Cannot call " + tag + " from UID " + callingUid);
18102        }
18103    }
18104
18105    boolean isHistoricalPackageUsageAvailable() {
18106        return mPackageUsage.isHistoricalPackageUsageAvailable();
18107    }
18108}
18109