PackageManagerService.java revision fe54b11803e7940d23b6c540b2e6db738299702c
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.Installer.StorageFlags;
239import com.android.server.pm.PermissionsState.PermissionState;
240import com.android.server.pm.Settings.DatabaseVersion;
241import com.android.server.pm.Settings.VersionInfo;
242import com.android.server.storage.DeviceStorageMonitorInternal;
243
244import dalvik.system.DexFile;
245import dalvik.system.VMRuntime;
246
247import libcore.io.IoUtils;
248import libcore.util.EmptyArray;
249
250import org.xmlpull.v1.XmlPullParser;
251import org.xmlpull.v1.XmlPullParserException;
252import org.xmlpull.v1.XmlSerializer;
253
254import java.io.BufferedInputStream;
255import java.io.BufferedOutputStream;
256import java.io.BufferedReader;
257import java.io.ByteArrayInputStream;
258import java.io.ByteArrayOutputStream;
259import java.io.File;
260import java.io.FileDescriptor;
261import java.io.FileNotFoundException;
262import java.io.FileOutputStream;
263import java.io.FileReader;
264import java.io.FilenameFilter;
265import java.io.IOException;
266import java.io.InputStream;
267import java.io.PrintStream;
268import java.io.PrintWriter;
269import java.nio.charset.StandardCharsets;
270import java.security.MessageDigest;
271import java.security.NoSuchAlgorithmException;
272import java.security.PublicKey;
273import java.security.cert.CertificateEncodingException;
274import java.security.cert.CertificateException;
275import java.text.SimpleDateFormat;
276import java.util.ArrayList;
277import java.util.Arrays;
278import java.util.Collection;
279import java.util.Collections;
280import java.util.Comparator;
281import java.util.Date;
282import java.util.HashSet;
283import java.util.Iterator;
284import java.util.List;
285import java.util.Map;
286import java.util.Objects;
287import java.util.Set;
288import java.util.concurrent.CountDownLatch;
289import java.util.concurrent.TimeUnit;
290import java.util.concurrent.atomic.AtomicBoolean;
291import java.util.concurrent.atomic.AtomicInteger;
292import java.util.concurrent.atomic.AtomicLong;
293
294/**
295 * Keep track of all those .apks everywhere.
296 *
297 * This is very central to the platform's security; please run the unit
298 * tests whenever making modifications here:
299 *
300runtest -c android.content.pm.PackageManagerTests frameworks-core
301 *
302 * {@hide}
303 */
304public class PackageManagerService extends IPackageManager.Stub {
305    static final String TAG = "PackageManager";
306    static final boolean DEBUG_SETTINGS = false;
307    static final boolean DEBUG_PREFERRED = false;
308    static final boolean DEBUG_UPGRADE = false;
309    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
310    private static final boolean DEBUG_BACKUP = false;
311    private static final boolean DEBUG_INSTALL = false;
312    private static final boolean DEBUG_REMOVE = false;
313    private static final boolean DEBUG_BROADCASTS = false;
314    private static final boolean DEBUG_SHOW_INFO = false;
315    private static final boolean DEBUG_PACKAGE_INFO = false;
316    private static final boolean DEBUG_INTENT_MATCHING = false;
317    private static final boolean DEBUG_PACKAGE_SCANNING = false;
318    private static final boolean DEBUG_VERIFY = false;
319
320    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
321    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
322    // user, but by default initialize to this.
323    static final boolean DEBUG_DEXOPT = false;
324
325    private static final boolean DEBUG_ABI_SELECTION = false;
326    private static final boolean DEBUG_EPHEMERAL = false;
327    private static final boolean DEBUG_TRIAGED_MISSING = false;
328    private static final boolean DEBUG_APP_DATA = false;
329
330    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
331
332    private static final boolean DISABLE_EPHEMERAL_APPS = true;
333
334    private static final int RADIO_UID = Process.PHONE_UID;
335    private static final int LOG_UID = Process.LOG_UID;
336    private static final int NFC_UID = Process.NFC_UID;
337    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
338    private static final int SHELL_UID = Process.SHELL_UID;
339
340    // Cap the size of permission trees that 3rd party apps can define
341    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
342
343    // Suffix used during package installation when copying/moving
344    // package apks to install directory.
345    private static final String INSTALL_PACKAGE_SUFFIX = "-";
346
347    static final int SCAN_NO_DEX = 1<<1;
348    static final int SCAN_FORCE_DEX = 1<<2;
349    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
350    static final int SCAN_NEW_INSTALL = 1<<4;
351    static final int SCAN_NO_PATHS = 1<<5;
352    static final int SCAN_UPDATE_TIME = 1<<6;
353    static final int SCAN_DEFER_DEX = 1<<7;
354    static final int SCAN_BOOTING = 1<<8;
355    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
356    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
357    static final int SCAN_REPLACING = 1<<11;
358    static final int SCAN_REQUIRE_KNOWN = 1<<12;
359    static final int SCAN_MOVE = 1<<13;
360    static final int SCAN_INITIAL = 1<<14;
361
362    static final int REMOVE_CHATTY = 1<<16;
363
364    private static final int[] EMPTY_INT_ARRAY = new int[0];
365
366    /**
367     * Timeout (in milliseconds) after which the watchdog should declare that
368     * our handler thread is wedged.  The usual default for such things is one
369     * minute but we sometimes do very lengthy I/O operations on this thread,
370     * such as installing multi-gigabyte applications, so ours needs to be longer.
371     */
372    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
373
374    /**
375     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
376     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
377     * settings entry if available, otherwise we use the hardcoded default.  If it's been
378     * more than this long since the last fstrim, we force one during the boot sequence.
379     *
380     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
381     * one gets run at the next available charging+idle time.  This final mandatory
382     * no-fstrim check kicks in only of the other scheduling criteria is never met.
383     */
384    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
385
386    /**
387     * Whether verification is enabled by default.
388     */
389    private static final boolean DEFAULT_VERIFY_ENABLE = true;
390
391    /**
392     * The default maximum time to wait for the verification agent to return in
393     * milliseconds.
394     */
395    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
396
397    /**
398     * The default response for package verification timeout.
399     *
400     * This can be either PackageManager.VERIFICATION_ALLOW or
401     * PackageManager.VERIFICATION_REJECT.
402     */
403    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
404
405    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
406
407    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
408            DEFAULT_CONTAINER_PACKAGE,
409            "com.android.defcontainer.DefaultContainerService");
410
411    private static final String KILL_APP_REASON_GIDS_CHANGED =
412            "permission grant or revoke changed gids";
413
414    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
415            "permissions revoked";
416
417    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
418
419    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
420
421    /** Permission grant: not grant the permission. */
422    private static final int GRANT_DENIED = 1;
423
424    /** Permission grant: grant the permission as an install permission. */
425    private static final int GRANT_INSTALL = 2;
426
427    /** Permission grant: grant the permission as a runtime one. */
428    private static final int GRANT_RUNTIME = 3;
429
430    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
431    private static final int GRANT_UPGRADE = 4;
432
433    /** Canonical intent used to identify what counts as a "web browser" app */
434    private static final Intent sBrowserIntent;
435    static {
436        sBrowserIntent = new Intent();
437        sBrowserIntent.setAction(Intent.ACTION_VIEW);
438        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
439        sBrowserIntent.setData(Uri.parse("http:"));
440    }
441
442    final ServiceThread mHandlerThread;
443
444    final PackageHandler mHandler;
445
446    /**
447     * Messages for {@link #mHandler} that need to wait for system ready before
448     * being dispatched.
449     */
450    private ArrayList<Message> mPostSystemReadyMessages;
451
452    final int mSdkVersion = Build.VERSION.SDK_INT;
453
454    final Context mContext;
455    final boolean mFactoryTest;
456    final boolean mOnlyCore;
457    final DisplayMetrics mMetrics;
458    final int mDefParseFlags;
459    final String[] mSeparateProcesses;
460    final boolean mIsUpgrade;
461
462    /** The location for ASEC container files on internal storage. */
463    final String mAsecInternalPath;
464
465    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
466    // LOCK HELD.  Can be called with mInstallLock held.
467    @GuardedBy("mInstallLock")
468    final Installer mInstaller;
469
470    /** Directory where installed third-party apps stored */
471    final File mAppInstallDir;
472    final File mEphemeralInstallDir;
473
474    /**
475     * Directory to which applications installed internally have their
476     * 32 bit native libraries copied.
477     */
478    private File mAppLib32InstallDir;
479
480    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
481    // apps.
482    final File mDrmAppPrivateInstallDir;
483
484    // ----------------------------------------------------------------
485
486    // Lock for state used when installing and doing other long running
487    // operations.  Methods that must be called with this lock held have
488    // the suffix "LI".
489    final Object mInstallLock = new Object();
490
491    // ----------------------------------------------------------------
492
493    // Keys are String (package name), values are Package.  This also serves
494    // as the lock for the global state.  Methods that must be called with
495    // this lock held have the prefix "LP".
496    @GuardedBy("mPackages")
497    final ArrayMap<String, PackageParser.Package> mPackages =
498            new ArrayMap<String, PackageParser.Package>();
499
500    // Tracks available target package names -> overlay package paths.
501    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
502        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
503
504    /**
505     * Tracks new system packages [received in an OTA] that we expect to
506     * find updated user-installed versions. Keys are package name, values
507     * are package location.
508     */
509    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
510
511    /**
512     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
513     */
514    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
515    /**
516     * Whether or not system app permissions should be promoted from install to runtime.
517     */
518    boolean mPromoteSystemApps;
519
520    final Settings mSettings;
521    boolean mRestoredSettings;
522
523    // System configuration read by SystemConfig.
524    final int[] mGlobalGids;
525    final SparseArray<ArraySet<String>> mSystemPermissions;
526    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
527
528    // If mac_permissions.xml was found for seinfo labeling.
529    boolean mFoundPolicyFile;
530
531    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
532
533    public static final class SharedLibraryEntry {
534        public final String path;
535        public final String apk;
536
537        SharedLibraryEntry(String _path, String _apk) {
538            path = _path;
539            apk = _apk;
540        }
541    }
542
543    // Currently known shared libraries.
544    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
545            new ArrayMap<String, SharedLibraryEntry>();
546
547    // All available activities, for your resolving pleasure.
548    final ActivityIntentResolver mActivities =
549            new ActivityIntentResolver();
550
551    // All available receivers, for your resolving pleasure.
552    final ActivityIntentResolver mReceivers =
553            new ActivityIntentResolver();
554
555    // All available services, for your resolving pleasure.
556    final ServiceIntentResolver mServices = new ServiceIntentResolver();
557
558    // All available providers, for your resolving pleasure.
559    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
560
561    // Mapping from provider base names (first directory in content URI codePath)
562    // to the provider information.
563    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
564            new ArrayMap<String, PackageParser.Provider>();
565
566    // Mapping from instrumentation class names to info about them.
567    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
568            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
569
570    // Mapping from permission names to info about them.
571    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
572            new ArrayMap<String, PackageParser.PermissionGroup>();
573
574    // Packages whose data we have transfered into another package, thus
575    // should no longer exist.
576    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
577
578    // Broadcast actions that are only available to the system.
579    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
580
581    /** List of packages waiting for verification. */
582    final SparseArray<PackageVerificationState> mPendingVerification
583            = new SparseArray<PackageVerificationState>();
584
585    /** Set of packages associated with each app op permission. */
586    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
587
588    final PackageInstallerService mInstallerService;
589
590    private final PackageDexOptimizer mPackageDexOptimizer;
591
592    private AtomicInteger mNextMoveId = new AtomicInteger();
593    private final MoveCallbacks mMoveCallbacks;
594
595    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
596
597    // Cache of users who need badging.
598    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
599
600    /** Token for keys in mPendingVerification. */
601    private int mPendingVerificationToken = 0;
602
603    volatile boolean mSystemReady;
604    volatile boolean mSafeMode;
605    volatile boolean mHasSystemUidErrors;
606
607    ApplicationInfo mAndroidApplication;
608    final ActivityInfo mResolveActivity = new ActivityInfo();
609    final ResolveInfo mResolveInfo = new ResolveInfo();
610    ComponentName mResolveComponentName;
611    PackageParser.Package mPlatformPackage;
612    ComponentName mCustomResolverComponentName;
613
614    boolean mResolverReplaced = false;
615
616    private final @Nullable ComponentName mIntentFilterVerifierComponent;
617    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
618
619    private int mIntentFilterVerificationToken = 0;
620
621    /** Component that knows whether or not an ephemeral application exists */
622    final ComponentName mEphemeralResolverComponent;
623    /** The service connection to the ephemeral resolver */
624    final EphemeralResolverConnection mEphemeralResolverConnection;
625
626    /** Component used to install ephemeral applications */
627    final ComponentName mEphemeralInstallerComponent;
628    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
629    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
630
631    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
632            = new SparseArray<IntentFilterVerificationState>();
633
634    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
635            new DefaultPermissionGrantPolicy(this);
636
637    // List of packages names to keep cached, even if they are uninstalled for all users
638    private List<String> mKeepUninstalledPackages;
639
640    private boolean mUseJitProfiles =
641            SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false);
642
643    private static class IFVerificationParams {
644        PackageParser.Package pkg;
645        boolean replacing;
646        int userId;
647        int verifierUid;
648
649        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
650                int _userId, int _verifierUid) {
651            pkg = _pkg;
652            replacing = _replacing;
653            userId = _userId;
654            replacing = _replacing;
655            verifierUid = _verifierUid;
656        }
657    }
658
659    private interface IntentFilterVerifier<T extends IntentFilter> {
660        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
661                                               T filter, String packageName);
662        void startVerifications(int userId);
663        void receiveVerificationResponse(int verificationId);
664    }
665
666    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
667        private Context mContext;
668        private ComponentName mIntentFilterVerifierComponent;
669        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
670
671        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
672            mContext = context;
673            mIntentFilterVerifierComponent = verifierComponent;
674        }
675
676        private String getDefaultScheme() {
677            return IntentFilter.SCHEME_HTTPS;
678        }
679
680        @Override
681        public void startVerifications(int userId) {
682            // Launch verifications requests
683            int count = mCurrentIntentFilterVerifications.size();
684            for (int n=0; n<count; n++) {
685                int verificationId = mCurrentIntentFilterVerifications.get(n);
686                final IntentFilterVerificationState ivs =
687                        mIntentFilterVerificationStates.get(verificationId);
688
689                String packageName = ivs.getPackageName();
690
691                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
692                final int filterCount = filters.size();
693                ArraySet<String> domainsSet = new ArraySet<>();
694                for (int m=0; m<filterCount; m++) {
695                    PackageParser.ActivityIntentInfo filter = filters.get(m);
696                    domainsSet.addAll(filter.getHostsList());
697                }
698                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
699                synchronized (mPackages) {
700                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
701                            packageName, domainsList) != null) {
702                        scheduleWriteSettingsLocked();
703                    }
704                }
705                sendVerificationRequest(userId, verificationId, ivs);
706            }
707            mCurrentIntentFilterVerifications.clear();
708        }
709
710        private void sendVerificationRequest(int userId, int verificationId,
711                IntentFilterVerificationState ivs) {
712
713            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
714            verificationIntent.putExtra(
715                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
716                    verificationId);
717            verificationIntent.putExtra(
718                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
719                    getDefaultScheme());
720            verificationIntent.putExtra(
721                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
722                    ivs.getHostsString());
723            verificationIntent.putExtra(
724                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
725                    ivs.getPackageName());
726            verificationIntent.setComponent(mIntentFilterVerifierComponent);
727            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
728
729            UserHandle user = new UserHandle(userId);
730            mContext.sendBroadcastAsUser(verificationIntent, user);
731            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
732                    "Sending IntentFilter verification broadcast");
733        }
734
735        public void receiveVerificationResponse(int verificationId) {
736            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
737
738            final boolean verified = ivs.isVerified();
739
740            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
741            final int count = filters.size();
742            if (DEBUG_DOMAIN_VERIFICATION) {
743                Slog.i(TAG, "Received verification response " + verificationId
744                        + " for " + count + " filters, verified=" + verified);
745            }
746            for (int n=0; n<count; n++) {
747                PackageParser.ActivityIntentInfo filter = filters.get(n);
748                filter.setVerified(verified);
749
750                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
751                        + " verified with result:" + verified + " and hosts:"
752                        + ivs.getHostsString());
753            }
754
755            mIntentFilterVerificationStates.remove(verificationId);
756
757            final String packageName = ivs.getPackageName();
758            IntentFilterVerificationInfo ivi = null;
759
760            synchronized (mPackages) {
761                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
762            }
763            if (ivi == null) {
764                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
765                        + verificationId + " packageName:" + packageName);
766                return;
767            }
768            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
769                    "Updating IntentFilterVerificationInfo for package " + packageName
770                            +" verificationId:" + verificationId);
771
772            synchronized (mPackages) {
773                if (verified) {
774                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
775                } else {
776                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
777                }
778                scheduleWriteSettingsLocked();
779
780                final int userId = ivs.getUserId();
781                if (userId != UserHandle.USER_ALL) {
782                    final int userStatus =
783                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
784
785                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
786                    boolean needUpdate = false;
787
788                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
789                    // already been set by the User thru the Disambiguation dialog
790                    switch (userStatus) {
791                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
792                            if (verified) {
793                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
794                            } else {
795                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
796                            }
797                            needUpdate = true;
798                            break;
799
800                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
801                            if (verified) {
802                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
803                                needUpdate = true;
804                            }
805                            break;
806
807                        default:
808                            // Nothing to do
809                    }
810
811                    if (needUpdate) {
812                        mSettings.updateIntentFilterVerificationStatusLPw(
813                                packageName, updatedStatus, userId);
814                        scheduleWritePackageRestrictionsLocked(userId);
815                    }
816                }
817            }
818        }
819
820        @Override
821        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
822                    ActivityIntentInfo filter, String packageName) {
823            if (!hasValidDomains(filter)) {
824                return false;
825            }
826            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
827            if (ivs == null) {
828                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
829                        packageName);
830            }
831            if (DEBUG_DOMAIN_VERIFICATION) {
832                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
833            }
834            ivs.addFilter(filter);
835            return true;
836        }
837
838        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
839                int userId, int verificationId, String packageName) {
840            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
841                    verifierUid, userId, packageName);
842            ivs.setPendingState();
843            synchronized (mPackages) {
844                mIntentFilterVerificationStates.append(verificationId, ivs);
845                mCurrentIntentFilterVerifications.add(verificationId);
846            }
847            return ivs;
848        }
849    }
850
851    private static boolean hasValidDomains(ActivityIntentInfo filter) {
852        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
853                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
854                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
855    }
856
857    // Set of pending broadcasts for aggregating enable/disable of components.
858    static class PendingPackageBroadcasts {
859        // for each user id, a map of <package name -> components within that package>
860        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
861
862        public PendingPackageBroadcasts() {
863            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
864        }
865
866        public ArrayList<String> get(int userId, String packageName) {
867            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
868            return packages.get(packageName);
869        }
870
871        public void put(int userId, String packageName, ArrayList<String> components) {
872            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
873            packages.put(packageName, components);
874        }
875
876        public void remove(int userId, String packageName) {
877            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
878            if (packages != null) {
879                packages.remove(packageName);
880            }
881        }
882
883        public void remove(int userId) {
884            mUidMap.remove(userId);
885        }
886
887        public int userIdCount() {
888            return mUidMap.size();
889        }
890
891        public int userIdAt(int n) {
892            return mUidMap.keyAt(n);
893        }
894
895        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
896            return mUidMap.get(userId);
897        }
898
899        public int size() {
900            // total number of pending broadcast entries across all userIds
901            int num = 0;
902            for (int i = 0; i< mUidMap.size(); i++) {
903                num += mUidMap.valueAt(i).size();
904            }
905            return num;
906        }
907
908        public void clear() {
909            mUidMap.clear();
910        }
911
912        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
913            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
914            if (map == null) {
915                map = new ArrayMap<String, ArrayList<String>>();
916                mUidMap.put(userId, map);
917            }
918            return map;
919        }
920    }
921    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
922
923    // Service Connection to remote media container service to copy
924    // package uri's from external media onto secure containers
925    // or internal storage.
926    private IMediaContainerService mContainerService = null;
927
928    static final int SEND_PENDING_BROADCAST = 1;
929    static final int MCS_BOUND = 3;
930    static final int END_COPY = 4;
931    static final int INIT_COPY = 5;
932    static final int MCS_UNBIND = 6;
933    static final int START_CLEANING_PACKAGE = 7;
934    static final int FIND_INSTALL_LOC = 8;
935    static final int POST_INSTALL = 9;
936    static final int MCS_RECONNECT = 10;
937    static final int MCS_GIVE_UP = 11;
938    static final int UPDATED_MEDIA_STATUS = 12;
939    static final int WRITE_SETTINGS = 13;
940    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
941    static final int PACKAGE_VERIFIED = 15;
942    static final int CHECK_PENDING_VERIFICATION = 16;
943    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
944    static final int INTENT_FILTER_VERIFIED = 18;
945
946    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
947
948    // Delay time in millisecs
949    static final int BROADCAST_DELAY = 10 * 1000;
950
951    static UserManagerService sUserManager;
952
953    // Stores a list of users whose package restrictions file needs to be updated
954    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
955
956    final private DefaultContainerConnection mDefContainerConn =
957            new DefaultContainerConnection();
958    class DefaultContainerConnection implements ServiceConnection {
959        public void onServiceConnected(ComponentName name, IBinder service) {
960            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
961            IMediaContainerService imcs =
962                IMediaContainerService.Stub.asInterface(service);
963            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
964        }
965
966        public void onServiceDisconnected(ComponentName name) {
967            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
968        }
969    }
970
971    // Recordkeeping of restore-after-install operations that are currently in flight
972    // between the Package Manager and the Backup Manager
973    static class PostInstallData {
974        public InstallArgs args;
975        public PackageInstalledInfo res;
976
977        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
978            args = _a;
979            res = _r;
980        }
981    }
982
983    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
984    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
985
986    // XML tags for backup/restore of various bits of state
987    private static final String TAG_PREFERRED_BACKUP = "pa";
988    private static final String TAG_DEFAULT_APPS = "da";
989    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
990
991    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
992    private static final String TAG_ALL_GRANTS = "rt-grants";
993    private static final String TAG_GRANT = "grant";
994    private static final String ATTR_PACKAGE_NAME = "pkg";
995
996    private static final String TAG_PERMISSION = "perm";
997    private static final String ATTR_PERMISSION_NAME = "name";
998    private static final String ATTR_IS_GRANTED = "g";
999    private static final String ATTR_USER_SET = "set";
1000    private static final String ATTR_USER_FIXED = "fixed";
1001    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1002
1003    // System/policy permission grants are not backed up
1004    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1005            FLAG_PERMISSION_POLICY_FIXED
1006            | FLAG_PERMISSION_SYSTEM_FIXED
1007            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1008
1009    // And we back up these user-adjusted states
1010    private static final int USER_RUNTIME_GRANT_MASK =
1011            FLAG_PERMISSION_USER_SET
1012            | FLAG_PERMISSION_USER_FIXED
1013            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1014
1015    final @Nullable String mRequiredVerifierPackage;
1016    final @Nullable String mRequiredInstallerPackage;
1017
1018    private final PackageUsage mPackageUsage = new PackageUsage();
1019
1020    private class PackageUsage {
1021        private static final int WRITE_INTERVAL
1022            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1023
1024        private final Object mFileLock = new Object();
1025        private final AtomicLong mLastWritten = new AtomicLong(0);
1026        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1027
1028        private boolean mIsHistoricalPackageUsageAvailable = true;
1029
1030        boolean isHistoricalPackageUsageAvailable() {
1031            return mIsHistoricalPackageUsageAvailable;
1032        }
1033
1034        void write(boolean force) {
1035            if (force) {
1036                writeInternal();
1037                return;
1038            }
1039            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1040                && !DEBUG_DEXOPT) {
1041                return;
1042            }
1043            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1044                new Thread("PackageUsage_DiskWriter") {
1045                    @Override
1046                    public void run() {
1047                        try {
1048                            writeInternal();
1049                        } finally {
1050                            mBackgroundWriteRunning.set(false);
1051                        }
1052                    }
1053                }.start();
1054            }
1055        }
1056
1057        private void writeInternal() {
1058            synchronized (mPackages) {
1059                synchronized (mFileLock) {
1060                    AtomicFile file = getFile();
1061                    FileOutputStream f = null;
1062                    try {
1063                        f = file.startWrite();
1064                        BufferedOutputStream out = new BufferedOutputStream(f);
1065                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1066                        StringBuilder sb = new StringBuilder();
1067                        for (PackageParser.Package pkg : mPackages.values()) {
1068                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1069                                continue;
1070                            }
1071                            sb.setLength(0);
1072                            sb.append(pkg.packageName);
1073                            sb.append(' ');
1074                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1075                            sb.append('\n');
1076                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1077                        }
1078                        out.flush();
1079                        file.finishWrite(f);
1080                    } catch (IOException e) {
1081                        if (f != null) {
1082                            file.failWrite(f);
1083                        }
1084                        Log.e(TAG, "Failed to write package usage times", e);
1085                    }
1086                }
1087            }
1088            mLastWritten.set(SystemClock.elapsedRealtime());
1089        }
1090
1091        void readLP() {
1092            synchronized (mFileLock) {
1093                AtomicFile file = getFile();
1094                BufferedInputStream in = null;
1095                try {
1096                    in = new BufferedInputStream(file.openRead());
1097                    StringBuffer sb = new StringBuffer();
1098                    while (true) {
1099                        String packageName = readToken(in, sb, ' ');
1100                        if (packageName == null) {
1101                            break;
1102                        }
1103                        String timeInMillisString = readToken(in, sb, '\n');
1104                        if (timeInMillisString == null) {
1105                            throw new IOException("Failed to find last usage time for package "
1106                                                  + packageName);
1107                        }
1108                        PackageParser.Package pkg = mPackages.get(packageName);
1109                        if (pkg == null) {
1110                            continue;
1111                        }
1112                        long timeInMillis;
1113                        try {
1114                            timeInMillis = Long.parseLong(timeInMillisString);
1115                        } catch (NumberFormatException e) {
1116                            throw new IOException("Failed to parse " + timeInMillisString
1117                                                  + " as a long.", e);
1118                        }
1119                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1120                    }
1121                } catch (FileNotFoundException expected) {
1122                    mIsHistoricalPackageUsageAvailable = false;
1123                } catch (IOException e) {
1124                    Log.w(TAG, "Failed to read package usage times", e);
1125                } finally {
1126                    IoUtils.closeQuietly(in);
1127                }
1128            }
1129            mLastWritten.set(SystemClock.elapsedRealtime());
1130        }
1131
1132        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1133                throws IOException {
1134            sb.setLength(0);
1135            while (true) {
1136                int ch = in.read();
1137                if (ch == -1) {
1138                    if (sb.length() == 0) {
1139                        return null;
1140                    }
1141                    throw new IOException("Unexpected EOF");
1142                }
1143                if (ch == endOfToken) {
1144                    return sb.toString();
1145                }
1146                sb.append((char)ch);
1147            }
1148        }
1149
1150        private AtomicFile getFile() {
1151            File dataDir = Environment.getDataDirectory();
1152            File systemDir = new File(dataDir, "system");
1153            File fname = new File(systemDir, "package-usage.list");
1154            return new AtomicFile(fname);
1155        }
1156    }
1157
1158    class PackageHandler extends Handler {
1159        private boolean mBound = false;
1160        final ArrayList<HandlerParams> mPendingInstalls =
1161            new ArrayList<HandlerParams>();
1162
1163        private boolean connectToService() {
1164            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1165                    " DefaultContainerService");
1166            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1167            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1168            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1169                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1170                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1171                mBound = true;
1172                return true;
1173            }
1174            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1175            return false;
1176        }
1177
1178        private void disconnectService() {
1179            mContainerService = null;
1180            mBound = false;
1181            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1182            mContext.unbindService(mDefContainerConn);
1183            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1184        }
1185
1186        PackageHandler(Looper looper) {
1187            super(looper);
1188        }
1189
1190        public void handleMessage(Message msg) {
1191            try {
1192                doHandleMessage(msg);
1193            } finally {
1194                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1195            }
1196        }
1197
1198        void doHandleMessage(Message msg) {
1199            switch (msg.what) {
1200                case INIT_COPY: {
1201                    HandlerParams params = (HandlerParams) msg.obj;
1202                    int idx = mPendingInstalls.size();
1203                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1204                    // If a bind was already initiated we dont really
1205                    // need to do anything. The pending install
1206                    // will be processed later on.
1207                    if (!mBound) {
1208                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1209                                System.identityHashCode(mHandler));
1210                        // If this is the only one pending we might
1211                        // have to bind to the service again.
1212                        if (!connectToService()) {
1213                            Slog.e(TAG, "Failed to bind to media container service");
1214                            params.serviceError();
1215                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1216                                    System.identityHashCode(mHandler));
1217                            if (params.traceMethod != null) {
1218                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1219                                        params.traceCookie);
1220                            }
1221                            return;
1222                        } else {
1223                            // Once we bind to the service, the first
1224                            // pending request will be processed.
1225                            mPendingInstalls.add(idx, params);
1226                        }
1227                    } else {
1228                        mPendingInstalls.add(idx, params);
1229                        // Already bound to the service. Just make
1230                        // sure we trigger off processing the first request.
1231                        if (idx == 0) {
1232                            mHandler.sendEmptyMessage(MCS_BOUND);
1233                        }
1234                    }
1235                    break;
1236                }
1237                case MCS_BOUND: {
1238                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1239                    if (msg.obj != null) {
1240                        mContainerService = (IMediaContainerService) msg.obj;
1241                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1242                                System.identityHashCode(mHandler));
1243                    }
1244                    if (mContainerService == null) {
1245                        if (!mBound) {
1246                            // Something seriously wrong since we are not bound and we are not
1247                            // waiting for connection. Bail out.
1248                            Slog.e(TAG, "Cannot bind to media container service");
1249                            for (HandlerParams params : mPendingInstalls) {
1250                                // Indicate service bind error
1251                                params.serviceError();
1252                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1253                                        System.identityHashCode(params));
1254                                if (params.traceMethod != null) {
1255                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1256                                            params.traceMethod, params.traceCookie);
1257                                }
1258                                return;
1259                            }
1260                            mPendingInstalls.clear();
1261                        } else {
1262                            Slog.w(TAG, "Waiting to connect to media container service");
1263                        }
1264                    } else if (mPendingInstalls.size() > 0) {
1265                        HandlerParams params = mPendingInstalls.get(0);
1266                        if (params != null) {
1267                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1268                                    System.identityHashCode(params));
1269                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1270                            if (params.startCopy()) {
1271                                // We are done...  look for more work or to
1272                                // go idle.
1273                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1274                                        "Checking for more work or unbind...");
1275                                // Delete pending install
1276                                if (mPendingInstalls.size() > 0) {
1277                                    mPendingInstalls.remove(0);
1278                                }
1279                                if (mPendingInstalls.size() == 0) {
1280                                    if (mBound) {
1281                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1282                                                "Posting delayed MCS_UNBIND");
1283                                        removeMessages(MCS_UNBIND);
1284                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1285                                        // Unbind after a little delay, to avoid
1286                                        // continual thrashing.
1287                                        sendMessageDelayed(ubmsg, 10000);
1288                                    }
1289                                } else {
1290                                    // There are more pending requests in queue.
1291                                    // Just post MCS_BOUND message to trigger processing
1292                                    // of next pending install.
1293                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1294                                            "Posting MCS_BOUND for next work");
1295                                    mHandler.sendEmptyMessage(MCS_BOUND);
1296                                }
1297                            }
1298                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1299                        }
1300                    } else {
1301                        // Should never happen ideally.
1302                        Slog.w(TAG, "Empty queue");
1303                    }
1304                    break;
1305                }
1306                case MCS_RECONNECT: {
1307                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1308                    if (mPendingInstalls.size() > 0) {
1309                        if (mBound) {
1310                            disconnectService();
1311                        }
1312                        if (!connectToService()) {
1313                            Slog.e(TAG, "Failed to bind to media container service");
1314                            for (HandlerParams params : mPendingInstalls) {
1315                                // Indicate service bind error
1316                                params.serviceError();
1317                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1318                                        System.identityHashCode(params));
1319                            }
1320                            mPendingInstalls.clear();
1321                        }
1322                    }
1323                    break;
1324                }
1325                case MCS_UNBIND: {
1326                    // If there is no actual work left, then time to unbind.
1327                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1328
1329                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1330                        if (mBound) {
1331                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1332
1333                            disconnectService();
1334                        }
1335                    } else if (mPendingInstalls.size() > 0) {
1336                        // There are more pending requests in queue.
1337                        // Just post MCS_BOUND message to trigger processing
1338                        // of next pending install.
1339                        mHandler.sendEmptyMessage(MCS_BOUND);
1340                    }
1341
1342                    break;
1343                }
1344                case MCS_GIVE_UP: {
1345                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1346                    HandlerParams params = mPendingInstalls.remove(0);
1347                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1348                            System.identityHashCode(params));
1349                    break;
1350                }
1351                case SEND_PENDING_BROADCAST: {
1352                    String packages[];
1353                    ArrayList<String> components[];
1354                    int size = 0;
1355                    int uids[];
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1357                    synchronized (mPackages) {
1358                        if (mPendingBroadcasts == null) {
1359                            return;
1360                        }
1361                        size = mPendingBroadcasts.size();
1362                        if (size <= 0) {
1363                            // Nothing to be done. Just return
1364                            return;
1365                        }
1366                        packages = new String[size];
1367                        components = new ArrayList[size];
1368                        uids = new int[size];
1369                        int i = 0;  // filling out the above arrays
1370
1371                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1372                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1373                            Iterator<Map.Entry<String, ArrayList<String>>> it
1374                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1375                                            .entrySet().iterator();
1376                            while (it.hasNext() && i < size) {
1377                                Map.Entry<String, ArrayList<String>> ent = it.next();
1378                                packages[i] = ent.getKey();
1379                                components[i] = ent.getValue();
1380                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1381                                uids[i] = (ps != null)
1382                                        ? UserHandle.getUid(packageUserId, ps.appId)
1383                                        : -1;
1384                                i++;
1385                            }
1386                        }
1387                        size = i;
1388                        mPendingBroadcasts.clear();
1389                    }
1390                    // Send broadcasts
1391                    for (int i = 0; i < size; i++) {
1392                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1393                    }
1394                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1395                    break;
1396                }
1397                case START_CLEANING_PACKAGE: {
1398                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1399                    final String packageName = (String)msg.obj;
1400                    final int userId = msg.arg1;
1401                    final boolean andCode = msg.arg2 != 0;
1402                    synchronized (mPackages) {
1403                        if (userId == UserHandle.USER_ALL) {
1404                            int[] users = sUserManager.getUserIds();
1405                            for (int user : users) {
1406                                mSettings.addPackageToCleanLPw(
1407                                        new PackageCleanItem(user, packageName, andCode));
1408                            }
1409                        } else {
1410                            mSettings.addPackageToCleanLPw(
1411                                    new PackageCleanItem(userId, packageName, andCode));
1412                        }
1413                    }
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                    startCleaningPackages();
1416                } break;
1417                case POST_INSTALL: {
1418                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1419
1420                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1421                    mRunningInstalls.delete(msg.arg1);
1422                    boolean deleteOld = false;
1423
1424                    if (data != null) {
1425                        InstallArgs args = data.args;
1426                        PackageInstalledInfo res = data.res;
1427
1428                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1429                            final String packageName = res.pkg.applicationInfo.packageName;
1430                            res.removedInfo.sendBroadcast(false, true, false);
1431                            Bundle extras = new Bundle(1);
1432                            extras.putInt(Intent.EXTRA_UID, res.uid);
1433
1434                            // Now that we successfully installed the package, grant runtime
1435                            // permissions if requested before broadcasting the install.
1436                            if ((args.installFlags
1437                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1438                                    && res.pkg.applicationInfo.targetSdkVersion
1439                                            >= Build.VERSION_CODES.M) {
1440                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1441                                        args.installGrantPermissions);
1442                            }
1443
1444                            synchronized (mPackages) {
1445                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1446                            }
1447
1448                            // Determine the set of users who are adding this
1449                            // package for the first time vs. those who are seeing
1450                            // an update.
1451                            int[] firstUsers;
1452                            int[] updateUsers = new int[0];
1453                            if (res.origUsers == null || res.origUsers.length == 0) {
1454                                firstUsers = res.newUsers;
1455                            } else {
1456                                firstUsers = new int[0];
1457                                for (int i=0; i<res.newUsers.length; i++) {
1458                                    int user = res.newUsers[i];
1459                                    boolean isNew = true;
1460                                    for (int j=0; j<res.origUsers.length; j++) {
1461                                        if (res.origUsers[j] == user) {
1462                                            isNew = false;
1463                                            break;
1464                                        }
1465                                    }
1466                                    if (isNew) {
1467                                        int[] newFirst = new int[firstUsers.length+1];
1468                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1469                                                firstUsers.length);
1470                                        newFirst[firstUsers.length] = user;
1471                                        firstUsers = newFirst;
1472                                    } else {
1473                                        int[] newUpdate = new int[updateUsers.length+1];
1474                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1475                                                updateUsers.length);
1476                                        newUpdate[updateUsers.length] = user;
1477                                        updateUsers = newUpdate;
1478                                    }
1479                                }
1480                            }
1481                            // don't broadcast for ephemeral installs/updates
1482                            final boolean isEphemeral = isEphemeral(res.pkg);
1483                            if (!isEphemeral) {
1484                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1485                                        extras, 0 /*flags*/, null /*targetPackage*/,
1486                                        null /*finishedReceiver*/, firstUsers);
1487                            }
1488                            final boolean update = res.removedInfo.removedPackage != null;
1489                            if (update) {
1490                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1491                            }
1492                            if (!isEphemeral) {
1493                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1494                                        extras, 0 /*flags*/, null /*targetPackage*/,
1495                                        null /*finishedReceiver*/, updateUsers);
1496                            }
1497                            if (update) {
1498                                if (!isEphemeral) {
1499                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1500                                            packageName, extras, 0 /*flags*/,
1501                                            null /*targetPackage*/, null /*finishedReceiver*/,
1502                                            updateUsers);
1503                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1504                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1505                                            packageName /*targetPackage*/,
1506                                            null /*finishedReceiver*/, updateUsers);
1507                                }
1508
1509                                // treat asec-hosted packages like removable media on upgrade
1510                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1511                                    if (DEBUG_INSTALL) {
1512                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1513                                                + " is ASEC-hosted -> AVAILABLE");
1514                                    }
1515                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1516                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1517                                    pkgList.add(packageName);
1518                                    sendResourcesChangedBroadcast(true, true,
1519                                            pkgList,uidArray, null);
1520                                }
1521                            }
1522                            if (res.removedInfo.args != null) {
1523                                // Remove the replaced package's older resources safely now
1524                                deleteOld = true;
1525                            }
1526
1527
1528                            // Work that needs to happen on first install within each user
1529                            if (firstUsers.length > 0) {
1530                                for (int userId : firstUsers) {
1531                                    synchronized (mPackages) {
1532                                        // If this app is a browser and it's newly-installed for
1533                                        // some users, clear any default-browser state in those
1534                                        // users.  The app's nature doesn't depend on the user,
1535                                        // so we can just check its browser nature in any user
1536                                        // and generalize.
1537                                        if (packageIsBrowser(packageName, firstUsers[0])) {
1538                                            mSettings.setDefaultBrowserPackageNameLPw(
1539                                                    null, userId);
1540                                        }
1541
1542                                        // We may also need to apply pending (restored) runtime
1543                                        // permission grants within these users.
1544                                        mSettings.applyPendingPermissionGrantsLPw(
1545                                                packageName, userId);
1546                                    }
1547                                }
1548                            }
1549                            // Log current value of "unknown sources" setting
1550                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1551                                getUnknownSourcesSettings());
1552                        }
1553                        // Force a gc to clear up things
1554                        Runtime.getRuntime().gc();
1555                        // We delete after a gc for applications  on sdcard.
1556                        if (deleteOld) {
1557                            synchronized (mInstallLock) {
1558                                res.removedInfo.args.doPostDeleteLI(true);
1559                            }
1560                        }
1561                        if (args.observer != null) {
1562                            try {
1563                                Bundle extras = extrasForInstallResult(res);
1564                                args.observer.onPackageInstalled(res.name, res.returnCode,
1565                                        res.returnMsg, extras);
1566                            } catch (RemoteException e) {
1567                                Slog.i(TAG, "Observer no longer exists.");
1568                            }
1569                        }
1570                        if (args.traceMethod != null) {
1571                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1572                                    args.traceCookie);
1573                        }
1574                        return;
1575                    } else {
1576                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1577                    }
1578
1579                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1580                } break;
1581                case UPDATED_MEDIA_STATUS: {
1582                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1583                    boolean reportStatus = msg.arg1 == 1;
1584                    boolean doGc = msg.arg2 == 1;
1585                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1586                    if (doGc) {
1587                        // Force a gc to clear up stale containers.
1588                        Runtime.getRuntime().gc();
1589                    }
1590                    if (msg.obj != null) {
1591                        @SuppressWarnings("unchecked")
1592                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1593                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1594                        // Unload containers
1595                        unloadAllContainers(args);
1596                    }
1597                    if (reportStatus) {
1598                        try {
1599                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1600                            PackageHelper.getMountService().finishMediaUpdate();
1601                        } catch (RemoteException e) {
1602                            Log.e(TAG, "MountService not running?");
1603                        }
1604                    }
1605                } break;
1606                case WRITE_SETTINGS: {
1607                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1608                    synchronized (mPackages) {
1609                        removeMessages(WRITE_SETTINGS);
1610                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1611                        mSettings.writeLPr();
1612                        mDirtyUsers.clear();
1613                    }
1614                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1615                } break;
1616                case WRITE_PACKAGE_RESTRICTIONS: {
1617                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1618                    synchronized (mPackages) {
1619                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1620                        for (int userId : mDirtyUsers) {
1621                            mSettings.writePackageRestrictionsLPr(userId);
1622                        }
1623                        mDirtyUsers.clear();
1624                    }
1625                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1626                } break;
1627                case CHECK_PENDING_VERIFICATION: {
1628                    final int verificationId = msg.arg1;
1629                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1630
1631                    if ((state != null) && !state.timeoutExtended()) {
1632                        final InstallArgs args = state.getInstallArgs();
1633                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1634
1635                        Slog.i(TAG, "Verification timed out for " + originUri);
1636                        mPendingVerification.remove(verificationId);
1637
1638                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1639
1640                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1641                            Slog.i(TAG, "Continuing with installation of " + originUri);
1642                            state.setVerifierResponse(Binder.getCallingUid(),
1643                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1644                            broadcastPackageVerified(verificationId, originUri,
1645                                    PackageManager.VERIFICATION_ALLOW,
1646                                    state.getInstallArgs().getUser());
1647                            try {
1648                                ret = args.copyApk(mContainerService, true);
1649                            } catch (RemoteException e) {
1650                                Slog.e(TAG, "Could not contact the ContainerService");
1651                            }
1652                        } else {
1653                            broadcastPackageVerified(verificationId, originUri,
1654                                    PackageManager.VERIFICATION_REJECT,
1655                                    state.getInstallArgs().getUser());
1656                        }
1657
1658                        Trace.asyncTraceEnd(
1659                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1660
1661                        processPendingInstall(args, ret);
1662                        mHandler.sendEmptyMessage(MCS_UNBIND);
1663                    }
1664                    break;
1665                }
1666                case PACKAGE_VERIFIED: {
1667                    final int verificationId = msg.arg1;
1668
1669                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1670                    if (state == null) {
1671                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1672                        break;
1673                    }
1674
1675                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1676
1677                    state.setVerifierResponse(response.callerUid, response.code);
1678
1679                    if (state.isVerificationComplete()) {
1680                        mPendingVerification.remove(verificationId);
1681
1682                        final InstallArgs args = state.getInstallArgs();
1683                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1684
1685                        int ret;
1686                        if (state.isInstallAllowed()) {
1687                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1688                            broadcastPackageVerified(verificationId, originUri,
1689                                    response.code, state.getInstallArgs().getUser());
1690                            try {
1691                                ret = args.copyApk(mContainerService, true);
1692                            } catch (RemoteException e) {
1693                                Slog.e(TAG, "Could not contact the ContainerService");
1694                            }
1695                        } else {
1696                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1697                        }
1698
1699                        Trace.asyncTraceEnd(
1700                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1701
1702                        processPendingInstall(args, ret);
1703                        mHandler.sendEmptyMessage(MCS_UNBIND);
1704                    }
1705
1706                    break;
1707                }
1708                case START_INTENT_FILTER_VERIFICATIONS: {
1709                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1710                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1711                            params.replacing, params.pkg);
1712                    break;
1713                }
1714                case INTENT_FILTER_VERIFIED: {
1715                    final int verificationId = msg.arg1;
1716
1717                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1718                            verificationId);
1719                    if (state == null) {
1720                        Slog.w(TAG, "Invalid IntentFilter verification token "
1721                                + verificationId + " received");
1722                        break;
1723                    }
1724
1725                    final int userId = state.getUserId();
1726
1727                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1728                            "Processing IntentFilter verification with token:"
1729                            + verificationId + " and userId:" + userId);
1730
1731                    final IntentFilterVerificationResponse response =
1732                            (IntentFilterVerificationResponse) msg.obj;
1733
1734                    state.setVerifierResponse(response.callerUid, response.code);
1735
1736                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1737                            "IntentFilter verification with token:" + verificationId
1738                            + " and userId:" + userId
1739                            + " is settings verifier response with response code:"
1740                            + response.code);
1741
1742                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1743                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1744                                + response.getFailedDomainsString());
1745                    }
1746
1747                    if (state.isVerificationComplete()) {
1748                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1749                    } else {
1750                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1751                                "IntentFilter verification with token:" + verificationId
1752                                + " was not said to be complete");
1753                    }
1754
1755                    break;
1756                }
1757            }
1758        }
1759    }
1760
1761    private StorageEventListener mStorageListener = new StorageEventListener() {
1762        @Override
1763        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1764            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1765                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1766                    final String volumeUuid = vol.getFsUuid();
1767
1768                    // Clean up any users or apps that were removed or recreated
1769                    // while this volume was missing
1770                    reconcileUsers(volumeUuid);
1771                    reconcileApps(volumeUuid);
1772
1773                    // Clean up any install sessions that expired or were
1774                    // cancelled while this volume was missing
1775                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1776
1777                    loadPrivatePackages(vol);
1778
1779                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1780                    unloadPrivatePackages(vol);
1781                }
1782            }
1783
1784            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1785                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1786                    updateExternalMediaStatus(true, false);
1787                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1788                    updateExternalMediaStatus(false, false);
1789                }
1790            }
1791        }
1792
1793        @Override
1794        public void onVolumeForgotten(String fsUuid) {
1795            if (TextUtils.isEmpty(fsUuid)) {
1796                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1797                return;
1798            }
1799
1800            // Remove any apps installed on the forgotten volume
1801            synchronized (mPackages) {
1802                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1803                for (PackageSetting ps : packages) {
1804                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1805                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1806                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1807                }
1808
1809                mSettings.onVolumeForgotten(fsUuid);
1810                mSettings.writeLPr();
1811            }
1812        }
1813    };
1814
1815    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1816            String[] grantedPermissions) {
1817        if (userId >= UserHandle.USER_SYSTEM) {
1818            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1819        } else if (userId == UserHandle.USER_ALL) {
1820            final int[] userIds;
1821            synchronized (mPackages) {
1822                userIds = UserManagerService.getInstance().getUserIds();
1823            }
1824            for (int someUserId : userIds) {
1825                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1826            }
1827        }
1828
1829        // We could have touched GID membership, so flush out packages.list
1830        synchronized (mPackages) {
1831            mSettings.writePackageListLPr();
1832        }
1833    }
1834
1835    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1836            String[] grantedPermissions) {
1837        SettingBase sb = (SettingBase) pkg.mExtras;
1838        if (sb == null) {
1839            return;
1840        }
1841
1842        PermissionsState permissionsState = sb.getPermissionsState();
1843
1844        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1845                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1846
1847        synchronized (mPackages) {
1848            for (String permission : pkg.requestedPermissions) {
1849                BasePermission bp = mSettings.mPermissions.get(permission);
1850                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1851                        && (grantedPermissions == null
1852                               || ArrayUtils.contains(grantedPermissions, permission))) {
1853                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1854                    // Installer cannot change immutable permissions.
1855                    if ((flags & immutableFlags) == 0) {
1856                        grantRuntimePermission(pkg.packageName, permission, userId);
1857                    }
1858                }
1859            }
1860        }
1861    }
1862
1863    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1864        Bundle extras = null;
1865        switch (res.returnCode) {
1866            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1867                extras = new Bundle();
1868                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1869                        res.origPermission);
1870                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1871                        res.origPackage);
1872                break;
1873            }
1874            case PackageManager.INSTALL_SUCCEEDED: {
1875                extras = new Bundle();
1876                extras.putBoolean(Intent.EXTRA_REPLACING,
1877                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1878                break;
1879            }
1880        }
1881        return extras;
1882    }
1883
1884    void scheduleWriteSettingsLocked() {
1885        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1886            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1887        }
1888    }
1889
1890    void scheduleWritePackageRestrictionsLocked(int userId) {
1891        if (!sUserManager.exists(userId)) return;
1892        mDirtyUsers.add(userId);
1893        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1894            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1895        }
1896    }
1897
1898    public static PackageManagerService main(Context context, Installer installer,
1899            boolean factoryTest, boolean onlyCore) {
1900        PackageManagerService m = new PackageManagerService(context, installer,
1901                factoryTest, onlyCore);
1902        m.enableSystemUserPackages();
1903        ServiceManager.addService("package", m);
1904        return m;
1905    }
1906
1907    private void enableSystemUserPackages() {
1908        if (!UserManager.isSplitSystemUser()) {
1909            return;
1910        }
1911        // For system user, enable apps based on the following conditions:
1912        // - app is whitelisted or belong to one of these groups:
1913        //   -- system app which has no launcher icons
1914        //   -- system app which has INTERACT_ACROSS_USERS permission
1915        //   -- system IME app
1916        // - app is not in the blacklist
1917        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1918        Set<String> enableApps = new ArraySet<>();
1919        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1920                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1921                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1922        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1923        enableApps.addAll(wlApps);
1924        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1925                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1926        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1927        enableApps.removeAll(blApps);
1928        Log.i(TAG, "Applications installed for system user: " + enableApps);
1929        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1930                UserHandle.SYSTEM);
1931        final int allAppsSize = allAps.size();
1932        synchronized (mPackages) {
1933            for (int i = 0; i < allAppsSize; i++) {
1934                String pName = allAps.get(i);
1935                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1936                // Should not happen, but we shouldn't be failing if it does
1937                if (pkgSetting == null) {
1938                    continue;
1939                }
1940                boolean install = enableApps.contains(pName);
1941                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1942                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1943                            + " for system user");
1944                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1945                }
1946            }
1947        }
1948    }
1949
1950    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1951        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1952                Context.DISPLAY_SERVICE);
1953        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1954    }
1955
1956    public PackageManagerService(Context context, Installer installer,
1957            boolean factoryTest, boolean onlyCore) {
1958        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1959                SystemClock.uptimeMillis());
1960
1961        if (mSdkVersion <= 0) {
1962            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1963        }
1964
1965        mContext = context;
1966        mFactoryTest = factoryTest;
1967        mOnlyCore = onlyCore;
1968        mMetrics = new DisplayMetrics();
1969        mSettings = new Settings(mPackages);
1970        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1971                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1972        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1973                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1974        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1975                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1976        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1977                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1978        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1979                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1980        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1981                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1982
1983        String separateProcesses = SystemProperties.get("debug.separate_processes");
1984        if (separateProcesses != null && separateProcesses.length() > 0) {
1985            if ("*".equals(separateProcesses)) {
1986                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1987                mSeparateProcesses = null;
1988                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1989            } else {
1990                mDefParseFlags = 0;
1991                mSeparateProcesses = separateProcesses.split(",");
1992                Slog.w(TAG, "Running with debug.separate_processes: "
1993                        + separateProcesses);
1994            }
1995        } else {
1996            mDefParseFlags = 0;
1997            mSeparateProcesses = null;
1998        }
1999
2000        mInstaller = installer;
2001        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2002                "*dexopt*");
2003        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2004
2005        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2006                FgThread.get().getLooper());
2007
2008        getDefaultDisplayMetrics(context, mMetrics);
2009
2010        SystemConfig systemConfig = SystemConfig.getInstance();
2011        mGlobalGids = systemConfig.getGlobalGids();
2012        mSystemPermissions = systemConfig.getSystemPermissions();
2013        mAvailableFeatures = systemConfig.getAvailableFeatures();
2014
2015        synchronized (mInstallLock) {
2016        // writer
2017        synchronized (mPackages) {
2018            mHandlerThread = new ServiceThread(TAG,
2019                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2020            mHandlerThread.start();
2021            mHandler = new PackageHandler(mHandlerThread.getLooper());
2022            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2023
2024            File dataDir = Environment.getDataDirectory();
2025            mAppInstallDir = new File(dataDir, "app");
2026            mAppLib32InstallDir = new File(dataDir, "app-lib");
2027            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2028            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2029            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2030
2031            sUserManager = new UserManagerService(context, this, mPackages);
2032
2033            // Propagate permission configuration in to package manager.
2034            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2035                    = systemConfig.getPermissions();
2036            for (int i=0; i<permConfig.size(); i++) {
2037                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2038                BasePermission bp = mSettings.mPermissions.get(perm.name);
2039                if (bp == null) {
2040                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2041                    mSettings.mPermissions.put(perm.name, bp);
2042                }
2043                if (perm.gids != null) {
2044                    bp.setGids(perm.gids, perm.perUser);
2045                }
2046            }
2047
2048            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2049            for (int i=0; i<libConfig.size(); i++) {
2050                mSharedLibraries.put(libConfig.keyAt(i),
2051                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2052            }
2053
2054            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2055
2056            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2057
2058            String customResolverActivity = Resources.getSystem().getString(
2059                    R.string.config_customResolverActivity);
2060            if (TextUtils.isEmpty(customResolverActivity)) {
2061                customResolverActivity = null;
2062            } else {
2063                mCustomResolverComponentName = ComponentName.unflattenFromString(
2064                        customResolverActivity);
2065            }
2066
2067            long startTime = SystemClock.uptimeMillis();
2068
2069            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2070                    startTime);
2071
2072            // Set flag to monitor and not change apk file paths when
2073            // scanning install directories.
2074            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2075
2076            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2077            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2078
2079            if (bootClassPath == null) {
2080                Slog.w(TAG, "No BOOTCLASSPATH found!");
2081            }
2082
2083            if (systemServerClassPath == null) {
2084                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2085            }
2086
2087            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2088            final String[] dexCodeInstructionSets =
2089                    getDexCodeInstructionSets(
2090                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2091
2092            /**
2093             * Ensure all external libraries have had dexopt run on them.
2094             */
2095            if (mSharedLibraries.size() > 0) {
2096                // NOTE: For now, we're compiling these system "shared libraries"
2097                // (and framework jars) into all available architectures. It's possible
2098                // to compile them only when we come across an app that uses them (there's
2099                // already logic for that in scanPackageLI) but that adds some complexity.
2100                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2101                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2102                        final String lib = libEntry.path;
2103                        if (lib == null) {
2104                            continue;
2105                        }
2106
2107                        try {
2108                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2109                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2110                                // Shared libraries do not have profiles so we perform a full
2111                                // AOT compilation.
2112                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2113                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2114                                        StorageManager.UUID_PRIVATE_INTERNAL,
2115                                        false /*useProfiles*/);
2116                            }
2117                        } catch (FileNotFoundException e) {
2118                            Slog.w(TAG, "Library not found: " + lib);
2119                        } catch (IOException | InstallerException e) {
2120                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2121                                    + e.getMessage());
2122                        }
2123                    }
2124                }
2125            }
2126
2127            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2128
2129            final VersionInfo ver = mSettings.getInternalVersion();
2130            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2131            // when upgrading from pre-M, promote system app permissions from install to runtime
2132            mPromoteSystemApps =
2133                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2134
2135            // save off the names of pre-existing system packages prior to scanning; we don't
2136            // want to automatically grant runtime permissions for new system apps
2137            if (mPromoteSystemApps) {
2138                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2139                while (pkgSettingIter.hasNext()) {
2140                    PackageSetting ps = pkgSettingIter.next();
2141                    if (isSystemApp(ps)) {
2142                        mExistingSystemPackages.add(ps.name);
2143                    }
2144                }
2145            }
2146
2147            // Collect vendor overlay packages.
2148            // (Do this before scanning any apps.)
2149            // For security and version matching reason, only consider
2150            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2151            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2152            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2153                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2154
2155            // Find base frameworks (resource packages without code).
2156            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2157                    | PackageParser.PARSE_IS_SYSTEM_DIR
2158                    | PackageParser.PARSE_IS_PRIVILEGED,
2159                    scanFlags | SCAN_NO_DEX, 0);
2160
2161            // Collected privileged system packages.
2162            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2163            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2164                    | PackageParser.PARSE_IS_SYSTEM_DIR
2165                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2166
2167            // Collect ordinary system packages.
2168            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2169            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2170                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2171
2172            // Collect all vendor packages.
2173            File vendorAppDir = new File("/vendor/app");
2174            try {
2175                vendorAppDir = vendorAppDir.getCanonicalFile();
2176            } catch (IOException e) {
2177                // failed to look up canonical path, continue with original one
2178            }
2179            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2180                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2181
2182            // Collect all OEM packages.
2183            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2184            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2185                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2186
2187            // Prune any system packages that no longer exist.
2188            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2189            if (!mOnlyCore) {
2190                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2191                while (psit.hasNext()) {
2192                    PackageSetting ps = psit.next();
2193
2194                    /*
2195                     * If this is not a system app, it can't be a
2196                     * disable system app.
2197                     */
2198                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2199                        continue;
2200                    }
2201
2202                    /*
2203                     * If the package is scanned, it's not erased.
2204                     */
2205                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2206                    if (scannedPkg != null) {
2207                        /*
2208                         * If the system app is both scanned and in the
2209                         * disabled packages list, then it must have been
2210                         * added via OTA. Remove it from the currently
2211                         * scanned package so the previously user-installed
2212                         * application can be scanned.
2213                         */
2214                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2215                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2216                                    + ps.name + "; removing system app.  Last known codePath="
2217                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2218                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2219                                    + scannedPkg.mVersionCode);
2220                            removePackageLI(ps, true);
2221                            mExpectingBetter.put(ps.name, ps.codePath);
2222                        }
2223
2224                        continue;
2225                    }
2226
2227                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2228                        psit.remove();
2229                        logCriticalInfo(Log.WARN, "System package " + ps.name
2230                                + " no longer exists; wiping its data");
2231                        removeDataDirsLI(null, ps.name);
2232                    } else {
2233                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2234                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2235                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2236                        }
2237                    }
2238                }
2239            }
2240
2241            //look for any incomplete package installations
2242            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2243            //clean up list
2244            for(int i = 0; i < deletePkgsList.size(); i++) {
2245                //clean up here
2246                cleanupInstallFailedPackage(deletePkgsList.get(i));
2247            }
2248            //delete tmp files
2249            deleteTempPackageFiles();
2250
2251            // Remove any shared userIDs that have no associated packages
2252            mSettings.pruneSharedUsersLPw();
2253
2254            if (!mOnlyCore) {
2255                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2256                        SystemClock.uptimeMillis());
2257                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2258
2259                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2260                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2261
2262                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2263                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2264
2265                /**
2266                 * Remove disable package settings for any updated system
2267                 * apps that were removed via an OTA. If they're not a
2268                 * previously-updated app, remove them completely.
2269                 * Otherwise, just revoke their system-level permissions.
2270                 */
2271                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2272                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2273                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2274
2275                    String msg;
2276                    if (deletedPkg == null) {
2277                        msg = "Updated system package " + deletedAppName
2278                                + " no longer exists; wiping its data";
2279                        removeDataDirsLI(null, deletedAppName);
2280                    } else {
2281                        msg = "Updated system app + " + deletedAppName
2282                                + " no longer present; removing system privileges for "
2283                                + deletedAppName;
2284
2285                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2286
2287                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2288                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2289                    }
2290                    logCriticalInfo(Log.WARN, msg);
2291                }
2292
2293                /**
2294                 * Make sure all system apps that we expected to appear on
2295                 * the userdata partition actually showed up. If they never
2296                 * appeared, crawl back and revive the system version.
2297                 */
2298                for (int i = 0; i < mExpectingBetter.size(); i++) {
2299                    final String packageName = mExpectingBetter.keyAt(i);
2300                    if (!mPackages.containsKey(packageName)) {
2301                        final File scanFile = mExpectingBetter.valueAt(i);
2302
2303                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2304                                + " but never showed up; reverting to system");
2305
2306                        final int reparseFlags;
2307                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2308                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2309                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2310                                    | PackageParser.PARSE_IS_PRIVILEGED;
2311                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2312                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2313                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2314                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2315                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2316                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2317                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2318                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2319                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2320                        } else {
2321                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2322                            continue;
2323                        }
2324
2325                        mSettings.enableSystemPackageLPw(packageName);
2326
2327                        try {
2328                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2329                        } catch (PackageManagerException e) {
2330                            Slog.e(TAG, "Failed to parse original system package: "
2331                                    + e.getMessage());
2332                        }
2333                    }
2334                }
2335            }
2336            mExpectingBetter.clear();
2337
2338            // Now that we know all of the shared libraries, update all clients to have
2339            // the correct library paths.
2340            updateAllSharedLibrariesLPw();
2341
2342            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2343                // NOTE: We ignore potential failures here during a system scan (like
2344                // the rest of the commands above) because there's precious little we
2345                // can do about it. A settings error is reported, though.
2346                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2347                        false /* boot complete */);
2348            }
2349
2350            // Now that we know all the packages we are keeping,
2351            // read and update their last usage times.
2352            mPackageUsage.readLP();
2353
2354            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2355                    SystemClock.uptimeMillis());
2356            Slog.i(TAG, "Time to scan packages: "
2357                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2358                    + " seconds");
2359
2360            // If the platform SDK has changed since the last time we booted,
2361            // we need to re-grant app permission to catch any new ones that
2362            // appear.  This is really a hack, and means that apps can in some
2363            // cases get permissions that the user didn't initially explicitly
2364            // allow...  it would be nice to have some better way to handle
2365            // this situation.
2366            int updateFlags = UPDATE_PERMISSIONS_ALL;
2367            if (ver.sdkVersion != mSdkVersion) {
2368                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2369                        + mSdkVersion + "; regranting permissions for internal storage");
2370                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2371            }
2372            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2373            ver.sdkVersion = mSdkVersion;
2374
2375            // If this is the first boot or an update from pre-M, and it is a normal
2376            // boot, then we need to initialize the default preferred apps across
2377            // all defined users.
2378            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2379                for (UserInfo user : sUserManager.getUsers(true)) {
2380                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2381                    applyFactoryDefaultBrowserLPw(user.id);
2382                    primeDomainVerificationsLPw(user.id);
2383                }
2384            }
2385
2386            // Prepare storage for system user really early during boot,
2387            // since core system apps like SettingsProvider and SystemUI
2388            // can't wait for user to start
2389            final int flags;
2390            if (StorageManager.isFileBasedEncryptionEnabled()) {
2391                flags = Installer.FLAG_DE_STORAGE;
2392            } else {
2393                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
2394            }
2395            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2396
2397            // If this is first boot after an OTA, and a normal boot, then
2398            // we need to clear code cache directories.
2399            if (mIsUpgrade && !onlyCore) {
2400                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2401                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2402                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2403                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2404                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2405                    }
2406                }
2407                ver.fingerprint = Build.FINGERPRINT;
2408            }
2409
2410            checkDefaultBrowser();
2411
2412            // clear only after permissions and other defaults have been updated
2413            mExistingSystemPackages.clear();
2414            mPromoteSystemApps = false;
2415
2416            // All the changes are done during package scanning.
2417            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2418
2419            // can downgrade to reader
2420            mSettings.writeLPr();
2421
2422            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2423                    SystemClock.uptimeMillis());
2424
2425            if (!mOnlyCore) {
2426                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2427                mRequiredInstallerPackage = getRequiredInstallerLPr();
2428                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2429                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2430                        mIntentFilterVerifierComponent);
2431            } else {
2432                mRequiredVerifierPackage = null;
2433                mRequiredInstallerPackage = null;
2434                mIntentFilterVerifierComponent = null;
2435                mIntentFilterVerifier = null;
2436            }
2437
2438            mInstallerService = new PackageInstallerService(context, this);
2439
2440            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2441            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2442            // both the installer and resolver must be present to enable ephemeral
2443            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2444                if (DEBUG_EPHEMERAL) {
2445                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2446                            + " installer:" + ephemeralInstallerComponent);
2447                }
2448                mEphemeralResolverComponent = ephemeralResolverComponent;
2449                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2450                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2451                mEphemeralResolverConnection =
2452                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2453            } else {
2454                if (DEBUG_EPHEMERAL) {
2455                    final String missingComponent =
2456                            (ephemeralResolverComponent == null)
2457                            ? (ephemeralInstallerComponent == null)
2458                                    ? "resolver and installer"
2459                                    : "resolver"
2460                            : "installer";
2461                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2462                }
2463                mEphemeralResolverComponent = null;
2464                mEphemeralInstallerComponent = null;
2465                mEphemeralResolverConnection = null;
2466            }
2467
2468            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2469        } // synchronized (mPackages)
2470        } // synchronized (mInstallLock)
2471
2472        // Now after opening every single application zip, make sure they
2473        // are all flushed.  Not really needed, but keeps things nice and
2474        // tidy.
2475        Runtime.getRuntime().gc();
2476
2477        // The initial scanning above does many calls into installd while
2478        // holding the mPackages lock, but we're mostly interested in yelling
2479        // once we have a booted system.
2480        mInstaller.setWarnIfHeld(mPackages);
2481
2482        // Expose private service for system components to use.
2483        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2484    }
2485
2486    @Override
2487    public boolean isFirstBoot() {
2488        return !mRestoredSettings;
2489    }
2490
2491    @Override
2492    public boolean isOnlyCoreApps() {
2493        return mOnlyCore;
2494    }
2495
2496    @Override
2497    public boolean isUpgrade() {
2498        return mIsUpgrade;
2499    }
2500
2501    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2502        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2503
2504        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2505                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2506        if (matches.size() == 1) {
2507            return matches.get(0).getComponentInfo().packageName;
2508        } else {
2509            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2510            return null;
2511        }
2512    }
2513
2514    private @NonNull String getRequiredInstallerLPr() {
2515        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2516        intent.addCategory(Intent.CATEGORY_DEFAULT);
2517        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2518
2519        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2520                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2521        if (matches.size() == 1) {
2522            return matches.get(0).getComponentInfo().packageName;
2523        } else {
2524            throw new RuntimeException("There must be exactly one installer; found " + matches);
2525        }
2526    }
2527
2528    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2529        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2530
2531        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2532                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2533        ResolveInfo best = null;
2534        final int N = matches.size();
2535        for (int i = 0; i < N; i++) {
2536            final ResolveInfo cur = matches.get(i);
2537            final String packageName = cur.getComponentInfo().packageName;
2538            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2539                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2540                continue;
2541            }
2542
2543            if (best == null || cur.priority > best.priority) {
2544                best = cur;
2545            }
2546        }
2547
2548        if (best != null) {
2549            return best.getComponentInfo().getComponentName();
2550        } else {
2551            throw new RuntimeException("There must be at least one intent filter verifier");
2552        }
2553    }
2554
2555    private @Nullable ComponentName getEphemeralResolverLPr() {
2556        final String[] packageArray =
2557                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2558        if (packageArray.length == 0) {
2559            if (DEBUG_EPHEMERAL) {
2560                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2561            }
2562            return null;
2563        }
2564
2565        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2566        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2567                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2568
2569        final int N = resolvers.size();
2570        if (N == 0) {
2571            if (DEBUG_EPHEMERAL) {
2572                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2573            }
2574            return null;
2575        }
2576
2577        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2578        for (int i = 0; i < N; i++) {
2579            final ResolveInfo info = resolvers.get(i);
2580
2581            if (info.serviceInfo == null) {
2582                continue;
2583            }
2584
2585            final String packageName = info.serviceInfo.packageName;
2586            if (!possiblePackages.contains(packageName)) {
2587                if (DEBUG_EPHEMERAL) {
2588                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2589                            + " pkg: " + packageName + ", info:" + info);
2590                }
2591                continue;
2592            }
2593
2594            if (DEBUG_EPHEMERAL) {
2595                Slog.v(TAG, "Ephemeral resolver found;"
2596                        + " pkg: " + packageName + ", info:" + info);
2597            }
2598            return new ComponentName(packageName, info.serviceInfo.name);
2599        }
2600        if (DEBUG_EPHEMERAL) {
2601            Slog.v(TAG, "Ephemeral resolver NOT found");
2602        }
2603        return null;
2604    }
2605
2606    private @Nullable ComponentName getEphemeralInstallerLPr() {
2607        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2608        intent.addCategory(Intent.CATEGORY_DEFAULT);
2609        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2610
2611        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2612                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2613        if (matches.size() == 0) {
2614            return null;
2615        } else if (matches.size() == 1) {
2616            return matches.get(0).getComponentInfo().getComponentName();
2617        } else {
2618            throw new RuntimeException(
2619                    "There must be at most one ephemeral installer; found " + matches);
2620        }
2621    }
2622
2623    private void primeDomainVerificationsLPw(int userId) {
2624        if (DEBUG_DOMAIN_VERIFICATION) {
2625            Slog.d(TAG, "Priming domain verifications in user " + userId);
2626        }
2627
2628        SystemConfig systemConfig = SystemConfig.getInstance();
2629        ArraySet<String> packages = systemConfig.getLinkedApps();
2630        ArraySet<String> domains = new ArraySet<String>();
2631
2632        for (String packageName : packages) {
2633            PackageParser.Package pkg = mPackages.get(packageName);
2634            if (pkg != null) {
2635                if (!pkg.isSystemApp()) {
2636                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2637                    continue;
2638                }
2639
2640                domains.clear();
2641                for (PackageParser.Activity a : pkg.activities) {
2642                    for (ActivityIntentInfo filter : a.intents) {
2643                        if (hasValidDomains(filter)) {
2644                            domains.addAll(filter.getHostsList());
2645                        }
2646                    }
2647                }
2648
2649                if (domains.size() > 0) {
2650                    if (DEBUG_DOMAIN_VERIFICATION) {
2651                        Slog.v(TAG, "      + " + packageName);
2652                    }
2653                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2654                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2655                    // and then 'always' in the per-user state actually used for intent resolution.
2656                    final IntentFilterVerificationInfo ivi;
2657                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2658                            new ArrayList<String>(domains));
2659                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2660                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2661                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2662                } else {
2663                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2664                            + "' does not handle web links");
2665                }
2666            } else {
2667                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2668            }
2669        }
2670
2671        scheduleWritePackageRestrictionsLocked(userId);
2672        scheduleWriteSettingsLocked();
2673    }
2674
2675    private void applyFactoryDefaultBrowserLPw(int userId) {
2676        // The default browser app's package name is stored in a string resource,
2677        // with a product-specific overlay used for vendor customization.
2678        String browserPkg = mContext.getResources().getString(
2679                com.android.internal.R.string.default_browser);
2680        if (!TextUtils.isEmpty(browserPkg)) {
2681            // non-empty string => required to be a known package
2682            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2683            if (ps == null) {
2684                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2685                browserPkg = null;
2686            } else {
2687                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2688            }
2689        }
2690
2691        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2692        // default.  If there's more than one, just leave everything alone.
2693        if (browserPkg == null) {
2694            calculateDefaultBrowserLPw(userId);
2695        }
2696    }
2697
2698    private void calculateDefaultBrowserLPw(int userId) {
2699        List<String> allBrowsers = resolveAllBrowserApps(userId);
2700        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2701        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2702    }
2703
2704    private List<String> resolveAllBrowserApps(int userId) {
2705        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2706        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2707                PackageManager.MATCH_ALL, userId);
2708
2709        final int count = list.size();
2710        List<String> result = new ArrayList<String>(count);
2711        for (int i=0; i<count; i++) {
2712            ResolveInfo info = list.get(i);
2713            if (info.activityInfo == null
2714                    || !info.handleAllWebDataURI
2715                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2716                    || result.contains(info.activityInfo.packageName)) {
2717                continue;
2718            }
2719            result.add(info.activityInfo.packageName);
2720        }
2721
2722        return result;
2723    }
2724
2725    private boolean packageIsBrowser(String packageName, int userId) {
2726        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2727                PackageManager.MATCH_ALL, userId);
2728        final int N = list.size();
2729        for (int i = 0; i < N; i++) {
2730            ResolveInfo info = list.get(i);
2731            if (packageName.equals(info.activityInfo.packageName)) {
2732                return true;
2733            }
2734        }
2735        return false;
2736    }
2737
2738    private void checkDefaultBrowser() {
2739        final int myUserId = UserHandle.myUserId();
2740        final String packageName = getDefaultBrowserPackageName(myUserId);
2741        if (packageName != null) {
2742            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2743            if (info == null) {
2744                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2745                synchronized (mPackages) {
2746                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2747                }
2748            }
2749        }
2750    }
2751
2752    @Override
2753    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2754            throws RemoteException {
2755        try {
2756            return super.onTransact(code, data, reply, flags);
2757        } catch (RuntimeException e) {
2758            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2759                Slog.wtf(TAG, "Package Manager Crash", e);
2760            }
2761            throw e;
2762        }
2763    }
2764
2765    void cleanupInstallFailedPackage(PackageSetting ps) {
2766        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2767
2768        removeDataDirsLI(ps.volumeUuid, ps.name);
2769        if (ps.codePath != null) {
2770            removeCodePathLI(ps.codePath);
2771        }
2772        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2773            if (ps.resourcePath.isDirectory()) {
2774                FileUtils.deleteContents(ps.resourcePath);
2775            }
2776            ps.resourcePath.delete();
2777        }
2778        mSettings.removePackageLPw(ps.name);
2779    }
2780
2781    static int[] appendInts(int[] cur, int[] add) {
2782        if (add == null) return cur;
2783        if (cur == null) return add;
2784        final int N = add.length;
2785        for (int i=0; i<N; i++) {
2786            cur = appendInt(cur, add[i]);
2787        }
2788        return cur;
2789    }
2790
2791    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2792        if (!sUserManager.exists(userId)) return null;
2793        final PackageSetting ps = (PackageSetting) p.mExtras;
2794        if (ps == null) {
2795            return null;
2796        }
2797
2798        final PermissionsState permissionsState = ps.getPermissionsState();
2799
2800        final int[] gids = permissionsState.computeGids(userId);
2801        final Set<String> permissions = permissionsState.getPermissions(userId);
2802        final PackageUserState state = ps.readUserState(userId);
2803
2804        return PackageParser.generatePackageInfo(p, gids, flags,
2805                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2806    }
2807
2808    @Override
2809    public void checkPackageStartable(String packageName, int userId) {
2810        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2811
2812        synchronized (mPackages) {
2813            final PackageSetting ps = mSettings.mPackages.get(packageName);
2814            if (ps == null) {
2815                throw new SecurityException("Package " + packageName + " was not found!");
2816            }
2817
2818            if (ps.frozen) {
2819                throw new SecurityException("Package " + packageName + " is currently frozen!");
2820            }
2821
2822            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2823                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2824                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2825            }
2826        }
2827    }
2828
2829    @Override
2830    public boolean isPackageAvailable(String packageName, int userId) {
2831        if (!sUserManager.exists(userId)) return false;
2832        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2833        synchronized (mPackages) {
2834            PackageParser.Package p = mPackages.get(packageName);
2835            if (p != null) {
2836                final PackageSetting ps = (PackageSetting) p.mExtras;
2837                if (ps != null) {
2838                    final PackageUserState state = ps.readUserState(userId);
2839                    if (state != null) {
2840                        return PackageParser.isAvailable(state);
2841                    }
2842                }
2843            }
2844        }
2845        return false;
2846    }
2847
2848    @Override
2849    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2850        if (!sUserManager.exists(userId)) return null;
2851        flags = updateFlagsForPackage(flags, userId, packageName);
2852        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2853        // reader
2854        synchronized (mPackages) {
2855            PackageParser.Package p = mPackages.get(packageName);
2856            if (DEBUG_PACKAGE_INFO)
2857                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2858            if (p != null) {
2859                return generatePackageInfo(p, flags, userId);
2860            }
2861            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2862                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2863            }
2864        }
2865        return null;
2866    }
2867
2868    @Override
2869    public String[] currentToCanonicalPackageNames(String[] names) {
2870        String[] out = new String[names.length];
2871        // reader
2872        synchronized (mPackages) {
2873            for (int i=names.length-1; i>=0; i--) {
2874                PackageSetting ps = mSettings.mPackages.get(names[i]);
2875                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2876            }
2877        }
2878        return out;
2879    }
2880
2881    @Override
2882    public String[] canonicalToCurrentPackageNames(String[] names) {
2883        String[] out = new String[names.length];
2884        // reader
2885        synchronized (mPackages) {
2886            for (int i=names.length-1; i>=0; i--) {
2887                String cur = mSettings.mRenamedPackages.get(names[i]);
2888                out[i] = cur != null ? cur : names[i];
2889            }
2890        }
2891        return out;
2892    }
2893
2894    @Override
2895    public int getPackageUid(String packageName, int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return -1;
2897        flags = updateFlagsForPackage(flags, userId, packageName);
2898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2899
2900        // reader
2901        synchronized (mPackages) {
2902            final PackageParser.Package p = mPackages.get(packageName);
2903            if (p != null && p.isMatch(flags)) {
2904                return UserHandle.getUid(userId, p.applicationInfo.uid);
2905            }
2906            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2907                final PackageSetting ps = mSettings.mPackages.get(packageName);
2908                if (ps != null && ps.isMatch(flags)) {
2909                    return UserHandle.getUid(userId, ps.appId);
2910                }
2911            }
2912        }
2913
2914        return -1;
2915    }
2916
2917    @Override
2918    public int[] getPackageGids(String packageName, int flags, int userId) {
2919        if (!sUserManager.exists(userId)) return null;
2920        flags = updateFlagsForPackage(flags, userId, packageName);
2921        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2922                "getPackageGids");
2923
2924        // reader
2925        synchronized (mPackages) {
2926            final PackageParser.Package p = mPackages.get(packageName);
2927            if (p != null && p.isMatch(flags)) {
2928                PackageSetting ps = (PackageSetting) p.mExtras;
2929                return ps.getPermissionsState().computeGids(userId);
2930            }
2931            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2932                final PackageSetting ps = mSettings.mPackages.get(packageName);
2933                if (ps != null && ps.isMatch(flags)) {
2934                    return ps.getPermissionsState().computeGids(userId);
2935                }
2936            }
2937        }
2938
2939        return null;
2940    }
2941
2942    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2943        if (bp.perm != null) {
2944            return PackageParser.generatePermissionInfo(bp.perm, flags);
2945        }
2946        PermissionInfo pi = new PermissionInfo();
2947        pi.name = bp.name;
2948        pi.packageName = bp.sourcePackage;
2949        pi.nonLocalizedLabel = bp.name;
2950        pi.protectionLevel = bp.protectionLevel;
2951        return pi;
2952    }
2953
2954    @Override
2955    public PermissionInfo getPermissionInfo(String name, int flags) {
2956        // reader
2957        synchronized (mPackages) {
2958            final BasePermission p = mSettings.mPermissions.get(name);
2959            if (p != null) {
2960                return generatePermissionInfo(p, flags);
2961            }
2962            return null;
2963        }
2964    }
2965
2966    @Override
2967    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2968        // reader
2969        synchronized (mPackages) {
2970            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2971            for (BasePermission p : mSettings.mPermissions.values()) {
2972                if (group == null) {
2973                    if (p.perm == null || p.perm.info.group == null) {
2974                        out.add(generatePermissionInfo(p, flags));
2975                    }
2976                } else {
2977                    if (p.perm != null && group.equals(p.perm.info.group)) {
2978                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2979                    }
2980                }
2981            }
2982
2983            if (out.size() > 0) {
2984                return out;
2985            }
2986            return mPermissionGroups.containsKey(group) ? out : null;
2987        }
2988    }
2989
2990    @Override
2991    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2992        // reader
2993        synchronized (mPackages) {
2994            return PackageParser.generatePermissionGroupInfo(
2995                    mPermissionGroups.get(name), flags);
2996        }
2997    }
2998
2999    @Override
3000    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3001        // reader
3002        synchronized (mPackages) {
3003            final int N = mPermissionGroups.size();
3004            ArrayList<PermissionGroupInfo> out
3005                    = new ArrayList<PermissionGroupInfo>(N);
3006            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3007                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3008            }
3009            return out;
3010        }
3011    }
3012
3013    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3014            int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        PackageSetting ps = mSettings.mPackages.get(packageName);
3017        if (ps != null) {
3018            if (ps.pkg == null) {
3019                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3020                        flags, userId);
3021                if (pInfo != null) {
3022                    return pInfo.applicationInfo;
3023                }
3024                return null;
3025            }
3026            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3027                    ps.readUserState(userId), userId);
3028        }
3029        return null;
3030    }
3031
3032    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3033            int userId) {
3034        if (!sUserManager.exists(userId)) return null;
3035        PackageSetting ps = mSettings.mPackages.get(packageName);
3036        if (ps != null) {
3037            PackageParser.Package pkg = ps.pkg;
3038            if (pkg == null) {
3039                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3040                    return null;
3041                }
3042                // Only data remains, so we aren't worried about code paths
3043                pkg = new PackageParser.Package(packageName);
3044                pkg.applicationInfo.packageName = packageName;
3045                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3046                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3047                pkg.applicationInfo.uid = ps.appId;
3048                pkg.applicationInfo.initForUser(userId);
3049                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3050                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3051            }
3052            return generatePackageInfo(pkg, flags, userId);
3053        }
3054        return null;
3055    }
3056
3057    @Override
3058    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3059        if (!sUserManager.exists(userId)) return null;
3060        flags = updateFlagsForApplication(flags, userId, packageName);
3061        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3062        // writer
3063        synchronized (mPackages) {
3064            PackageParser.Package p = mPackages.get(packageName);
3065            if (DEBUG_PACKAGE_INFO) Log.v(
3066                    TAG, "getApplicationInfo " + packageName
3067                    + ": " + p);
3068            if (p != null) {
3069                PackageSetting ps = mSettings.mPackages.get(packageName);
3070                if (ps == null) return null;
3071                // Note: isEnabledLP() does not apply here - always return info
3072                return PackageParser.generateApplicationInfo(
3073                        p, flags, ps.readUserState(userId), userId);
3074            }
3075            if ("android".equals(packageName)||"system".equals(packageName)) {
3076                return mAndroidApplication;
3077            }
3078            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3079                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3080            }
3081        }
3082        return null;
3083    }
3084
3085    @Override
3086    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3087            final IPackageDataObserver observer) {
3088        mContext.enforceCallingOrSelfPermission(
3089                android.Manifest.permission.CLEAR_APP_CACHE, null);
3090        // Queue up an async operation since clearing cache may take a little while.
3091        mHandler.post(new Runnable() {
3092            public void run() {
3093                mHandler.removeCallbacks(this);
3094                boolean success = true;
3095                synchronized (mInstallLock) {
3096                    try {
3097                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3098                    } catch (InstallerException e) {
3099                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3100                        success = false;
3101                    }
3102                }
3103                if (observer != null) {
3104                    try {
3105                        observer.onRemoveCompleted(null, success);
3106                    } catch (RemoteException e) {
3107                        Slog.w(TAG, "RemoveException when invoking call back");
3108                    }
3109                }
3110            }
3111        });
3112    }
3113
3114    @Override
3115    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3116            final IntentSender pi) {
3117        mContext.enforceCallingOrSelfPermission(
3118                android.Manifest.permission.CLEAR_APP_CACHE, null);
3119        // Queue up an async operation since clearing cache may take a little while.
3120        mHandler.post(new Runnable() {
3121            public void run() {
3122                mHandler.removeCallbacks(this);
3123                boolean success = true;
3124                synchronized (mInstallLock) {
3125                    try {
3126                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3127                    } catch (InstallerException e) {
3128                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3129                        success = false;
3130                    }
3131                }
3132                if(pi != null) {
3133                    try {
3134                        // Callback via pending intent
3135                        int code = success ? 1 : 0;
3136                        pi.sendIntent(null, code, null,
3137                                null, null);
3138                    } catch (SendIntentException e1) {
3139                        Slog.i(TAG, "Failed to send pending intent");
3140                    }
3141                }
3142            }
3143        });
3144    }
3145
3146    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3147        synchronized (mInstallLock) {
3148            try {
3149                mInstaller.freeCache(volumeUuid, freeStorageSize);
3150            } catch (InstallerException e) {
3151                throw new IOException("Failed to free enough space", e);
3152            }
3153        }
3154    }
3155
3156    /**
3157     * Return if the user key is currently unlocked.
3158     */
3159    private boolean isUserKeyUnlocked(int userId) {
3160        if (StorageManager.isFileBasedEncryptionEnabled()) {
3161            final IMountService mount = IMountService.Stub
3162                    .asInterface(ServiceManager.getService("mount"));
3163            if (mount == null) {
3164                Slog.w(TAG, "Early during boot, assuming locked");
3165                return false;
3166            }
3167            final long token = Binder.clearCallingIdentity();
3168            try {
3169                return mount.isUserKeyUnlocked(userId);
3170            } catch (RemoteException e) {
3171                throw e.rethrowAsRuntimeException();
3172            } finally {
3173                Binder.restoreCallingIdentity(token);
3174            }
3175        } else {
3176            return true;
3177        }
3178    }
3179
3180    /**
3181     * Update given flags based on encryption status of current user.
3182     */
3183    private int updateFlags(int flags, int userId) {
3184        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3185                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3186            // Caller expressed an explicit opinion about what encryption
3187            // aware/unaware components they want to see, so fall through and
3188            // give them what they want
3189        } else {
3190            // Caller expressed no opinion, so match based on user state
3191            if (isUserKeyUnlocked(userId)) {
3192                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3193            } else {
3194                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3195            }
3196        }
3197
3198        // Safe mode means we should ignore any third-party apps
3199        if (mSafeMode) {
3200            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3201        }
3202
3203        return flags;
3204    }
3205
3206    /**
3207     * Update given flags when being used to request {@link PackageInfo}.
3208     */
3209    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3210        boolean triaged = true;
3211        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3212                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3213            // Caller is asking for component details, so they'd better be
3214            // asking for specific encryption matching behavior, or be triaged
3215            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3216                    | PackageManager.MATCH_ENCRYPTION_AWARE
3217                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3218                triaged = false;
3219            }
3220        }
3221        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3222                | PackageManager.MATCH_SYSTEM_ONLY
3223                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3224            triaged = false;
3225        }
3226        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3227            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3228                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3229        }
3230        return updateFlags(flags, userId);
3231    }
3232
3233    /**
3234     * Update given flags when being used to request {@link ApplicationInfo}.
3235     */
3236    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3237        return updateFlagsForPackage(flags, userId, cookie);
3238    }
3239
3240    /**
3241     * Update given flags when being used to request {@link ComponentInfo}.
3242     */
3243    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3244        if (cookie instanceof Intent) {
3245            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3246                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3247            }
3248        }
3249
3250        boolean triaged = true;
3251        // Caller is asking for component details, so they'd better be
3252        // asking for specific encryption matching behavior, or be triaged
3253        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3254                | PackageManager.MATCH_ENCRYPTION_AWARE
3255                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3256            triaged = false;
3257        }
3258        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3259            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3260                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3261        }
3262        return updateFlags(flags, userId);
3263    }
3264
3265    /**
3266     * Update given flags when being used to request {@link ResolveInfo}.
3267     */
3268    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3269        return updateFlagsForComponent(flags, userId, cookie);
3270    }
3271
3272    @Override
3273    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3274        if (!sUserManager.exists(userId)) return null;
3275        flags = updateFlagsForComponent(flags, userId, component);
3276        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3277        synchronized (mPackages) {
3278            PackageParser.Activity a = mActivities.mActivities.get(component);
3279
3280            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3281            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3282                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3283                if (ps == null) return null;
3284                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3285                        userId);
3286            }
3287            if (mResolveComponentName.equals(component)) {
3288                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3289                        new PackageUserState(), userId);
3290            }
3291        }
3292        return null;
3293    }
3294
3295    @Override
3296    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3297            String resolvedType) {
3298        synchronized (mPackages) {
3299            if (component.equals(mResolveComponentName)) {
3300                // The resolver supports EVERYTHING!
3301                return true;
3302            }
3303            PackageParser.Activity a = mActivities.mActivities.get(component);
3304            if (a == null) {
3305                return false;
3306            }
3307            for (int i=0; i<a.intents.size(); i++) {
3308                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3309                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3310                    return true;
3311                }
3312            }
3313            return false;
3314        }
3315    }
3316
3317    @Override
3318    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3319        if (!sUserManager.exists(userId)) return null;
3320        flags = updateFlagsForComponent(flags, userId, component);
3321        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3322        synchronized (mPackages) {
3323            PackageParser.Activity a = mReceivers.mActivities.get(component);
3324            if (DEBUG_PACKAGE_INFO) Log.v(
3325                TAG, "getReceiverInfo " + component + ": " + a);
3326            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3327                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3328                if (ps == null) return null;
3329                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3330                        userId);
3331            }
3332        }
3333        return null;
3334    }
3335
3336    @Override
3337    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3338        if (!sUserManager.exists(userId)) return null;
3339        flags = updateFlagsForComponent(flags, userId, component);
3340        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3341        synchronized (mPackages) {
3342            PackageParser.Service s = mServices.mServices.get(component);
3343            if (DEBUG_PACKAGE_INFO) Log.v(
3344                TAG, "getServiceInfo " + component + ": " + s);
3345            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3346                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3347                if (ps == null) return null;
3348                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3349                        userId);
3350            }
3351        }
3352        return null;
3353    }
3354
3355    @Override
3356    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3357        if (!sUserManager.exists(userId)) return null;
3358        flags = updateFlagsForComponent(flags, userId, component);
3359        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3360        synchronized (mPackages) {
3361            PackageParser.Provider p = mProviders.mProviders.get(component);
3362            if (DEBUG_PACKAGE_INFO) Log.v(
3363                TAG, "getProviderInfo " + component + ": " + p);
3364            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3365                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3366                if (ps == null) return null;
3367                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3368                        userId);
3369            }
3370        }
3371        return null;
3372    }
3373
3374    @Override
3375    public String[] getSystemSharedLibraryNames() {
3376        Set<String> libSet;
3377        synchronized (mPackages) {
3378            libSet = mSharedLibraries.keySet();
3379            int size = libSet.size();
3380            if (size > 0) {
3381                String[] libs = new String[size];
3382                libSet.toArray(libs);
3383                return libs;
3384            }
3385        }
3386        return null;
3387    }
3388
3389    @Override
3390    public FeatureInfo[] getSystemAvailableFeatures() {
3391        Collection<FeatureInfo> featSet;
3392        synchronized (mPackages) {
3393            featSet = mAvailableFeatures.values();
3394            int size = featSet.size();
3395            if (size > 0) {
3396                FeatureInfo[] features = new FeatureInfo[size+1];
3397                featSet.toArray(features);
3398                FeatureInfo fi = new FeatureInfo();
3399                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3400                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3401                features[size] = fi;
3402                return features;
3403            }
3404        }
3405        return null;
3406    }
3407
3408    @Override
3409    public boolean hasSystemFeature(String name) {
3410        synchronized (mPackages) {
3411            return mAvailableFeatures.containsKey(name);
3412        }
3413    }
3414
3415    @Override
3416    public int checkPermission(String permName, String pkgName, int userId) {
3417        if (!sUserManager.exists(userId)) {
3418            return PackageManager.PERMISSION_DENIED;
3419        }
3420
3421        synchronized (mPackages) {
3422            final PackageParser.Package p = mPackages.get(pkgName);
3423            if (p != null && p.mExtras != null) {
3424                final PackageSetting ps = (PackageSetting) p.mExtras;
3425                final PermissionsState permissionsState = ps.getPermissionsState();
3426                if (permissionsState.hasPermission(permName, userId)) {
3427                    return PackageManager.PERMISSION_GRANTED;
3428                }
3429                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3430                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3431                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3432                    return PackageManager.PERMISSION_GRANTED;
3433                }
3434            }
3435        }
3436
3437        return PackageManager.PERMISSION_DENIED;
3438    }
3439
3440    @Override
3441    public int checkUidPermission(String permName, int uid) {
3442        final int userId = UserHandle.getUserId(uid);
3443
3444        if (!sUserManager.exists(userId)) {
3445            return PackageManager.PERMISSION_DENIED;
3446        }
3447
3448        synchronized (mPackages) {
3449            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3450            if (obj != null) {
3451                final SettingBase ps = (SettingBase) obj;
3452                final PermissionsState permissionsState = ps.getPermissionsState();
3453                if (permissionsState.hasPermission(permName, userId)) {
3454                    return PackageManager.PERMISSION_GRANTED;
3455                }
3456                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3457                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3458                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3459                    return PackageManager.PERMISSION_GRANTED;
3460                }
3461            } else {
3462                ArraySet<String> perms = mSystemPermissions.get(uid);
3463                if (perms != null) {
3464                    if (perms.contains(permName)) {
3465                        return PackageManager.PERMISSION_GRANTED;
3466                    }
3467                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3468                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3469                        return PackageManager.PERMISSION_GRANTED;
3470                    }
3471                }
3472            }
3473        }
3474
3475        return PackageManager.PERMISSION_DENIED;
3476    }
3477
3478    @Override
3479    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3480        if (UserHandle.getCallingUserId() != userId) {
3481            mContext.enforceCallingPermission(
3482                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3483                    "isPermissionRevokedByPolicy for user " + userId);
3484        }
3485
3486        if (checkPermission(permission, packageName, userId)
3487                == PackageManager.PERMISSION_GRANTED) {
3488            return false;
3489        }
3490
3491        final long identity = Binder.clearCallingIdentity();
3492        try {
3493            final int flags = getPermissionFlags(permission, packageName, userId);
3494            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3495        } finally {
3496            Binder.restoreCallingIdentity(identity);
3497        }
3498    }
3499
3500    @Override
3501    public String getPermissionControllerPackageName() {
3502        synchronized (mPackages) {
3503            return mRequiredInstallerPackage;
3504        }
3505    }
3506
3507    /**
3508     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3509     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3510     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3511     * @param message the message to log on security exception
3512     */
3513    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3514            boolean checkShell, String message) {
3515        if (userId < 0) {
3516            throw new IllegalArgumentException("Invalid userId " + userId);
3517        }
3518        if (checkShell) {
3519            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3520        }
3521        if (userId == UserHandle.getUserId(callingUid)) return;
3522        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3523            if (requireFullPermission) {
3524                mContext.enforceCallingOrSelfPermission(
3525                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3526            } else {
3527                try {
3528                    mContext.enforceCallingOrSelfPermission(
3529                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3530                } catch (SecurityException se) {
3531                    mContext.enforceCallingOrSelfPermission(
3532                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3533                }
3534            }
3535        }
3536    }
3537
3538    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3539        if (callingUid == Process.SHELL_UID) {
3540            if (userHandle >= 0
3541                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3542                throw new SecurityException("Shell does not have permission to access user "
3543                        + userHandle);
3544            } else if (userHandle < 0) {
3545                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3546                        + Debug.getCallers(3));
3547            }
3548        }
3549    }
3550
3551    private BasePermission findPermissionTreeLP(String permName) {
3552        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3553            if (permName.startsWith(bp.name) &&
3554                    permName.length() > bp.name.length() &&
3555                    permName.charAt(bp.name.length()) == '.') {
3556                return bp;
3557            }
3558        }
3559        return null;
3560    }
3561
3562    private BasePermission checkPermissionTreeLP(String permName) {
3563        if (permName != null) {
3564            BasePermission bp = findPermissionTreeLP(permName);
3565            if (bp != null) {
3566                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3567                    return bp;
3568                }
3569                throw new SecurityException("Calling uid "
3570                        + Binder.getCallingUid()
3571                        + " is not allowed to add to permission tree "
3572                        + bp.name + " owned by uid " + bp.uid);
3573            }
3574        }
3575        throw new SecurityException("No permission tree found for " + permName);
3576    }
3577
3578    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3579        if (s1 == null) {
3580            return s2 == null;
3581        }
3582        if (s2 == null) {
3583            return false;
3584        }
3585        if (s1.getClass() != s2.getClass()) {
3586            return false;
3587        }
3588        return s1.equals(s2);
3589    }
3590
3591    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3592        if (pi1.icon != pi2.icon) return false;
3593        if (pi1.logo != pi2.logo) return false;
3594        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3595        if (!compareStrings(pi1.name, pi2.name)) return false;
3596        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3597        // We'll take care of setting this one.
3598        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3599        // These are not currently stored in settings.
3600        //if (!compareStrings(pi1.group, pi2.group)) return false;
3601        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3602        //if (pi1.labelRes != pi2.labelRes) return false;
3603        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3604        return true;
3605    }
3606
3607    int permissionInfoFootprint(PermissionInfo info) {
3608        int size = info.name.length();
3609        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3610        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3611        return size;
3612    }
3613
3614    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3615        int size = 0;
3616        for (BasePermission perm : mSettings.mPermissions.values()) {
3617            if (perm.uid == tree.uid) {
3618                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3619            }
3620        }
3621        return size;
3622    }
3623
3624    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3625        // We calculate the max size of permissions defined by this uid and throw
3626        // if that plus the size of 'info' would exceed our stated maximum.
3627        if (tree.uid != Process.SYSTEM_UID) {
3628            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3629            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3630                throw new SecurityException("Permission tree size cap exceeded");
3631            }
3632        }
3633    }
3634
3635    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3636        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3637            throw new SecurityException("Label must be specified in permission");
3638        }
3639        BasePermission tree = checkPermissionTreeLP(info.name);
3640        BasePermission bp = mSettings.mPermissions.get(info.name);
3641        boolean added = bp == null;
3642        boolean changed = true;
3643        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3644        if (added) {
3645            enforcePermissionCapLocked(info, tree);
3646            bp = new BasePermission(info.name, tree.sourcePackage,
3647                    BasePermission.TYPE_DYNAMIC);
3648        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3649            throw new SecurityException(
3650                    "Not allowed to modify non-dynamic permission "
3651                    + info.name);
3652        } else {
3653            if (bp.protectionLevel == fixedLevel
3654                    && bp.perm.owner.equals(tree.perm.owner)
3655                    && bp.uid == tree.uid
3656                    && comparePermissionInfos(bp.perm.info, info)) {
3657                changed = false;
3658            }
3659        }
3660        bp.protectionLevel = fixedLevel;
3661        info = new PermissionInfo(info);
3662        info.protectionLevel = fixedLevel;
3663        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3664        bp.perm.info.packageName = tree.perm.info.packageName;
3665        bp.uid = tree.uid;
3666        if (added) {
3667            mSettings.mPermissions.put(info.name, bp);
3668        }
3669        if (changed) {
3670            if (!async) {
3671                mSettings.writeLPr();
3672            } else {
3673                scheduleWriteSettingsLocked();
3674            }
3675        }
3676        return added;
3677    }
3678
3679    @Override
3680    public boolean addPermission(PermissionInfo info) {
3681        synchronized (mPackages) {
3682            return addPermissionLocked(info, false);
3683        }
3684    }
3685
3686    @Override
3687    public boolean addPermissionAsync(PermissionInfo info) {
3688        synchronized (mPackages) {
3689            return addPermissionLocked(info, true);
3690        }
3691    }
3692
3693    @Override
3694    public void removePermission(String name) {
3695        synchronized (mPackages) {
3696            checkPermissionTreeLP(name);
3697            BasePermission bp = mSettings.mPermissions.get(name);
3698            if (bp != null) {
3699                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3700                    throw new SecurityException(
3701                            "Not allowed to modify non-dynamic permission "
3702                            + name);
3703                }
3704                mSettings.mPermissions.remove(name);
3705                mSettings.writeLPr();
3706            }
3707        }
3708    }
3709
3710    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3711            BasePermission bp) {
3712        int index = pkg.requestedPermissions.indexOf(bp.name);
3713        if (index == -1) {
3714            throw new SecurityException("Package " + pkg.packageName
3715                    + " has not requested permission " + bp.name);
3716        }
3717        if (!bp.isRuntime() && !bp.isDevelopment()) {
3718            throw new SecurityException("Permission " + bp.name
3719                    + " is not a changeable permission type");
3720        }
3721    }
3722
3723    @Override
3724    public void grantRuntimePermission(String packageName, String name, final int userId) {
3725        if (!sUserManager.exists(userId)) {
3726            Log.e(TAG, "No such user:" + userId);
3727            return;
3728        }
3729
3730        mContext.enforceCallingOrSelfPermission(
3731                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3732                "grantRuntimePermission");
3733
3734        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3735                "grantRuntimePermission");
3736
3737        final int uid;
3738        final SettingBase sb;
3739
3740        synchronized (mPackages) {
3741            final PackageParser.Package pkg = mPackages.get(packageName);
3742            if (pkg == null) {
3743                throw new IllegalArgumentException("Unknown package: " + packageName);
3744            }
3745
3746            final BasePermission bp = mSettings.mPermissions.get(name);
3747            if (bp == null) {
3748                throw new IllegalArgumentException("Unknown permission: " + name);
3749            }
3750
3751            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3752
3753            // If a permission review is required for legacy apps we represent
3754            // their permissions as always granted runtime ones since we need
3755            // to keep the review required permission flag per user while an
3756            // install permission's state is shared across all users.
3757            if (Build.PERMISSIONS_REVIEW_REQUIRED
3758                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3759                    && bp.isRuntime()) {
3760                return;
3761            }
3762
3763            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3764            sb = (SettingBase) pkg.mExtras;
3765            if (sb == null) {
3766                throw new IllegalArgumentException("Unknown package: " + packageName);
3767            }
3768
3769            final PermissionsState permissionsState = sb.getPermissionsState();
3770
3771            final int flags = permissionsState.getPermissionFlags(name, userId);
3772            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3773                throw new SecurityException("Cannot grant system fixed permission "
3774                        + name + " for package " + packageName);
3775            }
3776
3777            if (bp.isDevelopment()) {
3778                // Development permissions must be handled specially, since they are not
3779                // normal runtime permissions.  For now they apply to all users.
3780                if (permissionsState.grantInstallPermission(bp) !=
3781                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3782                    scheduleWriteSettingsLocked();
3783                }
3784                return;
3785            }
3786
3787            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3788                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3789                return;
3790            }
3791
3792            final int result = permissionsState.grantRuntimePermission(bp, userId);
3793            switch (result) {
3794                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3795                    return;
3796                }
3797
3798                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3799                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3800                    mHandler.post(new Runnable() {
3801                        @Override
3802                        public void run() {
3803                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3804                        }
3805                    });
3806                }
3807                break;
3808            }
3809
3810            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3811
3812            // Not critical if that is lost - app has to request again.
3813            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3814        }
3815
3816        // Only need to do this if user is initialized. Otherwise it's a new user
3817        // and there are no processes running as the user yet and there's no need
3818        // to make an expensive call to remount processes for the changed permissions.
3819        if (READ_EXTERNAL_STORAGE.equals(name)
3820                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3821            final long token = Binder.clearCallingIdentity();
3822            try {
3823                if (sUserManager.isInitialized(userId)) {
3824                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3825                            MountServiceInternal.class);
3826                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3827                }
3828            } finally {
3829                Binder.restoreCallingIdentity(token);
3830            }
3831        }
3832    }
3833
3834    @Override
3835    public void revokeRuntimePermission(String packageName, String name, int userId) {
3836        if (!sUserManager.exists(userId)) {
3837            Log.e(TAG, "No such user:" + userId);
3838            return;
3839        }
3840
3841        mContext.enforceCallingOrSelfPermission(
3842                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3843                "revokeRuntimePermission");
3844
3845        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3846                "revokeRuntimePermission");
3847
3848        final int appId;
3849
3850        synchronized (mPackages) {
3851            final PackageParser.Package pkg = mPackages.get(packageName);
3852            if (pkg == null) {
3853                throw new IllegalArgumentException("Unknown package: " + packageName);
3854            }
3855
3856            final BasePermission bp = mSettings.mPermissions.get(name);
3857            if (bp == null) {
3858                throw new IllegalArgumentException("Unknown permission: " + name);
3859            }
3860
3861            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3862
3863            // If a permission review is required for legacy apps we represent
3864            // their permissions as always granted runtime ones since we need
3865            // to keep the review required permission flag per user while an
3866            // install permission's state is shared across all users.
3867            if (Build.PERMISSIONS_REVIEW_REQUIRED
3868                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3869                    && bp.isRuntime()) {
3870                return;
3871            }
3872
3873            SettingBase sb = (SettingBase) pkg.mExtras;
3874            if (sb == null) {
3875                throw new IllegalArgumentException("Unknown package: " + packageName);
3876            }
3877
3878            final PermissionsState permissionsState = sb.getPermissionsState();
3879
3880            final int flags = permissionsState.getPermissionFlags(name, userId);
3881            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3882                throw new SecurityException("Cannot revoke system fixed permission "
3883                        + name + " for package " + packageName);
3884            }
3885
3886            if (bp.isDevelopment()) {
3887                // Development permissions must be handled specially, since they are not
3888                // normal runtime permissions.  For now they apply to all users.
3889                if (permissionsState.revokeInstallPermission(bp) !=
3890                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3891                    scheduleWriteSettingsLocked();
3892                }
3893                return;
3894            }
3895
3896            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3897                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3898                return;
3899            }
3900
3901            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3902
3903            // Critical, after this call app should never have the permission.
3904            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3905
3906            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3907        }
3908
3909        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3910    }
3911
3912    @Override
3913    public void resetRuntimePermissions() {
3914        mContext.enforceCallingOrSelfPermission(
3915                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3916                "revokeRuntimePermission");
3917
3918        int callingUid = Binder.getCallingUid();
3919        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3920            mContext.enforceCallingOrSelfPermission(
3921                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3922                    "resetRuntimePermissions");
3923        }
3924
3925        synchronized (mPackages) {
3926            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3927            for (int userId : UserManagerService.getInstance().getUserIds()) {
3928                final int packageCount = mPackages.size();
3929                for (int i = 0; i < packageCount; i++) {
3930                    PackageParser.Package pkg = mPackages.valueAt(i);
3931                    if (!(pkg.mExtras instanceof PackageSetting)) {
3932                        continue;
3933                    }
3934                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3935                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3936                }
3937            }
3938        }
3939    }
3940
3941    @Override
3942    public int getPermissionFlags(String name, String packageName, int userId) {
3943        if (!sUserManager.exists(userId)) {
3944            return 0;
3945        }
3946
3947        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3948
3949        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3950                "getPermissionFlags");
3951
3952        synchronized (mPackages) {
3953            final PackageParser.Package pkg = mPackages.get(packageName);
3954            if (pkg == null) {
3955                throw new IllegalArgumentException("Unknown package: " + packageName);
3956            }
3957
3958            final BasePermission bp = mSettings.mPermissions.get(name);
3959            if (bp == null) {
3960                throw new IllegalArgumentException("Unknown permission: " + name);
3961            }
3962
3963            SettingBase sb = (SettingBase) pkg.mExtras;
3964            if (sb == null) {
3965                throw new IllegalArgumentException("Unknown package: " + packageName);
3966            }
3967
3968            PermissionsState permissionsState = sb.getPermissionsState();
3969            return permissionsState.getPermissionFlags(name, userId);
3970        }
3971    }
3972
3973    @Override
3974    public void updatePermissionFlags(String name, String packageName, int flagMask,
3975            int flagValues, int userId) {
3976        if (!sUserManager.exists(userId)) {
3977            return;
3978        }
3979
3980        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3981
3982        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3983                "updatePermissionFlags");
3984
3985        // Only the system can change these flags and nothing else.
3986        if (getCallingUid() != Process.SYSTEM_UID) {
3987            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3988            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3989            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3990            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3991            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3992        }
3993
3994        synchronized (mPackages) {
3995            final PackageParser.Package pkg = mPackages.get(packageName);
3996            if (pkg == null) {
3997                throw new IllegalArgumentException("Unknown package: " + packageName);
3998            }
3999
4000            final BasePermission bp = mSettings.mPermissions.get(name);
4001            if (bp == null) {
4002                throw new IllegalArgumentException("Unknown permission: " + name);
4003            }
4004
4005            SettingBase sb = (SettingBase) pkg.mExtras;
4006            if (sb == null) {
4007                throw new IllegalArgumentException("Unknown package: " + packageName);
4008            }
4009
4010            PermissionsState permissionsState = sb.getPermissionsState();
4011
4012            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4013
4014            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4015                // Install and runtime permissions are stored in different places,
4016                // so figure out what permission changed and persist the change.
4017                if (permissionsState.getInstallPermissionState(name) != null) {
4018                    scheduleWriteSettingsLocked();
4019                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4020                        || hadState) {
4021                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4022                }
4023            }
4024        }
4025    }
4026
4027    /**
4028     * Update the permission flags for all packages and runtime permissions of a user in order
4029     * to allow device or profile owner to remove POLICY_FIXED.
4030     */
4031    @Override
4032    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4033        if (!sUserManager.exists(userId)) {
4034            return;
4035        }
4036
4037        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4038
4039        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4040                "updatePermissionFlagsForAllApps");
4041
4042        // Only the system can change system fixed flags.
4043        if (getCallingUid() != Process.SYSTEM_UID) {
4044            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4045            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4046        }
4047
4048        synchronized (mPackages) {
4049            boolean changed = false;
4050            final int packageCount = mPackages.size();
4051            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4052                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4053                SettingBase sb = (SettingBase) pkg.mExtras;
4054                if (sb == null) {
4055                    continue;
4056                }
4057                PermissionsState permissionsState = sb.getPermissionsState();
4058                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4059                        userId, flagMask, flagValues);
4060            }
4061            if (changed) {
4062                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4063            }
4064        }
4065    }
4066
4067    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4068        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4069                != PackageManager.PERMISSION_GRANTED
4070            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4071                != PackageManager.PERMISSION_GRANTED) {
4072            throw new SecurityException(message + " requires "
4073                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4074                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4075        }
4076    }
4077
4078    @Override
4079    public boolean shouldShowRequestPermissionRationale(String permissionName,
4080            String packageName, int userId) {
4081        if (UserHandle.getCallingUserId() != userId) {
4082            mContext.enforceCallingPermission(
4083                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4084                    "canShowRequestPermissionRationale for user " + userId);
4085        }
4086
4087        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4088        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4089            return false;
4090        }
4091
4092        if (checkPermission(permissionName, packageName, userId)
4093                == PackageManager.PERMISSION_GRANTED) {
4094            return false;
4095        }
4096
4097        final int flags;
4098
4099        final long identity = Binder.clearCallingIdentity();
4100        try {
4101            flags = getPermissionFlags(permissionName,
4102                    packageName, userId);
4103        } finally {
4104            Binder.restoreCallingIdentity(identity);
4105        }
4106
4107        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4108                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4109                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4110
4111        if ((flags & fixedFlags) != 0) {
4112            return false;
4113        }
4114
4115        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4116    }
4117
4118    @Override
4119    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4120        mContext.enforceCallingOrSelfPermission(
4121                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4122                "addOnPermissionsChangeListener");
4123
4124        synchronized (mPackages) {
4125            mOnPermissionChangeListeners.addListenerLocked(listener);
4126        }
4127    }
4128
4129    @Override
4130    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4131        synchronized (mPackages) {
4132            mOnPermissionChangeListeners.removeListenerLocked(listener);
4133        }
4134    }
4135
4136    @Override
4137    public boolean isProtectedBroadcast(String actionName) {
4138        synchronized (mPackages) {
4139            if (mProtectedBroadcasts.contains(actionName)) {
4140                return true;
4141            } else if (actionName != null) {
4142                // TODO: remove these terrible hacks
4143                if (actionName.startsWith("android.net.netmon.lingerExpired")
4144                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4145                    return true;
4146                }
4147            }
4148        }
4149        return false;
4150    }
4151
4152    @Override
4153    public int checkSignatures(String pkg1, String pkg2) {
4154        synchronized (mPackages) {
4155            final PackageParser.Package p1 = mPackages.get(pkg1);
4156            final PackageParser.Package p2 = mPackages.get(pkg2);
4157            if (p1 == null || p1.mExtras == null
4158                    || p2 == null || p2.mExtras == null) {
4159                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4160            }
4161            return compareSignatures(p1.mSignatures, p2.mSignatures);
4162        }
4163    }
4164
4165    @Override
4166    public int checkUidSignatures(int uid1, int uid2) {
4167        // Map to base uids.
4168        uid1 = UserHandle.getAppId(uid1);
4169        uid2 = UserHandle.getAppId(uid2);
4170        // reader
4171        synchronized (mPackages) {
4172            Signature[] s1;
4173            Signature[] s2;
4174            Object obj = mSettings.getUserIdLPr(uid1);
4175            if (obj != null) {
4176                if (obj instanceof SharedUserSetting) {
4177                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4178                } else if (obj instanceof PackageSetting) {
4179                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4180                } else {
4181                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4182                }
4183            } else {
4184                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4185            }
4186            obj = mSettings.getUserIdLPr(uid2);
4187            if (obj != null) {
4188                if (obj instanceof SharedUserSetting) {
4189                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4190                } else if (obj instanceof PackageSetting) {
4191                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4192                } else {
4193                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4194                }
4195            } else {
4196                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4197            }
4198            return compareSignatures(s1, s2);
4199        }
4200    }
4201
4202    private void killUid(int appId, int userId, String reason) {
4203        final long identity = Binder.clearCallingIdentity();
4204        try {
4205            IActivityManager am = ActivityManagerNative.getDefault();
4206            if (am != null) {
4207                try {
4208                    am.killUid(appId, userId, reason);
4209                } catch (RemoteException e) {
4210                    /* ignore - same process */
4211                }
4212            }
4213        } finally {
4214            Binder.restoreCallingIdentity(identity);
4215        }
4216    }
4217
4218    /**
4219     * Compares two sets of signatures. Returns:
4220     * <br />
4221     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4222     * <br />
4223     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4224     * <br />
4225     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4226     * <br />
4227     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4228     * <br />
4229     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4230     */
4231    static int compareSignatures(Signature[] s1, Signature[] s2) {
4232        if (s1 == null) {
4233            return s2 == null
4234                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4235                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4236        }
4237
4238        if (s2 == null) {
4239            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4240        }
4241
4242        if (s1.length != s2.length) {
4243            return PackageManager.SIGNATURE_NO_MATCH;
4244        }
4245
4246        // Since both signature sets are of size 1, we can compare without HashSets.
4247        if (s1.length == 1) {
4248            return s1[0].equals(s2[0]) ?
4249                    PackageManager.SIGNATURE_MATCH :
4250                    PackageManager.SIGNATURE_NO_MATCH;
4251        }
4252
4253        ArraySet<Signature> set1 = new ArraySet<Signature>();
4254        for (Signature sig : s1) {
4255            set1.add(sig);
4256        }
4257        ArraySet<Signature> set2 = new ArraySet<Signature>();
4258        for (Signature sig : s2) {
4259            set2.add(sig);
4260        }
4261        // Make sure s2 contains all signatures in s1.
4262        if (set1.equals(set2)) {
4263            return PackageManager.SIGNATURE_MATCH;
4264        }
4265        return PackageManager.SIGNATURE_NO_MATCH;
4266    }
4267
4268    /**
4269     * If the database version for this type of package (internal storage or
4270     * external storage) is less than the version where package signatures
4271     * were updated, return true.
4272     */
4273    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4274        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4275        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4276    }
4277
4278    /**
4279     * Used for backward compatibility to make sure any packages with
4280     * certificate chains get upgraded to the new style. {@code existingSigs}
4281     * will be in the old format (since they were stored on disk from before the
4282     * system upgrade) and {@code scannedSigs} will be in the newer format.
4283     */
4284    private int compareSignaturesCompat(PackageSignatures existingSigs,
4285            PackageParser.Package scannedPkg) {
4286        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4287            return PackageManager.SIGNATURE_NO_MATCH;
4288        }
4289
4290        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4291        for (Signature sig : existingSigs.mSignatures) {
4292            existingSet.add(sig);
4293        }
4294        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4295        for (Signature sig : scannedPkg.mSignatures) {
4296            try {
4297                Signature[] chainSignatures = sig.getChainSignatures();
4298                for (Signature chainSig : chainSignatures) {
4299                    scannedCompatSet.add(chainSig);
4300                }
4301            } catch (CertificateEncodingException e) {
4302                scannedCompatSet.add(sig);
4303            }
4304        }
4305        /*
4306         * Make sure the expanded scanned set contains all signatures in the
4307         * existing one.
4308         */
4309        if (scannedCompatSet.equals(existingSet)) {
4310            // Migrate the old signatures to the new scheme.
4311            existingSigs.assignSignatures(scannedPkg.mSignatures);
4312            // The new KeySets will be re-added later in the scanning process.
4313            synchronized (mPackages) {
4314                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4315            }
4316            return PackageManager.SIGNATURE_MATCH;
4317        }
4318        return PackageManager.SIGNATURE_NO_MATCH;
4319    }
4320
4321    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4322        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4323        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4324    }
4325
4326    private int compareSignaturesRecover(PackageSignatures existingSigs,
4327            PackageParser.Package scannedPkg) {
4328        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4329            return PackageManager.SIGNATURE_NO_MATCH;
4330        }
4331
4332        String msg = null;
4333        try {
4334            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4335                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4336                        + scannedPkg.packageName);
4337                return PackageManager.SIGNATURE_MATCH;
4338            }
4339        } catch (CertificateException e) {
4340            msg = e.getMessage();
4341        }
4342
4343        logCriticalInfo(Log.INFO,
4344                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4345        return PackageManager.SIGNATURE_NO_MATCH;
4346    }
4347
4348    @Override
4349    public String[] getPackagesForUid(int uid) {
4350        uid = UserHandle.getAppId(uid);
4351        // reader
4352        synchronized (mPackages) {
4353            Object obj = mSettings.getUserIdLPr(uid);
4354            if (obj instanceof SharedUserSetting) {
4355                final SharedUserSetting sus = (SharedUserSetting) obj;
4356                final int N = sus.packages.size();
4357                final String[] res = new String[N];
4358                final Iterator<PackageSetting> it = sus.packages.iterator();
4359                int i = 0;
4360                while (it.hasNext()) {
4361                    res[i++] = it.next().name;
4362                }
4363                return res;
4364            } else if (obj instanceof PackageSetting) {
4365                final PackageSetting ps = (PackageSetting) obj;
4366                return new String[] { ps.name };
4367            }
4368        }
4369        return null;
4370    }
4371
4372    @Override
4373    public String getNameForUid(int uid) {
4374        // reader
4375        synchronized (mPackages) {
4376            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4377            if (obj instanceof SharedUserSetting) {
4378                final SharedUserSetting sus = (SharedUserSetting) obj;
4379                return sus.name + ":" + sus.userId;
4380            } else if (obj instanceof PackageSetting) {
4381                final PackageSetting ps = (PackageSetting) obj;
4382                return ps.name;
4383            }
4384        }
4385        return null;
4386    }
4387
4388    @Override
4389    public int getUidForSharedUser(String sharedUserName) {
4390        if(sharedUserName == null) {
4391            return -1;
4392        }
4393        // reader
4394        synchronized (mPackages) {
4395            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4396            if (suid == null) {
4397                return -1;
4398            }
4399            return suid.userId;
4400        }
4401    }
4402
4403    @Override
4404    public int getFlagsForUid(int uid) {
4405        synchronized (mPackages) {
4406            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4407            if (obj instanceof SharedUserSetting) {
4408                final SharedUserSetting sus = (SharedUserSetting) obj;
4409                return sus.pkgFlags;
4410            } else if (obj instanceof PackageSetting) {
4411                final PackageSetting ps = (PackageSetting) obj;
4412                return ps.pkgFlags;
4413            }
4414        }
4415        return 0;
4416    }
4417
4418    @Override
4419    public int getPrivateFlagsForUid(int uid) {
4420        synchronized (mPackages) {
4421            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4422            if (obj instanceof SharedUserSetting) {
4423                final SharedUserSetting sus = (SharedUserSetting) obj;
4424                return sus.pkgPrivateFlags;
4425            } else if (obj instanceof PackageSetting) {
4426                final PackageSetting ps = (PackageSetting) obj;
4427                return ps.pkgPrivateFlags;
4428            }
4429        }
4430        return 0;
4431    }
4432
4433    @Override
4434    public boolean isUidPrivileged(int uid) {
4435        uid = UserHandle.getAppId(uid);
4436        // reader
4437        synchronized (mPackages) {
4438            Object obj = mSettings.getUserIdLPr(uid);
4439            if (obj instanceof SharedUserSetting) {
4440                final SharedUserSetting sus = (SharedUserSetting) obj;
4441                final Iterator<PackageSetting> it = sus.packages.iterator();
4442                while (it.hasNext()) {
4443                    if (it.next().isPrivileged()) {
4444                        return true;
4445                    }
4446                }
4447            } else if (obj instanceof PackageSetting) {
4448                final PackageSetting ps = (PackageSetting) obj;
4449                return ps.isPrivileged();
4450            }
4451        }
4452        return false;
4453    }
4454
4455    @Override
4456    public String[] getAppOpPermissionPackages(String permissionName) {
4457        synchronized (mPackages) {
4458            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4459            if (pkgs == null) {
4460                return null;
4461            }
4462            return pkgs.toArray(new String[pkgs.size()]);
4463        }
4464    }
4465
4466    @Override
4467    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4468            int flags, int userId) {
4469        if (!sUserManager.exists(userId)) return null;
4470        flags = updateFlagsForResolve(flags, userId, intent);
4471        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4472        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4473        final ResolveInfo bestChoice =
4474                chooseBestActivity(intent, resolvedType, flags, query, userId);
4475
4476        if (isEphemeralAllowed(intent, query, userId)) {
4477            final EphemeralResolveInfo ai =
4478                    getEphemeralResolveInfo(intent, resolvedType, userId);
4479            if (ai != null) {
4480                if (DEBUG_EPHEMERAL) {
4481                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4482                }
4483                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4484                bestChoice.ephemeralResolveInfo = ai;
4485            }
4486        }
4487        return bestChoice;
4488    }
4489
4490    @Override
4491    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4492            IntentFilter filter, int match, ComponentName activity) {
4493        final int userId = UserHandle.getCallingUserId();
4494        if (DEBUG_PREFERRED) {
4495            Log.v(TAG, "setLastChosenActivity intent=" + intent
4496                + " resolvedType=" + resolvedType
4497                + " flags=" + flags
4498                + " filter=" + filter
4499                + " match=" + match
4500                + " activity=" + activity);
4501            filter.dump(new PrintStreamPrinter(System.out), "    ");
4502        }
4503        intent.setComponent(null);
4504        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4505        // Find any earlier preferred or last chosen entries and nuke them
4506        findPreferredActivity(intent, resolvedType,
4507                flags, query, 0, false, true, false, userId);
4508        // Add the new activity as the last chosen for this filter
4509        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4510                "Setting last chosen");
4511    }
4512
4513    @Override
4514    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4515        final int userId = UserHandle.getCallingUserId();
4516        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4517        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4518        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4519                false, false, false, userId);
4520    }
4521
4522
4523    private boolean isEphemeralAllowed(
4524            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4525        // Short circuit and return early if possible.
4526        if (DISABLE_EPHEMERAL_APPS) {
4527            return false;
4528        }
4529        final int callingUser = UserHandle.getCallingUserId();
4530        if (callingUser != UserHandle.USER_SYSTEM) {
4531            return false;
4532        }
4533        if (mEphemeralResolverConnection == null) {
4534            return false;
4535        }
4536        if (intent.getComponent() != null) {
4537            return false;
4538        }
4539        if (intent.getPackage() != null) {
4540            return false;
4541        }
4542        final boolean isWebUri = hasWebURI(intent);
4543        if (!isWebUri) {
4544            return false;
4545        }
4546        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4547        synchronized (mPackages) {
4548            final int count = resolvedActivites.size();
4549            for (int n = 0; n < count; n++) {
4550                ResolveInfo info = resolvedActivites.get(n);
4551                String packageName = info.activityInfo.packageName;
4552                PackageSetting ps = mSettings.mPackages.get(packageName);
4553                if (ps != null) {
4554                    // Try to get the status from User settings first
4555                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4556                    int status = (int) (packedStatus >> 32);
4557                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4558                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4559                        if (DEBUG_EPHEMERAL) {
4560                            Slog.v(TAG, "DENY ephemeral apps;"
4561                                + " pkg: " + packageName + ", status: " + status);
4562                        }
4563                        return false;
4564                    }
4565                }
4566            }
4567        }
4568        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4569        return true;
4570    }
4571
4572    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4573            int userId) {
4574        MessageDigest digest = null;
4575        try {
4576            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4577        } catch (NoSuchAlgorithmException e) {
4578            // If we can't create a digest, ignore ephemeral apps.
4579            return null;
4580        }
4581
4582        final byte[] hostBytes = intent.getData().getHost().getBytes();
4583        final byte[] digestBytes = digest.digest(hostBytes);
4584        int shaPrefix =
4585                digestBytes[0] << 24
4586                | digestBytes[1] << 16
4587                | digestBytes[2] << 8
4588                | digestBytes[3] << 0;
4589        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4590                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4591        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4592            // No hash prefix match; there are no ephemeral apps for this domain.
4593            return null;
4594        }
4595        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4596            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4597            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4598                continue;
4599            }
4600            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4601            // No filters; this should never happen.
4602            if (filters.isEmpty()) {
4603                continue;
4604            }
4605            // We have a domain match; resolve the filters to see if anything matches.
4606            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4607            for (int j = filters.size() - 1; j >= 0; --j) {
4608                final EphemeralResolveIntentInfo intentInfo =
4609                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4610                ephemeralResolver.addFilter(intentInfo);
4611            }
4612            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4613                    intent, resolvedType, false /*defaultOnly*/, userId);
4614            if (!matchedResolveInfoList.isEmpty()) {
4615                return matchedResolveInfoList.get(0);
4616            }
4617        }
4618        // Hash or filter mis-match; no ephemeral apps for this domain.
4619        return null;
4620    }
4621
4622    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4623            int flags, List<ResolveInfo> query, int userId) {
4624        if (query != null) {
4625            final int N = query.size();
4626            if (N == 1) {
4627                return query.get(0);
4628            } else if (N > 1) {
4629                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4630                // If there is more than one activity with the same priority,
4631                // then let the user decide between them.
4632                ResolveInfo r0 = query.get(0);
4633                ResolveInfo r1 = query.get(1);
4634                if (DEBUG_INTENT_MATCHING || debug) {
4635                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4636                            + r1.activityInfo.name + "=" + r1.priority);
4637                }
4638                // If the first activity has a higher priority, or a different
4639                // default, then it is always desirable to pick it.
4640                if (r0.priority != r1.priority
4641                        || r0.preferredOrder != r1.preferredOrder
4642                        || r0.isDefault != r1.isDefault) {
4643                    return query.get(0);
4644                }
4645                // If we have saved a preference for a preferred activity for
4646                // this Intent, use that.
4647                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4648                        flags, query, r0.priority, true, false, debug, userId);
4649                if (ri != null) {
4650                    return ri;
4651                }
4652                ri = new ResolveInfo(mResolveInfo);
4653                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4654                ri.activityInfo.applicationInfo = new ApplicationInfo(
4655                        ri.activityInfo.applicationInfo);
4656                if (userId != 0) {
4657                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4658                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4659                }
4660                // Make sure that the resolver is displayable in car mode
4661                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4662                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4663                return ri;
4664            }
4665        }
4666        return null;
4667    }
4668
4669    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4670            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4671        final int N = query.size();
4672        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4673                .get(userId);
4674        // Get the list of persistent preferred activities that handle the intent
4675        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4676        List<PersistentPreferredActivity> pprefs = ppir != null
4677                ? ppir.queryIntent(intent, resolvedType,
4678                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4679                : null;
4680        if (pprefs != null && pprefs.size() > 0) {
4681            final int M = pprefs.size();
4682            for (int i=0; i<M; i++) {
4683                final PersistentPreferredActivity ppa = pprefs.get(i);
4684                if (DEBUG_PREFERRED || debug) {
4685                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4686                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4687                            + "\n  component=" + ppa.mComponent);
4688                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4689                }
4690                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4691                        flags | MATCH_DISABLED_COMPONENTS, userId);
4692                if (DEBUG_PREFERRED || debug) {
4693                    Slog.v(TAG, "Found persistent preferred activity:");
4694                    if (ai != null) {
4695                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4696                    } else {
4697                        Slog.v(TAG, "  null");
4698                    }
4699                }
4700                if (ai == null) {
4701                    // This previously registered persistent preferred activity
4702                    // component is no longer known. Ignore it and do NOT remove it.
4703                    continue;
4704                }
4705                for (int j=0; j<N; j++) {
4706                    final ResolveInfo ri = query.get(j);
4707                    if (!ri.activityInfo.applicationInfo.packageName
4708                            .equals(ai.applicationInfo.packageName)) {
4709                        continue;
4710                    }
4711                    if (!ri.activityInfo.name.equals(ai.name)) {
4712                        continue;
4713                    }
4714                    //  Found a persistent preference that can handle the intent.
4715                    if (DEBUG_PREFERRED || debug) {
4716                        Slog.v(TAG, "Returning persistent preferred activity: " +
4717                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4718                    }
4719                    return ri;
4720                }
4721            }
4722        }
4723        return null;
4724    }
4725
4726    // TODO: handle preferred activities missing while user has amnesia
4727    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4728            List<ResolveInfo> query, int priority, boolean always,
4729            boolean removeMatches, boolean debug, int userId) {
4730        if (!sUserManager.exists(userId)) return null;
4731        flags = updateFlagsForResolve(flags, userId, intent);
4732        // writer
4733        synchronized (mPackages) {
4734            if (intent.getSelector() != null) {
4735                intent = intent.getSelector();
4736            }
4737            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4738
4739            // Try to find a matching persistent preferred activity.
4740            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4741                    debug, userId);
4742
4743            // If a persistent preferred activity matched, use it.
4744            if (pri != null) {
4745                return pri;
4746            }
4747
4748            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4749            // Get the list of preferred activities that handle the intent
4750            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4751            List<PreferredActivity> prefs = pir != null
4752                    ? pir.queryIntent(intent, resolvedType,
4753                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4754                    : null;
4755            if (prefs != null && prefs.size() > 0) {
4756                boolean changed = false;
4757                try {
4758                    // First figure out how good the original match set is.
4759                    // We will only allow preferred activities that came
4760                    // from the same match quality.
4761                    int match = 0;
4762
4763                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4764
4765                    final int N = query.size();
4766                    for (int j=0; j<N; j++) {
4767                        final ResolveInfo ri = query.get(j);
4768                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4769                                + ": 0x" + Integer.toHexString(match));
4770                        if (ri.match > match) {
4771                            match = ri.match;
4772                        }
4773                    }
4774
4775                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4776                            + Integer.toHexString(match));
4777
4778                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4779                    final int M = prefs.size();
4780                    for (int i=0; i<M; i++) {
4781                        final PreferredActivity pa = prefs.get(i);
4782                        if (DEBUG_PREFERRED || debug) {
4783                            Slog.v(TAG, "Checking PreferredActivity ds="
4784                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4785                                    + "\n  component=" + pa.mPref.mComponent);
4786                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4787                        }
4788                        if (pa.mPref.mMatch != match) {
4789                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4790                                    + Integer.toHexString(pa.mPref.mMatch));
4791                            continue;
4792                        }
4793                        // If it's not an "always" type preferred activity and that's what we're
4794                        // looking for, skip it.
4795                        if (always && !pa.mPref.mAlways) {
4796                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4797                            continue;
4798                        }
4799                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4800                                flags | MATCH_DISABLED_COMPONENTS, userId);
4801                        if (DEBUG_PREFERRED || debug) {
4802                            Slog.v(TAG, "Found preferred activity:");
4803                            if (ai != null) {
4804                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4805                            } else {
4806                                Slog.v(TAG, "  null");
4807                            }
4808                        }
4809                        if (ai == null) {
4810                            // This previously registered preferred activity
4811                            // component is no longer known.  Most likely an update
4812                            // to the app was installed and in the new version this
4813                            // component no longer exists.  Clean it up by removing
4814                            // it from the preferred activities list, and skip it.
4815                            Slog.w(TAG, "Removing dangling preferred activity: "
4816                                    + pa.mPref.mComponent);
4817                            pir.removeFilter(pa);
4818                            changed = true;
4819                            continue;
4820                        }
4821                        for (int j=0; j<N; j++) {
4822                            final ResolveInfo ri = query.get(j);
4823                            if (!ri.activityInfo.applicationInfo.packageName
4824                                    .equals(ai.applicationInfo.packageName)) {
4825                                continue;
4826                            }
4827                            if (!ri.activityInfo.name.equals(ai.name)) {
4828                                continue;
4829                            }
4830
4831                            if (removeMatches) {
4832                                pir.removeFilter(pa);
4833                                changed = true;
4834                                if (DEBUG_PREFERRED) {
4835                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4836                                }
4837                                break;
4838                            }
4839
4840                            // Okay we found a previously set preferred or last chosen app.
4841                            // If the result set is different from when this
4842                            // was created, we need to clear it and re-ask the
4843                            // user their preference, if we're looking for an "always" type entry.
4844                            if (always && !pa.mPref.sameSet(query)) {
4845                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4846                                        + intent + " type " + resolvedType);
4847                                if (DEBUG_PREFERRED) {
4848                                    Slog.v(TAG, "Removing preferred activity since set changed "
4849                                            + pa.mPref.mComponent);
4850                                }
4851                                pir.removeFilter(pa);
4852                                // Re-add the filter as a "last chosen" entry (!always)
4853                                PreferredActivity lastChosen = new PreferredActivity(
4854                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4855                                pir.addFilter(lastChosen);
4856                                changed = true;
4857                                return null;
4858                            }
4859
4860                            // Yay! Either the set matched or we're looking for the last chosen
4861                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4862                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4863                            return ri;
4864                        }
4865                    }
4866                } finally {
4867                    if (changed) {
4868                        if (DEBUG_PREFERRED) {
4869                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4870                        }
4871                        scheduleWritePackageRestrictionsLocked(userId);
4872                    }
4873                }
4874            }
4875        }
4876        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4877        return null;
4878    }
4879
4880    /*
4881     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4882     */
4883    @Override
4884    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4885            int targetUserId) {
4886        mContext.enforceCallingOrSelfPermission(
4887                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4888        List<CrossProfileIntentFilter> matches =
4889                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4890        if (matches != null) {
4891            int size = matches.size();
4892            for (int i = 0; i < size; i++) {
4893                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4894            }
4895        }
4896        if (hasWebURI(intent)) {
4897            // cross-profile app linking works only towards the parent.
4898            final UserInfo parent = getProfileParent(sourceUserId);
4899            synchronized(mPackages) {
4900                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4901                        intent, resolvedType, 0, sourceUserId, parent.id);
4902                return xpDomainInfo != null;
4903            }
4904        }
4905        return false;
4906    }
4907
4908    private UserInfo getProfileParent(int userId) {
4909        final long identity = Binder.clearCallingIdentity();
4910        try {
4911            return sUserManager.getProfileParent(userId);
4912        } finally {
4913            Binder.restoreCallingIdentity(identity);
4914        }
4915    }
4916
4917    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4918            String resolvedType, int userId) {
4919        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4920        if (resolver != null) {
4921            return resolver.queryIntent(intent, resolvedType, false, userId);
4922        }
4923        return null;
4924    }
4925
4926    @Override
4927    public List<ResolveInfo> queryIntentActivities(Intent intent,
4928            String resolvedType, int flags, int userId) {
4929        if (!sUserManager.exists(userId)) return Collections.emptyList();
4930        flags = updateFlagsForResolve(flags, userId, intent);
4931        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4932        ComponentName comp = intent.getComponent();
4933        if (comp == null) {
4934            if (intent.getSelector() != null) {
4935                intent = intent.getSelector();
4936                comp = intent.getComponent();
4937            }
4938        }
4939
4940        if (comp != null) {
4941            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4942            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4943            if (ai != null) {
4944                final ResolveInfo ri = new ResolveInfo();
4945                ri.activityInfo = ai;
4946                list.add(ri);
4947            }
4948            return list;
4949        }
4950
4951        // reader
4952        synchronized (mPackages) {
4953            final String pkgName = intent.getPackage();
4954            if (pkgName == null) {
4955                List<CrossProfileIntentFilter> matchingFilters =
4956                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4957                // Check for results that need to skip the current profile.
4958                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4959                        resolvedType, flags, userId);
4960                if (xpResolveInfo != null) {
4961                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4962                    result.add(xpResolveInfo);
4963                    return filterIfNotSystemUser(result, userId);
4964                }
4965
4966                // Check for results in the current profile.
4967                List<ResolveInfo> result = mActivities.queryIntent(
4968                        intent, resolvedType, flags, userId);
4969                result = filterIfNotSystemUser(result, userId);
4970
4971                // Check for cross profile results.
4972                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4973                xpResolveInfo = queryCrossProfileIntents(
4974                        matchingFilters, intent, resolvedType, flags, userId,
4975                        hasNonNegativePriorityResult);
4976                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4977                    boolean isVisibleToUser = filterIfNotSystemUser(
4978                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4979                    if (isVisibleToUser) {
4980                        result.add(xpResolveInfo);
4981                        Collections.sort(result, mResolvePrioritySorter);
4982                    }
4983                }
4984                if (hasWebURI(intent)) {
4985                    CrossProfileDomainInfo xpDomainInfo = null;
4986                    final UserInfo parent = getProfileParent(userId);
4987                    if (parent != null) {
4988                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4989                                flags, userId, parent.id);
4990                    }
4991                    if (xpDomainInfo != null) {
4992                        if (xpResolveInfo != null) {
4993                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4994                            // in the result.
4995                            result.remove(xpResolveInfo);
4996                        }
4997                        if (result.size() == 0) {
4998                            result.add(xpDomainInfo.resolveInfo);
4999                            return result;
5000                        }
5001                    } else if (result.size() <= 1) {
5002                        return result;
5003                    }
5004                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5005                            xpDomainInfo, userId);
5006                    Collections.sort(result, mResolvePrioritySorter);
5007                }
5008                return result;
5009            }
5010            final PackageParser.Package pkg = mPackages.get(pkgName);
5011            if (pkg != null) {
5012                return filterIfNotSystemUser(
5013                        mActivities.queryIntentForPackage(
5014                                intent, resolvedType, flags, pkg.activities, userId),
5015                        userId);
5016            }
5017            return new ArrayList<ResolveInfo>();
5018        }
5019    }
5020
5021    private static class CrossProfileDomainInfo {
5022        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5023        ResolveInfo resolveInfo;
5024        /* Best domain verification status of the activities found in the other profile */
5025        int bestDomainVerificationStatus;
5026    }
5027
5028    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5029            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5030        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5031                sourceUserId)) {
5032            return null;
5033        }
5034        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5035                resolvedType, flags, parentUserId);
5036
5037        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5038            return null;
5039        }
5040        CrossProfileDomainInfo result = null;
5041        int size = resultTargetUser.size();
5042        for (int i = 0; i < size; i++) {
5043            ResolveInfo riTargetUser = resultTargetUser.get(i);
5044            // Intent filter verification is only for filters that specify a host. So don't return
5045            // those that handle all web uris.
5046            if (riTargetUser.handleAllWebDataURI) {
5047                continue;
5048            }
5049            String packageName = riTargetUser.activityInfo.packageName;
5050            PackageSetting ps = mSettings.mPackages.get(packageName);
5051            if (ps == null) {
5052                continue;
5053            }
5054            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5055            int status = (int)(verificationState >> 32);
5056            if (result == null) {
5057                result = new CrossProfileDomainInfo();
5058                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5059                        sourceUserId, parentUserId);
5060                result.bestDomainVerificationStatus = status;
5061            } else {
5062                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5063                        result.bestDomainVerificationStatus);
5064            }
5065        }
5066        // Don't consider matches with status NEVER across profiles.
5067        if (result != null && result.bestDomainVerificationStatus
5068                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5069            return null;
5070        }
5071        return result;
5072    }
5073
5074    /**
5075     * Verification statuses are ordered from the worse to the best, except for
5076     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5077     */
5078    private int bestDomainVerificationStatus(int status1, int status2) {
5079        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5080            return status2;
5081        }
5082        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5083            return status1;
5084        }
5085        return (int) MathUtils.max(status1, status2);
5086    }
5087
5088    private boolean isUserEnabled(int userId) {
5089        long callingId = Binder.clearCallingIdentity();
5090        try {
5091            UserInfo userInfo = sUserManager.getUserInfo(userId);
5092            return userInfo != null && userInfo.isEnabled();
5093        } finally {
5094            Binder.restoreCallingIdentity(callingId);
5095        }
5096    }
5097
5098    /**
5099     * Filter out activities with systemUserOnly flag set, when current user is not System.
5100     *
5101     * @return filtered list
5102     */
5103    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5104        if (userId == UserHandle.USER_SYSTEM) {
5105            return resolveInfos;
5106        }
5107        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5108            ResolveInfo info = resolveInfos.get(i);
5109            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5110                resolveInfos.remove(i);
5111            }
5112        }
5113        return resolveInfos;
5114    }
5115
5116    /**
5117     * @param resolveInfos list of resolve infos in descending priority order
5118     * @return if the list contains a resolve info with non-negative priority
5119     */
5120    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5121        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5122    }
5123
5124    private static boolean hasWebURI(Intent intent) {
5125        if (intent.getData() == null) {
5126            return false;
5127        }
5128        final String scheme = intent.getScheme();
5129        if (TextUtils.isEmpty(scheme)) {
5130            return false;
5131        }
5132        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5133    }
5134
5135    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5136            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5137            int userId) {
5138        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5139
5140        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5141            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5142                    candidates.size());
5143        }
5144
5145        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5146        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5147        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5148        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5149        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5150        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5151
5152        synchronized (mPackages) {
5153            final int count = candidates.size();
5154            // First, try to use linked apps. Partition the candidates into four lists:
5155            // one for the final results, one for the "do not use ever", one for "undefined status"
5156            // and finally one for "browser app type".
5157            for (int n=0; n<count; n++) {
5158                ResolveInfo info = candidates.get(n);
5159                String packageName = info.activityInfo.packageName;
5160                PackageSetting ps = mSettings.mPackages.get(packageName);
5161                if (ps != null) {
5162                    // Add to the special match all list (Browser use case)
5163                    if (info.handleAllWebDataURI) {
5164                        matchAllList.add(info);
5165                        continue;
5166                    }
5167                    // Try to get the status from User settings first
5168                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5169                    int status = (int)(packedStatus >> 32);
5170                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5171                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5172                        if (DEBUG_DOMAIN_VERIFICATION) {
5173                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5174                                    + " : linkgen=" + linkGeneration);
5175                        }
5176                        // Use link-enabled generation as preferredOrder, i.e.
5177                        // prefer newly-enabled over earlier-enabled.
5178                        info.preferredOrder = linkGeneration;
5179                        alwaysList.add(info);
5180                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5181                        if (DEBUG_DOMAIN_VERIFICATION) {
5182                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5183                        }
5184                        neverList.add(info);
5185                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5186                        if (DEBUG_DOMAIN_VERIFICATION) {
5187                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5188                        }
5189                        alwaysAskList.add(info);
5190                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5191                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5192                        if (DEBUG_DOMAIN_VERIFICATION) {
5193                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5194                        }
5195                        undefinedList.add(info);
5196                    }
5197                }
5198            }
5199
5200            // We'll want to include browser possibilities in a few cases
5201            boolean includeBrowser = false;
5202
5203            // First try to add the "always" resolution(s) for the current user, if any
5204            if (alwaysList.size() > 0) {
5205                result.addAll(alwaysList);
5206            } else {
5207                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5208                result.addAll(undefinedList);
5209                // Maybe add one for the other profile.
5210                if (xpDomainInfo != null && (
5211                        xpDomainInfo.bestDomainVerificationStatus
5212                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5213                    result.add(xpDomainInfo.resolveInfo);
5214                }
5215                includeBrowser = true;
5216            }
5217
5218            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5219            // If there were 'always' entries their preferred order has been set, so we also
5220            // back that off to make the alternatives equivalent
5221            if (alwaysAskList.size() > 0) {
5222                for (ResolveInfo i : result) {
5223                    i.preferredOrder = 0;
5224                }
5225                result.addAll(alwaysAskList);
5226                includeBrowser = true;
5227            }
5228
5229            if (includeBrowser) {
5230                // Also add browsers (all of them or only the default one)
5231                if (DEBUG_DOMAIN_VERIFICATION) {
5232                    Slog.v(TAG, "   ...including browsers in candidate set");
5233                }
5234                if ((matchFlags & MATCH_ALL) != 0) {
5235                    result.addAll(matchAllList);
5236                } else {
5237                    // Browser/generic handling case.  If there's a default browser, go straight
5238                    // to that (but only if there is no other higher-priority match).
5239                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5240                    int maxMatchPrio = 0;
5241                    ResolveInfo defaultBrowserMatch = null;
5242                    final int numCandidates = matchAllList.size();
5243                    for (int n = 0; n < numCandidates; n++) {
5244                        ResolveInfo info = matchAllList.get(n);
5245                        // track the highest overall match priority...
5246                        if (info.priority > maxMatchPrio) {
5247                            maxMatchPrio = info.priority;
5248                        }
5249                        // ...and the highest-priority default browser match
5250                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5251                            if (defaultBrowserMatch == null
5252                                    || (defaultBrowserMatch.priority < info.priority)) {
5253                                if (debug) {
5254                                    Slog.v(TAG, "Considering default browser match " + info);
5255                                }
5256                                defaultBrowserMatch = info;
5257                            }
5258                        }
5259                    }
5260                    if (defaultBrowserMatch != null
5261                            && defaultBrowserMatch.priority >= maxMatchPrio
5262                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5263                    {
5264                        if (debug) {
5265                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5266                        }
5267                        result.add(defaultBrowserMatch);
5268                    } else {
5269                        result.addAll(matchAllList);
5270                    }
5271                }
5272
5273                // If there is nothing selected, add all candidates and remove the ones that the user
5274                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5275                if (result.size() == 0) {
5276                    result.addAll(candidates);
5277                    result.removeAll(neverList);
5278                }
5279            }
5280        }
5281        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5282            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5283                    result.size());
5284            for (ResolveInfo info : result) {
5285                Slog.v(TAG, "  + " + info.activityInfo);
5286            }
5287        }
5288        return result;
5289    }
5290
5291    // Returns a packed value as a long:
5292    //
5293    // high 'int'-sized word: link status: undefined/ask/never/always.
5294    // low 'int'-sized word: relative priority among 'always' results.
5295    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5296        long result = ps.getDomainVerificationStatusForUser(userId);
5297        // if none available, get the master status
5298        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5299            if (ps.getIntentFilterVerificationInfo() != null) {
5300                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5301            }
5302        }
5303        return result;
5304    }
5305
5306    private ResolveInfo querySkipCurrentProfileIntents(
5307            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5308            int flags, int sourceUserId) {
5309        if (matchingFilters != null) {
5310            int size = matchingFilters.size();
5311            for (int i = 0; i < size; i ++) {
5312                CrossProfileIntentFilter filter = matchingFilters.get(i);
5313                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5314                    // Checking if there are activities in the target user that can handle the
5315                    // intent.
5316                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5317                            resolvedType, flags, sourceUserId);
5318                    if (resolveInfo != null) {
5319                        return resolveInfo;
5320                    }
5321                }
5322            }
5323        }
5324        return null;
5325    }
5326
5327    // Return matching ResolveInfo in target user if any.
5328    private ResolveInfo queryCrossProfileIntents(
5329            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5330            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5331        if (matchingFilters != null) {
5332            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5333            // match the same intent. For performance reasons, it is better not to
5334            // run queryIntent twice for the same userId
5335            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5336            int size = matchingFilters.size();
5337            for (int i = 0; i < size; i++) {
5338                CrossProfileIntentFilter filter = matchingFilters.get(i);
5339                int targetUserId = filter.getTargetUserId();
5340                boolean skipCurrentProfile =
5341                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5342                boolean skipCurrentProfileIfNoMatchFound =
5343                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5344                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5345                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5346                    // Checking if there are activities in the target user that can handle the
5347                    // intent.
5348                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5349                            resolvedType, flags, sourceUserId);
5350                    if (resolveInfo != null) return resolveInfo;
5351                    alreadyTriedUserIds.put(targetUserId, true);
5352                }
5353            }
5354        }
5355        return null;
5356    }
5357
5358    /**
5359     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5360     * will forward the intent to the filter's target user.
5361     * Otherwise, returns null.
5362     */
5363    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5364            String resolvedType, int flags, int sourceUserId) {
5365        int targetUserId = filter.getTargetUserId();
5366        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5367                resolvedType, flags, targetUserId);
5368        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5369            // If all the matches in the target profile are suspended, return null.
5370            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5371                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5372                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5373                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5374                            targetUserId);
5375                }
5376            }
5377        }
5378        return null;
5379    }
5380
5381    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5382            int sourceUserId, int targetUserId) {
5383        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5384        long ident = Binder.clearCallingIdentity();
5385        boolean targetIsProfile;
5386        try {
5387            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5388        } finally {
5389            Binder.restoreCallingIdentity(ident);
5390        }
5391        String className;
5392        if (targetIsProfile) {
5393            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5394        } else {
5395            className = FORWARD_INTENT_TO_PARENT;
5396        }
5397        ComponentName forwardingActivityComponentName = new ComponentName(
5398                mAndroidApplication.packageName, className);
5399        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5400                sourceUserId);
5401        if (!targetIsProfile) {
5402            forwardingActivityInfo.showUserIcon = targetUserId;
5403            forwardingResolveInfo.noResourceId = true;
5404        }
5405        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5406        forwardingResolveInfo.priority = 0;
5407        forwardingResolveInfo.preferredOrder = 0;
5408        forwardingResolveInfo.match = 0;
5409        forwardingResolveInfo.isDefault = true;
5410        forwardingResolveInfo.filter = filter;
5411        forwardingResolveInfo.targetUserId = targetUserId;
5412        return forwardingResolveInfo;
5413    }
5414
5415    @Override
5416    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5417            Intent[] specifics, String[] specificTypes, Intent intent,
5418            String resolvedType, int flags, int userId) {
5419        if (!sUserManager.exists(userId)) return Collections.emptyList();
5420        flags = updateFlagsForResolve(flags, userId, intent);
5421        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5422                false, "query intent activity options");
5423        final String resultsAction = intent.getAction();
5424
5425        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5426                | PackageManager.GET_RESOLVED_FILTER, userId);
5427
5428        if (DEBUG_INTENT_MATCHING) {
5429            Log.v(TAG, "Query " + intent + ": " + results);
5430        }
5431
5432        int specificsPos = 0;
5433        int N;
5434
5435        // todo: note that the algorithm used here is O(N^2).  This
5436        // isn't a problem in our current environment, but if we start running
5437        // into situations where we have more than 5 or 10 matches then this
5438        // should probably be changed to something smarter...
5439
5440        // First we go through and resolve each of the specific items
5441        // that were supplied, taking care of removing any corresponding
5442        // duplicate items in the generic resolve list.
5443        if (specifics != null) {
5444            for (int i=0; i<specifics.length; i++) {
5445                final Intent sintent = specifics[i];
5446                if (sintent == null) {
5447                    continue;
5448                }
5449
5450                if (DEBUG_INTENT_MATCHING) {
5451                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5452                }
5453
5454                String action = sintent.getAction();
5455                if (resultsAction != null && resultsAction.equals(action)) {
5456                    // If this action was explicitly requested, then don't
5457                    // remove things that have it.
5458                    action = null;
5459                }
5460
5461                ResolveInfo ri = null;
5462                ActivityInfo ai = null;
5463
5464                ComponentName comp = sintent.getComponent();
5465                if (comp == null) {
5466                    ri = resolveIntent(
5467                        sintent,
5468                        specificTypes != null ? specificTypes[i] : null,
5469                            flags, userId);
5470                    if (ri == null) {
5471                        continue;
5472                    }
5473                    if (ri == mResolveInfo) {
5474                        // ACK!  Must do something better with this.
5475                    }
5476                    ai = ri.activityInfo;
5477                    comp = new ComponentName(ai.applicationInfo.packageName,
5478                            ai.name);
5479                } else {
5480                    ai = getActivityInfo(comp, flags, userId);
5481                    if (ai == null) {
5482                        continue;
5483                    }
5484                }
5485
5486                // Look for any generic query activities that are duplicates
5487                // of this specific one, and remove them from the results.
5488                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5489                N = results.size();
5490                int j;
5491                for (j=specificsPos; j<N; j++) {
5492                    ResolveInfo sri = results.get(j);
5493                    if ((sri.activityInfo.name.equals(comp.getClassName())
5494                            && sri.activityInfo.applicationInfo.packageName.equals(
5495                                    comp.getPackageName()))
5496                        || (action != null && sri.filter.matchAction(action))) {
5497                        results.remove(j);
5498                        if (DEBUG_INTENT_MATCHING) Log.v(
5499                            TAG, "Removing duplicate item from " + j
5500                            + " due to specific " + specificsPos);
5501                        if (ri == null) {
5502                            ri = sri;
5503                        }
5504                        j--;
5505                        N--;
5506                    }
5507                }
5508
5509                // Add this specific item to its proper place.
5510                if (ri == null) {
5511                    ri = new ResolveInfo();
5512                    ri.activityInfo = ai;
5513                }
5514                results.add(specificsPos, ri);
5515                ri.specificIndex = i;
5516                specificsPos++;
5517            }
5518        }
5519
5520        // Now we go through the remaining generic results and remove any
5521        // duplicate actions that are found here.
5522        N = results.size();
5523        for (int i=specificsPos; i<N-1; i++) {
5524            final ResolveInfo rii = results.get(i);
5525            if (rii.filter == null) {
5526                continue;
5527            }
5528
5529            // Iterate over all of the actions of this result's intent
5530            // filter...  typically this should be just one.
5531            final Iterator<String> it = rii.filter.actionsIterator();
5532            if (it == null) {
5533                continue;
5534            }
5535            while (it.hasNext()) {
5536                final String action = it.next();
5537                if (resultsAction != null && resultsAction.equals(action)) {
5538                    // If this action was explicitly requested, then don't
5539                    // remove things that have it.
5540                    continue;
5541                }
5542                for (int j=i+1; j<N; j++) {
5543                    final ResolveInfo rij = results.get(j);
5544                    if (rij.filter != null && rij.filter.hasAction(action)) {
5545                        results.remove(j);
5546                        if (DEBUG_INTENT_MATCHING) Log.v(
5547                            TAG, "Removing duplicate item from " + j
5548                            + " due to action " + action + " at " + i);
5549                        j--;
5550                        N--;
5551                    }
5552                }
5553            }
5554
5555            // If the caller didn't request filter information, drop it now
5556            // so we don't have to marshall/unmarshall it.
5557            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5558                rii.filter = null;
5559            }
5560        }
5561
5562        // Filter out the caller activity if so requested.
5563        if (caller != null) {
5564            N = results.size();
5565            for (int i=0; i<N; i++) {
5566                ActivityInfo ainfo = results.get(i).activityInfo;
5567                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5568                        && caller.getClassName().equals(ainfo.name)) {
5569                    results.remove(i);
5570                    break;
5571                }
5572            }
5573        }
5574
5575        // If the caller didn't request filter information,
5576        // drop them now so we don't have to
5577        // marshall/unmarshall it.
5578        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5579            N = results.size();
5580            for (int i=0; i<N; i++) {
5581                results.get(i).filter = null;
5582            }
5583        }
5584
5585        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5586        return results;
5587    }
5588
5589    @Override
5590    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5591            int userId) {
5592        if (!sUserManager.exists(userId)) return Collections.emptyList();
5593        flags = updateFlagsForResolve(flags, userId, intent);
5594        ComponentName comp = intent.getComponent();
5595        if (comp == null) {
5596            if (intent.getSelector() != null) {
5597                intent = intent.getSelector();
5598                comp = intent.getComponent();
5599            }
5600        }
5601        if (comp != null) {
5602            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5603            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5604            if (ai != null) {
5605                ResolveInfo ri = new ResolveInfo();
5606                ri.activityInfo = ai;
5607                list.add(ri);
5608            }
5609            return list;
5610        }
5611
5612        // reader
5613        synchronized (mPackages) {
5614            String pkgName = intent.getPackage();
5615            if (pkgName == null) {
5616                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5617            }
5618            final PackageParser.Package pkg = mPackages.get(pkgName);
5619            if (pkg != null) {
5620                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5621                        userId);
5622            }
5623            return null;
5624        }
5625    }
5626
5627    @Override
5628    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5629        if (!sUserManager.exists(userId)) return null;
5630        flags = updateFlagsForResolve(flags, userId, intent);
5631        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5632        if (query != null) {
5633            if (query.size() >= 1) {
5634                // If there is more than one service with the same priority,
5635                // just arbitrarily pick the first one.
5636                return query.get(0);
5637            }
5638        }
5639        return null;
5640    }
5641
5642    @Override
5643    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5644            int userId) {
5645        if (!sUserManager.exists(userId)) return Collections.emptyList();
5646        flags = updateFlagsForResolve(flags, userId, intent);
5647        ComponentName comp = intent.getComponent();
5648        if (comp == null) {
5649            if (intent.getSelector() != null) {
5650                intent = intent.getSelector();
5651                comp = intent.getComponent();
5652            }
5653        }
5654        if (comp != null) {
5655            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5656            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5657            if (si != null) {
5658                final ResolveInfo ri = new ResolveInfo();
5659                ri.serviceInfo = si;
5660                list.add(ri);
5661            }
5662            return list;
5663        }
5664
5665        // reader
5666        synchronized (mPackages) {
5667            String pkgName = intent.getPackage();
5668            if (pkgName == null) {
5669                return mServices.queryIntent(intent, resolvedType, flags, userId);
5670            }
5671            final PackageParser.Package pkg = mPackages.get(pkgName);
5672            if (pkg != null) {
5673                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5674                        userId);
5675            }
5676            return null;
5677        }
5678    }
5679
5680    @Override
5681    public List<ResolveInfo> queryIntentContentProviders(
5682            Intent intent, String resolvedType, int flags, int userId) {
5683        if (!sUserManager.exists(userId)) return Collections.emptyList();
5684        flags = updateFlagsForResolve(flags, userId, intent);
5685        ComponentName comp = intent.getComponent();
5686        if (comp == null) {
5687            if (intent.getSelector() != null) {
5688                intent = intent.getSelector();
5689                comp = intent.getComponent();
5690            }
5691        }
5692        if (comp != null) {
5693            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5694            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5695            if (pi != null) {
5696                final ResolveInfo ri = new ResolveInfo();
5697                ri.providerInfo = pi;
5698                list.add(ri);
5699            }
5700            return list;
5701        }
5702
5703        // reader
5704        synchronized (mPackages) {
5705            String pkgName = intent.getPackage();
5706            if (pkgName == null) {
5707                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5708            }
5709            final PackageParser.Package pkg = mPackages.get(pkgName);
5710            if (pkg != null) {
5711                return mProviders.queryIntentForPackage(
5712                        intent, resolvedType, flags, pkg.providers, userId);
5713            }
5714            return null;
5715        }
5716    }
5717
5718    @Override
5719    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5720        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5721        flags = updateFlagsForPackage(flags, userId, null);
5722        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5723        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5724
5725        // writer
5726        synchronized (mPackages) {
5727            ArrayList<PackageInfo> list;
5728            if (listUninstalled) {
5729                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5730                for (PackageSetting ps : mSettings.mPackages.values()) {
5731                    PackageInfo pi;
5732                    if (ps.pkg != null) {
5733                        pi = generatePackageInfo(ps.pkg, flags, userId);
5734                    } else {
5735                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5736                    }
5737                    if (pi != null) {
5738                        list.add(pi);
5739                    }
5740                }
5741            } else {
5742                list = new ArrayList<PackageInfo>(mPackages.size());
5743                for (PackageParser.Package p : mPackages.values()) {
5744                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5745                    if (pi != null) {
5746                        list.add(pi);
5747                    }
5748                }
5749            }
5750
5751            return new ParceledListSlice<PackageInfo>(list);
5752        }
5753    }
5754
5755    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5756            String[] permissions, boolean[] tmp, int flags, int userId) {
5757        int numMatch = 0;
5758        final PermissionsState permissionsState = ps.getPermissionsState();
5759        for (int i=0; i<permissions.length; i++) {
5760            final String permission = permissions[i];
5761            if (permissionsState.hasPermission(permission, userId)) {
5762                tmp[i] = true;
5763                numMatch++;
5764            } else {
5765                tmp[i] = false;
5766            }
5767        }
5768        if (numMatch == 0) {
5769            return;
5770        }
5771        PackageInfo pi;
5772        if (ps.pkg != null) {
5773            pi = generatePackageInfo(ps.pkg, flags, userId);
5774        } else {
5775            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5776        }
5777        // The above might return null in cases of uninstalled apps or install-state
5778        // skew across users/profiles.
5779        if (pi != null) {
5780            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5781                if (numMatch == permissions.length) {
5782                    pi.requestedPermissions = permissions;
5783                } else {
5784                    pi.requestedPermissions = new String[numMatch];
5785                    numMatch = 0;
5786                    for (int i=0; i<permissions.length; i++) {
5787                        if (tmp[i]) {
5788                            pi.requestedPermissions[numMatch] = permissions[i];
5789                            numMatch++;
5790                        }
5791                    }
5792                }
5793            }
5794            list.add(pi);
5795        }
5796    }
5797
5798    @Override
5799    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5800            String[] permissions, int flags, int userId) {
5801        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5802        flags = updateFlagsForPackage(flags, userId, permissions);
5803        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5804
5805        // writer
5806        synchronized (mPackages) {
5807            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5808            boolean[] tmpBools = new boolean[permissions.length];
5809            if (listUninstalled) {
5810                for (PackageSetting ps : mSettings.mPackages.values()) {
5811                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5812                }
5813            } else {
5814                for (PackageParser.Package pkg : mPackages.values()) {
5815                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5816                    if (ps != null) {
5817                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5818                                userId);
5819                    }
5820                }
5821            }
5822
5823            return new ParceledListSlice<PackageInfo>(list);
5824        }
5825    }
5826
5827    @Override
5828    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5829        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5830        flags = updateFlagsForApplication(flags, userId, null);
5831        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5832
5833        // writer
5834        synchronized (mPackages) {
5835            ArrayList<ApplicationInfo> list;
5836            if (listUninstalled) {
5837                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5838                for (PackageSetting ps : mSettings.mPackages.values()) {
5839                    ApplicationInfo ai;
5840                    if (ps.pkg != null) {
5841                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5842                                ps.readUserState(userId), userId);
5843                    } else {
5844                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5845                    }
5846                    if (ai != null) {
5847                        list.add(ai);
5848                    }
5849                }
5850            } else {
5851                list = new ArrayList<ApplicationInfo>(mPackages.size());
5852                for (PackageParser.Package p : mPackages.values()) {
5853                    if (p.mExtras != null) {
5854                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5855                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5856                        if (ai != null) {
5857                            list.add(ai);
5858                        }
5859                    }
5860                }
5861            }
5862
5863            return new ParceledListSlice<ApplicationInfo>(list);
5864        }
5865    }
5866
5867    @Override
5868    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5869        if (DISABLE_EPHEMERAL_APPS) {
5870            return null;
5871        }
5872
5873        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5874                "getEphemeralApplications");
5875        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5876                "getEphemeralApplications");
5877        synchronized (mPackages) {
5878            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5879                    .getEphemeralApplicationsLPw(userId);
5880            if (ephemeralApps != null) {
5881                return new ParceledListSlice<>(ephemeralApps);
5882            }
5883        }
5884        return null;
5885    }
5886
5887    @Override
5888    public boolean isEphemeralApplication(String packageName, int userId) {
5889        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5890                "isEphemeral");
5891        if (DISABLE_EPHEMERAL_APPS) {
5892            return false;
5893        }
5894
5895        if (!isCallerSameApp(packageName)) {
5896            return false;
5897        }
5898        synchronized (mPackages) {
5899            PackageParser.Package pkg = mPackages.get(packageName);
5900            if (pkg != null) {
5901                return pkg.applicationInfo.isEphemeralApp();
5902            }
5903        }
5904        return false;
5905    }
5906
5907    @Override
5908    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5909        if (DISABLE_EPHEMERAL_APPS) {
5910            return null;
5911        }
5912
5913        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5914                "getCookie");
5915        if (!isCallerSameApp(packageName)) {
5916            return null;
5917        }
5918        synchronized (mPackages) {
5919            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5920                    packageName, userId);
5921        }
5922    }
5923
5924    @Override
5925    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5926        if (DISABLE_EPHEMERAL_APPS) {
5927            return true;
5928        }
5929
5930        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5931                "setCookie");
5932        if (!isCallerSameApp(packageName)) {
5933            return false;
5934        }
5935        synchronized (mPackages) {
5936            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5937                    packageName, cookie, userId);
5938        }
5939    }
5940
5941    @Override
5942    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5943        if (DISABLE_EPHEMERAL_APPS) {
5944            return null;
5945        }
5946
5947        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5948                "getEphemeralApplicationIcon");
5949        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5950                "getEphemeralApplicationIcon");
5951        synchronized (mPackages) {
5952            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5953                    packageName, userId);
5954        }
5955    }
5956
5957    private boolean isCallerSameApp(String packageName) {
5958        PackageParser.Package pkg = mPackages.get(packageName);
5959        return pkg != null
5960                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5961    }
5962
5963    public List<ApplicationInfo> getPersistentApplications(int flags) {
5964        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5965
5966        // reader
5967        synchronized (mPackages) {
5968            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5969            final int userId = UserHandle.getCallingUserId();
5970            while (i.hasNext()) {
5971                final PackageParser.Package p = i.next();
5972                if (p.applicationInfo != null
5973                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5974                        && (!mSafeMode || isSystemApp(p))) {
5975                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5976                    if (ps != null) {
5977                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5978                                ps.readUserState(userId), userId);
5979                        if (ai != null) {
5980                            finalList.add(ai);
5981                        }
5982                    }
5983                }
5984            }
5985        }
5986
5987        return finalList;
5988    }
5989
5990    @Override
5991    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5992        if (!sUserManager.exists(userId)) return null;
5993        flags = updateFlagsForComponent(flags, userId, name);
5994        // reader
5995        synchronized (mPackages) {
5996            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5997            PackageSetting ps = provider != null
5998                    ? mSettings.mPackages.get(provider.owner.packageName)
5999                    : null;
6000            return ps != null
6001                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6002                    ? PackageParser.generateProviderInfo(provider, flags,
6003                            ps.readUserState(userId), userId)
6004                    : null;
6005        }
6006    }
6007
6008    /**
6009     * @deprecated
6010     */
6011    @Deprecated
6012    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6013        // reader
6014        synchronized (mPackages) {
6015            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6016                    .entrySet().iterator();
6017            final int userId = UserHandle.getCallingUserId();
6018            while (i.hasNext()) {
6019                Map.Entry<String, PackageParser.Provider> entry = i.next();
6020                PackageParser.Provider p = entry.getValue();
6021                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6022
6023                if (ps != null && p.syncable
6024                        && (!mSafeMode || (p.info.applicationInfo.flags
6025                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6026                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6027                            ps.readUserState(userId), userId);
6028                    if (info != null) {
6029                        outNames.add(entry.getKey());
6030                        outInfo.add(info);
6031                    }
6032                }
6033            }
6034        }
6035    }
6036
6037    @Override
6038    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6039            int uid, int flags) {
6040        final int userId = processName != null ? UserHandle.getUserId(uid)
6041                : UserHandle.getCallingUserId();
6042        if (!sUserManager.exists(userId)) return null;
6043        flags = updateFlagsForComponent(flags, userId, processName);
6044
6045        ArrayList<ProviderInfo> finalList = null;
6046        // reader
6047        synchronized (mPackages) {
6048            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6049            while (i.hasNext()) {
6050                final PackageParser.Provider p = i.next();
6051                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6052                if (ps != null && p.info.authority != null
6053                        && (processName == null
6054                                || (p.info.processName.equals(processName)
6055                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6056                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6057                    if (finalList == null) {
6058                        finalList = new ArrayList<ProviderInfo>(3);
6059                    }
6060                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6061                            ps.readUserState(userId), userId);
6062                    if (info != null) {
6063                        finalList.add(info);
6064                    }
6065                }
6066            }
6067        }
6068
6069        if (finalList != null) {
6070            Collections.sort(finalList, mProviderInitOrderSorter);
6071            return new ParceledListSlice<ProviderInfo>(finalList);
6072        }
6073
6074        return null;
6075    }
6076
6077    @Override
6078    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6079        // reader
6080        synchronized (mPackages) {
6081            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6082            return PackageParser.generateInstrumentationInfo(i, flags);
6083        }
6084    }
6085
6086    @Override
6087    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6088            int flags) {
6089        ArrayList<InstrumentationInfo> finalList =
6090            new ArrayList<InstrumentationInfo>();
6091
6092        // reader
6093        synchronized (mPackages) {
6094            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6095            while (i.hasNext()) {
6096                final PackageParser.Instrumentation p = i.next();
6097                if (targetPackage == null
6098                        || targetPackage.equals(p.info.targetPackage)) {
6099                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6100                            flags);
6101                    if (ii != null) {
6102                        finalList.add(ii);
6103                    }
6104                }
6105            }
6106        }
6107
6108        return finalList;
6109    }
6110
6111    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6112        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6113        if (overlays == null) {
6114            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6115            return;
6116        }
6117        for (PackageParser.Package opkg : overlays.values()) {
6118            // Not much to do if idmap fails: we already logged the error
6119            // and we certainly don't want to abort installation of pkg simply
6120            // because an overlay didn't fit properly. For these reasons,
6121            // ignore the return value of createIdmapForPackagePairLI.
6122            createIdmapForPackagePairLI(pkg, opkg);
6123        }
6124    }
6125
6126    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6127            PackageParser.Package opkg) {
6128        if (!opkg.mTrustedOverlay) {
6129            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6130                    opkg.baseCodePath + ": overlay not trusted");
6131            return false;
6132        }
6133        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6134        if (overlaySet == null) {
6135            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6136                    opkg.baseCodePath + " but target package has no known overlays");
6137            return false;
6138        }
6139        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6140        // TODO: generate idmap for split APKs
6141        try {
6142            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6143        } catch (InstallerException e) {
6144            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6145                    + opkg.baseCodePath);
6146            return false;
6147        }
6148        PackageParser.Package[] overlayArray =
6149            overlaySet.values().toArray(new PackageParser.Package[0]);
6150        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6151            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6152                return p1.mOverlayPriority - p2.mOverlayPriority;
6153            }
6154        };
6155        Arrays.sort(overlayArray, cmp);
6156
6157        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6158        int i = 0;
6159        for (PackageParser.Package p : overlayArray) {
6160            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6161        }
6162        return true;
6163    }
6164
6165    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6166        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6167        try {
6168            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6169        } finally {
6170            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6171        }
6172    }
6173
6174    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6175        final File[] files = dir.listFiles();
6176        if (ArrayUtils.isEmpty(files)) {
6177            Log.d(TAG, "No files in app dir " + dir);
6178            return;
6179        }
6180
6181        if (DEBUG_PACKAGE_SCANNING) {
6182            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6183                    + " flags=0x" + Integer.toHexString(parseFlags));
6184        }
6185
6186        for (File file : files) {
6187            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6188                    && !PackageInstallerService.isStageName(file.getName());
6189            if (!isPackage) {
6190                // Ignore entries which are not packages
6191                continue;
6192            }
6193            try {
6194                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6195                        scanFlags, currentTime, null);
6196            } catch (PackageManagerException e) {
6197                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6198
6199                // Delete invalid userdata apps
6200                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6201                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6202                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6203                    removeCodePathLI(file);
6204                }
6205            }
6206        }
6207    }
6208
6209    private static File getSettingsProblemFile() {
6210        File dataDir = Environment.getDataDirectory();
6211        File systemDir = new File(dataDir, "system");
6212        File fname = new File(systemDir, "uiderrors.txt");
6213        return fname;
6214    }
6215
6216    static void reportSettingsProblem(int priority, String msg) {
6217        logCriticalInfo(priority, msg);
6218    }
6219
6220    static void logCriticalInfo(int priority, String msg) {
6221        Slog.println(priority, TAG, msg);
6222        EventLogTags.writePmCriticalInfo(msg);
6223        try {
6224            File fname = getSettingsProblemFile();
6225            FileOutputStream out = new FileOutputStream(fname, true);
6226            PrintWriter pw = new FastPrintWriter(out);
6227            SimpleDateFormat formatter = new SimpleDateFormat();
6228            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6229            pw.println(dateString + ": " + msg);
6230            pw.close();
6231            FileUtils.setPermissions(
6232                    fname.toString(),
6233                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6234                    -1, -1);
6235        } catch (java.io.IOException e) {
6236        }
6237    }
6238
6239    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6240            PackageParser.Package pkg, File srcFile, int parseFlags)
6241            throws PackageManagerException {
6242        if (ps != null
6243                && ps.codePath.equals(srcFile)
6244                && ps.timeStamp == srcFile.lastModified()
6245                && !isCompatSignatureUpdateNeeded(pkg)
6246                && !isRecoverSignatureUpdateNeeded(pkg)) {
6247            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6248            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6249            ArraySet<PublicKey> signingKs;
6250            synchronized (mPackages) {
6251                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6252            }
6253            if (ps.signatures.mSignatures != null
6254                    && ps.signatures.mSignatures.length != 0
6255                    && signingKs != null) {
6256                // Optimization: reuse the existing cached certificates
6257                // if the package appears to be unchanged.
6258                pkg.mSignatures = ps.signatures.mSignatures;
6259                pkg.mSigningKeys = signingKs;
6260                return;
6261            }
6262
6263            Slog.w(TAG, "PackageSetting for " + ps.name
6264                    + " is missing signatures.  Collecting certs again to recover them.");
6265        } else {
6266            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6267        }
6268
6269        try {
6270            pp.collectCertificates(pkg, parseFlags);
6271        } catch (PackageParserException e) {
6272            throw PackageManagerException.from(e);
6273        }
6274    }
6275
6276    /**
6277     *  Traces a package scan.
6278     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6279     */
6280    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6281            long currentTime, UserHandle user) throws PackageManagerException {
6282        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6283        try {
6284            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6285        } finally {
6286            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6287        }
6288    }
6289
6290    /**
6291     *  Scans a package and returns the newly parsed package.
6292     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6293     */
6294    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6295            long currentTime, UserHandle user) throws PackageManagerException {
6296        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6297        parseFlags |= mDefParseFlags;
6298        PackageParser pp = new PackageParser();
6299        pp.setSeparateProcesses(mSeparateProcesses);
6300        pp.setOnlyCoreApps(mOnlyCore);
6301        pp.setDisplayMetrics(mMetrics);
6302
6303        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6304            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6305        }
6306
6307        final PackageParser.Package pkg;
6308        try {
6309            pkg = pp.parsePackage(scanFile, parseFlags);
6310        } catch (PackageParserException e) {
6311            throw PackageManagerException.from(e);
6312        }
6313
6314        PackageSetting ps = null;
6315        PackageSetting updatedPkg;
6316        // reader
6317        synchronized (mPackages) {
6318            // Look to see if we already know about this package.
6319            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6320            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6321                // This package has been renamed to its original name.  Let's
6322                // use that.
6323                ps = mSettings.peekPackageLPr(oldName);
6324            }
6325            // If there was no original package, see one for the real package name.
6326            if (ps == null) {
6327                ps = mSettings.peekPackageLPr(pkg.packageName);
6328            }
6329            // Check to see if this package could be hiding/updating a system
6330            // package.  Must look for it either under the original or real
6331            // package name depending on our state.
6332            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6333            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6334        }
6335        boolean updatedPkgBetter = false;
6336        // First check if this is a system package that may involve an update
6337        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6338            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6339            // it needs to drop FLAG_PRIVILEGED.
6340            if (locationIsPrivileged(scanFile)) {
6341                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6342            } else {
6343                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6344            }
6345
6346            if (ps != null && !ps.codePath.equals(scanFile)) {
6347                // The path has changed from what was last scanned...  check the
6348                // version of the new path against what we have stored to determine
6349                // what to do.
6350                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6351                if (pkg.mVersionCode <= ps.versionCode) {
6352                    // The system package has been updated and the code path does not match
6353                    // Ignore entry. Skip it.
6354                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6355                            + " ignored: updated version " + ps.versionCode
6356                            + " better than this " + pkg.mVersionCode);
6357                    if (!updatedPkg.codePath.equals(scanFile)) {
6358                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6359                                + ps.name + " changing from " + updatedPkg.codePathString
6360                                + " to " + scanFile);
6361                        updatedPkg.codePath = scanFile;
6362                        updatedPkg.codePathString = scanFile.toString();
6363                        updatedPkg.resourcePath = scanFile;
6364                        updatedPkg.resourcePathString = scanFile.toString();
6365                    }
6366                    updatedPkg.pkg = pkg;
6367                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6368                            "Package " + ps.name + " at " + scanFile
6369                                    + " ignored: updated version " + ps.versionCode
6370                                    + " better than this " + pkg.mVersionCode);
6371                } else {
6372                    // The current app on the system partition is better than
6373                    // what we have updated to on the data partition; switch
6374                    // back to the system partition version.
6375                    // At this point, its safely assumed that package installation for
6376                    // apps in system partition will go through. If not there won't be a working
6377                    // version of the app
6378                    // writer
6379                    synchronized (mPackages) {
6380                        // Just remove the loaded entries from package lists.
6381                        mPackages.remove(ps.name);
6382                    }
6383
6384                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6385                            + " reverting from " + ps.codePathString
6386                            + ": new version " + pkg.mVersionCode
6387                            + " better than installed " + ps.versionCode);
6388
6389                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6390                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6391                    synchronized (mInstallLock) {
6392                        args.cleanUpResourcesLI();
6393                    }
6394                    synchronized (mPackages) {
6395                        mSettings.enableSystemPackageLPw(ps.name);
6396                    }
6397                    updatedPkgBetter = true;
6398                }
6399            }
6400        }
6401
6402        if (updatedPkg != null) {
6403            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6404            // initially
6405            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6406
6407            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6408            // flag set initially
6409            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6410                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6411            }
6412        }
6413
6414        // Verify certificates against what was last scanned
6415        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6416
6417        /*
6418         * A new system app appeared, but we already had a non-system one of the
6419         * same name installed earlier.
6420         */
6421        boolean shouldHideSystemApp = false;
6422        if (updatedPkg == null && ps != null
6423                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6424            /*
6425             * Check to make sure the signatures match first. If they don't,
6426             * wipe the installed application and its data.
6427             */
6428            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6429                    != PackageManager.SIGNATURE_MATCH) {
6430                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6431                        + " signatures don't match existing userdata copy; removing");
6432                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6433                ps = null;
6434            } else {
6435                /*
6436                 * If the newly-added system app is an older version than the
6437                 * already installed version, hide it. It will be scanned later
6438                 * and re-added like an update.
6439                 */
6440                if (pkg.mVersionCode <= ps.versionCode) {
6441                    shouldHideSystemApp = true;
6442                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6443                            + " but new version " + pkg.mVersionCode + " better than installed "
6444                            + ps.versionCode + "; hiding system");
6445                } else {
6446                    /*
6447                     * The newly found system app is a newer version that the
6448                     * one previously installed. Simply remove the
6449                     * already-installed application and replace it with our own
6450                     * while keeping the application data.
6451                     */
6452                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6453                            + " reverting from " + ps.codePathString + ": new version "
6454                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6455                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6456                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6457                    synchronized (mInstallLock) {
6458                        args.cleanUpResourcesLI();
6459                    }
6460                }
6461            }
6462        }
6463
6464        // The apk is forward locked (not public) if its code and resources
6465        // are kept in different files. (except for app in either system or
6466        // vendor path).
6467        // TODO grab this value from PackageSettings
6468        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6469            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6470                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6471            }
6472        }
6473
6474        // TODO: extend to support forward-locked splits
6475        String resourcePath = null;
6476        String baseResourcePath = null;
6477        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6478            if (ps != null && ps.resourcePathString != null) {
6479                resourcePath = ps.resourcePathString;
6480                baseResourcePath = ps.resourcePathString;
6481            } else {
6482                // Should not happen at all. Just log an error.
6483                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6484            }
6485        } else {
6486            resourcePath = pkg.codePath;
6487            baseResourcePath = pkg.baseCodePath;
6488        }
6489
6490        // Set application objects path explicitly.
6491        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6492        pkg.applicationInfo.setCodePath(pkg.codePath);
6493        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6494        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6495        pkg.applicationInfo.setResourcePath(resourcePath);
6496        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6497        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6498
6499        // Note that we invoke the following method only if we are about to unpack an application
6500        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6501                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6502
6503        /*
6504         * If the system app should be overridden by a previously installed
6505         * data, hide the system app now and let the /data/app scan pick it up
6506         * again.
6507         */
6508        if (shouldHideSystemApp) {
6509            synchronized (mPackages) {
6510                mSettings.disableSystemPackageLPw(pkg.packageName);
6511            }
6512        }
6513
6514        return scannedPkg;
6515    }
6516
6517    private static String fixProcessName(String defProcessName,
6518            String processName, int uid) {
6519        if (processName == null) {
6520            return defProcessName;
6521        }
6522        return processName;
6523    }
6524
6525    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6526            throws PackageManagerException {
6527        if (pkgSetting.signatures.mSignatures != null) {
6528            // Already existing package. Make sure signatures match
6529            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6530                    == PackageManager.SIGNATURE_MATCH;
6531            if (!match) {
6532                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6533                        == PackageManager.SIGNATURE_MATCH;
6534            }
6535            if (!match) {
6536                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6537                        == PackageManager.SIGNATURE_MATCH;
6538            }
6539            if (!match) {
6540                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6541                        + pkg.packageName + " signatures do not match the "
6542                        + "previously installed version; ignoring!");
6543            }
6544        }
6545
6546        // Check for shared user signatures
6547        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6548            // Already existing package. Make sure signatures match
6549            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6550                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6551            if (!match) {
6552                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6553                        == PackageManager.SIGNATURE_MATCH;
6554            }
6555            if (!match) {
6556                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6557                        == PackageManager.SIGNATURE_MATCH;
6558            }
6559            if (!match) {
6560                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6561                        "Package " + pkg.packageName
6562                        + " has no signatures that match those in shared user "
6563                        + pkgSetting.sharedUser.name + "; ignoring!");
6564            }
6565        }
6566    }
6567
6568    /**
6569     * Enforces that only the system UID or root's UID can call a method exposed
6570     * via Binder.
6571     *
6572     * @param message used as message if SecurityException is thrown
6573     * @throws SecurityException if the caller is not system or root
6574     */
6575    private static final void enforceSystemOrRoot(String message) {
6576        final int uid = Binder.getCallingUid();
6577        if (uid != Process.SYSTEM_UID && uid != 0) {
6578            throw new SecurityException(message);
6579        }
6580    }
6581
6582    @Override
6583    public void performFstrimIfNeeded() {
6584        enforceSystemOrRoot("Only the system can request fstrim");
6585
6586        // Before everything else, see whether we need to fstrim.
6587        try {
6588            IMountService ms = PackageHelper.getMountService();
6589            if (ms != null) {
6590                final boolean isUpgrade = isUpgrade();
6591                boolean doTrim = isUpgrade;
6592                if (doTrim) {
6593                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6594                } else {
6595                    final long interval = android.provider.Settings.Global.getLong(
6596                            mContext.getContentResolver(),
6597                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6598                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6599                    if (interval > 0) {
6600                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6601                        if (timeSinceLast > interval) {
6602                            doTrim = true;
6603                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6604                                    + "; running immediately");
6605                        }
6606                    }
6607                }
6608                if (doTrim) {
6609                    if (!isFirstBoot()) {
6610                        try {
6611                            ActivityManagerNative.getDefault().showBootMessage(
6612                                    mContext.getResources().getString(
6613                                            R.string.android_upgrading_fstrim), true);
6614                        } catch (RemoteException e) {
6615                        }
6616                    }
6617                    ms.runMaintenance();
6618                }
6619            } else {
6620                Slog.e(TAG, "Mount service unavailable!");
6621            }
6622        } catch (RemoteException e) {
6623            // Can't happen; MountService is local
6624        }
6625    }
6626
6627    @Override
6628    public void extractPackagesIfNeeded() {
6629        enforceSystemOrRoot("Only the system can request package extraction");
6630
6631        // Extract pacakges only if profile-guided compilation is enabled because
6632        // otherwise BackgroundDexOptService will not dexopt them later.
6633        if (mUseJitProfiles) {
6634            ArraySet<String> pkgs = getOptimizablePackages();
6635            if (pkgs != null) {
6636                for (String pkg : pkgs) {
6637                    performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */,
6638                            true /* extractOnly */, false /* force */);
6639                }
6640            }
6641        }
6642    }
6643
6644    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6645        List<ResolveInfo> ris = null;
6646        try {
6647            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6648                    intent, null, 0, userId);
6649        } catch (RemoteException e) {
6650        }
6651        ArraySet<String> pkgNames = new ArraySet<String>();
6652        if (ris != null) {
6653            for (ResolveInfo ri : ris) {
6654                pkgNames.add(ri.activityInfo.packageName);
6655            }
6656        }
6657        return pkgNames;
6658    }
6659
6660    @Override
6661    public void notifyPackageUse(String packageName) {
6662        synchronized (mPackages) {
6663            PackageParser.Package p = mPackages.get(packageName);
6664            if (p == null) {
6665                return;
6666            }
6667            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6668        }
6669    }
6670
6671    // TODO: this is not used nor needed. Delete it.
6672    @Override
6673    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6674        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6675                false /* extractOnly */, false /* force */);
6676    }
6677
6678    @Override
6679    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6680            boolean extractOnly, boolean force) {
6681        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6682    }
6683
6684    private boolean performDexOptTraced(String packageName, String instructionSet,
6685                boolean useProfiles, boolean extractOnly, boolean force) {
6686        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6687        try {
6688            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6689                    force);
6690        } finally {
6691            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6692        }
6693    }
6694
6695    private boolean performDexOptInternal(String packageName, String instructionSet,
6696                boolean useProfiles, boolean extractOnly, boolean force) {
6697        PackageParser.Package p;
6698        final String targetInstructionSet;
6699        synchronized (mPackages) {
6700            p = mPackages.get(packageName);
6701            if (p == null) {
6702                return false;
6703            }
6704            mPackageUsage.write(false);
6705
6706            targetInstructionSet = instructionSet != null ? instructionSet :
6707                    getPrimaryInstructionSet(p.applicationInfo);
6708            if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) {
6709                // Skip only if we do not use profiles since they might trigger a recompilation.
6710                return false;
6711            }
6712        }
6713        long callingId = Binder.clearCallingIdentity();
6714        try {
6715            synchronized (mInstallLock) {
6716                final String[] instructionSets = new String[] { targetInstructionSet };
6717                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6718                        useProfiles, extractOnly, force);
6719                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6720            }
6721        } finally {
6722            Binder.restoreCallingIdentity(callingId);
6723        }
6724    }
6725
6726    public ArraySet<String> getOptimizablePackages() {
6727        ArraySet<String> pkgs = new ArraySet<String>();
6728        synchronized (mPackages) {
6729            for (PackageParser.Package p : mPackages.values()) {
6730                if (PackageDexOptimizer.canOptimizePackage(p)) {
6731                    pkgs.add(p.packageName);
6732                }
6733            }
6734        }
6735        return pkgs;
6736    }
6737
6738    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
6739            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
6740        // Select the dex optimizer based on the force parameter.
6741        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
6742        //       allocate an object here.
6743        PackageDexOptimizer pdo = force
6744                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
6745                : mPackageDexOptimizer;
6746
6747        // Optimize all dependencies first. Note: we ignore the return value and march on
6748        // on errors.
6749        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
6750        if (!deps.isEmpty()) {
6751            for (PackageParser.Package depPackage : deps) {
6752                // TODO: Analyze and investigate if we (should) profile libraries.
6753                // Currently this will do a full compilation of the library.
6754                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
6755                        false /* extractOnly */);
6756            }
6757        }
6758
6759        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
6760    }
6761
6762    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
6763        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
6764            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
6765            Set<String> collectedNames = new HashSet<>();
6766            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
6767
6768            retValue.remove(p);
6769
6770            return retValue;
6771        } else {
6772            return Collections.emptyList();
6773        }
6774    }
6775
6776    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
6777            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6778        if (!collectedNames.contains(p.packageName)) {
6779            collectedNames.add(p.packageName);
6780            collected.add(p);
6781
6782            if (p.usesLibraries != null) {
6783                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
6784            }
6785            if (p.usesOptionalLibraries != null) {
6786                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
6787                        collectedNames);
6788            }
6789        }
6790    }
6791
6792    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
6793            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
6794        for (String libName : libs) {
6795            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
6796            if (libPkg != null) {
6797                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
6798            }
6799        }
6800    }
6801
6802    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
6803        synchronized (mPackages) {
6804            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
6805            if (lib != null && lib.apk != null) {
6806                return mPackages.get(lib.apk);
6807            }
6808        }
6809        return null;
6810    }
6811
6812    public void shutdown() {
6813        mPackageUsage.write(true);
6814    }
6815
6816    @Override
6817    public void forceDexOpt(String packageName) {
6818        enforceSystemOrRoot("forceDexOpt");
6819
6820        PackageParser.Package pkg;
6821        synchronized (mPackages) {
6822            pkg = mPackages.get(packageName);
6823            if (pkg == null) {
6824                throw new IllegalArgumentException("Unknown package: " + packageName);
6825            }
6826        }
6827
6828        synchronized (mInstallLock) {
6829            final String[] instructionSets = new String[] {
6830                    getPrimaryInstructionSet(pkg.applicationInfo) };
6831
6832            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6833
6834            // Whoever is calling forceDexOpt wants a fully compiled package.
6835            // Don't use profiles since that may cause compilation to be skipped.
6836            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
6837                    false /* useProfiles */, false /* extractOnly */, true /* force */);
6838
6839            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6840            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6841                throw new IllegalStateException("Failed to dexopt: " + res);
6842            }
6843        }
6844    }
6845
6846    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6847        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6848            Slog.w(TAG, "Unable to update from " + oldPkg.name
6849                    + " to " + newPkg.packageName
6850                    + ": old package not in system partition");
6851            return false;
6852        } else if (mPackages.get(oldPkg.name) != null) {
6853            Slog.w(TAG, "Unable to update from " + oldPkg.name
6854                    + " to " + newPkg.packageName
6855                    + ": old package still exists");
6856            return false;
6857        }
6858        return true;
6859    }
6860
6861    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6862        // TODO: triage flags as part of 26466827
6863        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6864
6865        boolean res = true;
6866        final int[] users = sUserManager.getUserIds();
6867        for (int user : users) {
6868            try {
6869                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6870            } catch (InstallerException e) {
6871                Slog.w(TAG, "Failed to delete data directory", e);
6872                res = false;
6873            }
6874        }
6875        return res;
6876    }
6877
6878    void removeCodePathLI(File codePath) {
6879        if (codePath.isDirectory()) {
6880            try {
6881                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6882            } catch (InstallerException e) {
6883                Slog.w(TAG, "Failed to remove code path", e);
6884            }
6885        } else {
6886            codePath.delete();
6887        }
6888    }
6889
6890    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6891        try {
6892            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6893        } catch (InstallerException e) {
6894            Slog.w(TAG, "Failed to destroy app data", e);
6895        }
6896    }
6897
6898    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6899            int appId, String seinfo) {
6900        try {
6901            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6902        } catch (InstallerException e) {
6903            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6904        }
6905    }
6906
6907    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6908        // TODO: triage flags as part of 26466827
6909        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6910
6911        final int[] users = sUserManager.getUserIds();
6912        for (int user : users) {
6913            try {
6914                mInstaller.clearAppData(volumeUuid, packageName, user,
6915                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6916            } catch (InstallerException e) {
6917                Slog.w(TAG, "Failed to delete code cache directory", e);
6918            }
6919        }
6920    }
6921
6922    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6923            PackageParser.Package changingLib) {
6924        if (file.path != null) {
6925            usesLibraryFiles.add(file.path);
6926            return;
6927        }
6928        PackageParser.Package p = mPackages.get(file.apk);
6929        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6930            // If we are doing this while in the middle of updating a library apk,
6931            // then we need to make sure to use that new apk for determining the
6932            // dependencies here.  (We haven't yet finished committing the new apk
6933            // to the package manager state.)
6934            if (p == null || p.packageName.equals(changingLib.packageName)) {
6935                p = changingLib;
6936            }
6937        }
6938        if (p != null) {
6939            usesLibraryFiles.addAll(p.getAllCodePaths());
6940        }
6941    }
6942
6943    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6944            PackageParser.Package changingLib) throws PackageManagerException {
6945        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6946            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6947            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6948            for (int i=0; i<N; i++) {
6949                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6950                if (file == null) {
6951                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6952                            "Package " + pkg.packageName + " requires unavailable shared library "
6953                            + pkg.usesLibraries.get(i) + "; failing!");
6954                }
6955                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6956            }
6957            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6958            for (int i=0; i<N; i++) {
6959                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6960                if (file == null) {
6961                    Slog.w(TAG, "Package " + pkg.packageName
6962                            + " desires unavailable shared library "
6963                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6964                } else {
6965                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6966                }
6967            }
6968            N = usesLibraryFiles.size();
6969            if (N > 0) {
6970                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6971            } else {
6972                pkg.usesLibraryFiles = null;
6973            }
6974        }
6975    }
6976
6977    private static boolean hasString(List<String> list, List<String> which) {
6978        if (list == null) {
6979            return false;
6980        }
6981        for (int i=list.size()-1; i>=0; i--) {
6982            for (int j=which.size()-1; j>=0; j--) {
6983                if (which.get(j).equals(list.get(i))) {
6984                    return true;
6985                }
6986            }
6987        }
6988        return false;
6989    }
6990
6991    private void updateAllSharedLibrariesLPw() {
6992        for (PackageParser.Package pkg : mPackages.values()) {
6993            try {
6994                updateSharedLibrariesLPw(pkg, null);
6995            } catch (PackageManagerException e) {
6996                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6997            }
6998        }
6999    }
7000
7001    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7002            PackageParser.Package changingPkg) {
7003        ArrayList<PackageParser.Package> res = null;
7004        for (PackageParser.Package pkg : mPackages.values()) {
7005            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7006                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7007                if (res == null) {
7008                    res = new ArrayList<PackageParser.Package>();
7009                }
7010                res.add(pkg);
7011                try {
7012                    updateSharedLibrariesLPw(pkg, changingPkg);
7013                } catch (PackageManagerException e) {
7014                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7015                }
7016            }
7017        }
7018        return res;
7019    }
7020
7021    /**
7022     * Derive the value of the {@code cpuAbiOverride} based on the provided
7023     * value and an optional stored value from the package settings.
7024     */
7025    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7026        String cpuAbiOverride = null;
7027
7028        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7029            cpuAbiOverride = null;
7030        } else if (abiOverride != null) {
7031            cpuAbiOverride = abiOverride;
7032        } else if (settings != null) {
7033            cpuAbiOverride = settings.cpuAbiOverrideString;
7034        }
7035
7036        return cpuAbiOverride;
7037    }
7038
7039    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7040            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7041        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7042        try {
7043            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7044        } finally {
7045            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7046        }
7047    }
7048
7049    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7050            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7051        boolean success = false;
7052        try {
7053            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7054                    currentTime, user);
7055            success = true;
7056            return res;
7057        } finally {
7058            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7059                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7060            }
7061        }
7062    }
7063
7064    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7065            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7066        final File scanFile = new File(pkg.codePath);
7067        if (pkg.applicationInfo.getCodePath() == null ||
7068                pkg.applicationInfo.getResourcePath() == null) {
7069            // Bail out. The resource and code paths haven't been set.
7070            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7071                    "Code and resource paths haven't been set correctly");
7072        }
7073
7074        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7075            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7076        } else {
7077            // Only allow system apps to be flagged as core apps.
7078            pkg.coreApp = false;
7079        }
7080
7081        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7082            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7083        }
7084
7085        if (mCustomResolverComponentName != null &&
7086                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7087            setUpCustomResolverActivity(pkg);
7088        }
7089
7090        if (pkg.packageName.equals("android")) {
7091            synchronized (mPackages) {
7092                if (mAndroidApplication != null) {
7093                    Slog.w(TAG, "*************************************************");
7094                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7095                    Slog.w(TAG, " file=" + scanFile);
7096                    Slog.w(TAG, "*************************************************");
7097                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7098                            "Core android package being redefined.  Skipping.");
7099                }
7100
7101                // Set up information for our fall-back user intent resolution activity.
7102                mPlatformPackage = pkg;
7103                pkg.mVersionCode = mSdkVersion;
7104                mAndroidApplication = pkg.applicationInfo;
7105
7106                if (!mResolverReplaced) {
7107                    mResolveActivity.applicationInfo = mAndroidApplication;
7108                    mResolveActivity.name = ResolverActivity.class.getName();
7109                    mResolveActivity.packageName = mAndroidApplication.packageName;
7110                    mResolveActivity.processName = "system:ui";
7111                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7112                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7113                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7114                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7115                    mResolveActivity.exported = true;
7116                    mResolveActivity.enabled = true;
7117                    mResolveInfo.activityInfo = mResolveActivity;
7118                    mResolveInfo.priority = 0;
7119                    mResolveInfo.preferredOrder = 0;
7120                    mResolveInfo.match = 0;
7121                    mResolveComponentName = new ComponentName(
7122                            mAndroidApplication.packageName, mResolveActivity.name);
7123                }
7124            }
7125        }
7126
7127        if (DEBUG_PACKAGE_SCANNING) {
7128            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7129                Log.d(TAG, "Scanning package " + pkg.packageName);
7130        }
7131
7132        if (mPackages.containsKey(pkg.packageName)
7133                || mSharedLibraries.containsKey(pkg.packageName)) {
7134            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7135                    "Application package " + pkg.packageName
7136                    + " already installed.  Skipping duplicate.");
7137        }
7138
7139        // If we're only installing presumed-existing packages, require that the
7140        // scanned APK is both already known and at the path previously established
7141        // for it.  Previously unknown packages we pick up normally, but if we have an
7142        // a priori expectation about this package's install presence, enforce it.
7143        // With a singular exception for new system packages. When an OTA contains
7144        // a new system package, we allow the codepath to change from a system location
7145        // to the user-installed location. If we don't allow this change, any newer,
7146        // user-installed version of the application will be ignored.
7147        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7148            if (mExpectingBetter.containsKey(pkg.packageName)) {
7149                logCriticalInfo(Log.WARN,
7150                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7151            } else {
7152                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7153                if (known != null) {
7154                    if (DEBUG_PACKAGE_SCANNING) {
7155                        Log.d(TAG, "Examining " + pkg.codePath
7156                                + " and requiring known paths " + known.codePathString
7157                                + " & " + known.resourcePathString);
7158                    }
7159                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7160                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7161                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7162                                "Application package " + pkg.packageName
7163                                + " found at " + pkg.applicationInfo.getCodePath()
7164                                + " but expected at " + known.codePathString + "; ignoring.");
7165                    }
7166                }
7167            }
7168        }
7169
7170        // Initialize package source and resource directories
7171        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7172        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7173
7174        SharedUserSetting suid = null;
7175        PackageSetting pkgSetting = null;
7176
7177        if (!isSystemApp(pkg)) {
7178            // Only system apps can use these features.
7179            pkg.mOriginalPackages = null;
7180            pkg.mRealPackage = null;
7181            pkg.mAdoptPermissions = null;
7182        }
7183
7184        // writer
7185        synchronized (mPackages) {
7186            if (pkg.mSharedUserId != null) {
7187                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7188                if (suid == null) {
7189                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7190                            "Creating application package " + pkg.packageName
7191                            + " for shared user failed");
7192                }
7193                if (DEBUG_PACKAGE_SCANNING) {
7194                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7195                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7196                                + "): packages=" + suid.packages);
7197                }
7198            }
7199
7200            // Check if we are renaming from an original package name.
7201            PackageSetting origPackage = null;
7202            String realName = null;
7203            if (pkg.mOriginalPackages != null) {
7204                // This package may need to be renamed to a previously
7205                // installed name.  Let's check on that...
7206                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7207                if (pkg.mOriginalPackages.contains(renamed)) {
7208                    // This package had originally been installed as the
7209                    // original name, and we have already taken care of
7210                    // transitioning to the new one.  Just update the new
7211                    // one to continue using the old name.
7212                    realName = pkg.mRealPackage;
7213                    if (!pkg.packageName.equals(renamed)) {
7214                        // Callers into this function may have already taken
7215                        // care of renaming the package; only do it here if
7216                        // it is not already done.
7217                        pkg.setPackageName(renamed);
7218                    }
7219
7220                } else {
7221                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7222                        if ((origPackage = mSettings.peekPackageLPr(
7223                                pkg.mOriginalPackages.get(i))) != null) {
7224                            // We do have the package already installed under its
7225                            // original name...  should we use it?
7226                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7227                                // New package is not compatible with original.
7228                                origPackage = null;
7229                                continue;
7230                            } else if (origPackage.sharedUser != null) {
7231                                // Make sure uid is compatible between packages.
7232                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7233                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7234                                            + " to " + pkg.packageName + ": old uid "
7235                                            + origPackage.sharedUser.name
7236                                            + " differs from " + pkg.mSharedUserId);
7237                                    origPackage = null;
7238                                    continue;
7239                                }
7240                            } else {
7241                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7242                                        + pkg.packageName + " to old name " + origPackage.name);
7243                            }
7244                            break;
7245                        }
7246                    }
7247                }
7248            }
7249
7250            if (mTransferedPackages.contains(pkg.packageName)) {
7251                Slog.w(TAG, "Package " + pkg.packageName
7252                        + " was transferred to another, but its .apk remains");
7253            }
7254
7255            // Just create the setting, don't add it yet. For already existing packages
7256            // the PkgSetting exists already and doesn't have to be created.
7257            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7258                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7259                    pkg.applicationInfo.primaryCpuAbi,
7260                    pkg.applicationInfo.secondaryCpuAbi,
7261                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7262                    user, false);
7263            if (pkgSetting == null) {
7264                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7265                        "Creating application package " + pkg.packageName + " failed");
7266            }
7267
7268            if (pkgSetting.origPackage != null) {
7269                // If we are first transitioning from an original package,
7270                // fix up the new package's name now.  We need to do this after
7271                // looking up the package under its new name, so getPackageLP
7272                // can take care of fiddling things correctly.
7273                pkg.setPackageName(origPackage.name);
7274
7275                // File a report about this.
7276                String msg = "New package " + pkgSetting.realName
7277                        + " renamed to replace old package " + pkgSetting.name;
7278                reportSettingsProblem(Log.WARN, msg);
7279
7280                // Make a note of it.
7281                mTransferedPackages.add(origPackage.name);
7282
7283                // No longer need to retain this.
7284                pkgSetting.origPackage = null;
7285            }
7286
7287            if (realName != null) {
7288                // Make a note of it.
7289                mTransferedPackages.add(pkg.packageName);
7290            }
7291
7292            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7293                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7294            }
7295
7296            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7297                // Check all shared libraries and map to their actual file path.
7298                // We only do this here for apps not on a system dir, because those
7299                // are the only ones that can fail an install due to this.  We
7300                // will take care of the system apps by updating all of their
7301                // library paths after the scan is done.
7302                updateSharedLibrariesLPw(pkg, null);
7303            }
7304
7305            if (mFoundPolicyFile) {
7306                SELinuxMMAC.assignSeinfoValue(pkg);
7307            }
7308
7309            pkg.applicationInfo.uid = pkgSetting.appId;
7310            pkg.mExtras = pkgSetting;
7311            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7312                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7313                    // We just determined the app is signed correctly, so bring
7314                    // over the latest parsed certs.
7315                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7316                } else {
7317                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7318                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7319                                "Package " + pkg.packageName + " upgrade keys do not match the "
7320                                + "previously installed version");
7321                    } else {
7322                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7323                        String msg = "System package " + pkg.packageName
7324                            + " signature changed; retaining data.";
7325                        reportSettingsProblem(Log.WARN, msg);
7326                    }
7327                }
7328            } else {
7329                try {
7330                    verifySignaturesLP(pkgSetting, pkg);
7331                    // We just determined the app is signed correctly, so bring
7332                    // over the latest parsed certs.
7333                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7334                } catch (PackageManagerException e) {
7335                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7336                        throw e;
7337                    }
7338                    // The signature has changed, but this package is in the system
7339                    // image...  let's recover!
7340                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7341                    // However...  if this package is part of a shared user, but it
7342                    // doesn't match the signature of the shared user, let's fail.
7343                    // What this means is that you can't change the signatures
7344                    // associated with an overall shared user, which doesn't seem all
7345                    // that unreasonable.
7346                    if (pkgSetting.sharedUser != null) {
7347                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7348                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7349                            throw new PackageManagerException(
7350                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7351                                            "Signature mismatch for shared user: "
7352                                            + pkgSetting.sharedUser);
7353                        }
7354                    }
7355                    // File a report about this.
7356                    String msg = "System package " + pkg.packageName
7357                        + " signature changed; retaining data.";
7358                    reportSettingsProblem(Log.WARN, msg);
7359                }
7360            }
7361            // Verify that this new package doesn't have any content providers
7362            // that conflict with existing packages.  Only do this if the
7363            // package isn't already installed, since we don't want to break
7364            // things that are installed.
7365            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7366                final int N = pkg.providers.size();
7367                int i;
7368                for (i=0; i<N; i++) {
7369                    PackageParser.Provider p = pkg.providers.get(i);
7370                    if (p.info.authority != null) {
7371                        String names[] = p.info.authority.split(";");
7372                        for (int j = 0; j < names.length; j++) {
7373                            if (mProvidersByAuthority.containsKey(names[j])) {
7374                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7375                                final String otherPackageName =
7376                                        ((other != null && other.getComponentName() != null) ?
7377                                                other.getComponentName().getPackageName() : "?");
7378                                throw new PackageManagerException(
7379                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7380                                                "Can't install because provider name " + names[j]
7381                                                + " (in package " + pkg.applicationInfo.packageName
7382                                                + ") is already used by " + otherPackageName);
7383                            }
7384                        }
7385                    }
7386                }
7387            }
7388
7389            if (pkg.mAdoptPermissions != null) {
7390                // This package wants to adopt ownership of permissions from
7391                // another package.
7392                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7393                    final String origName = pkg.mAdoptPermissions.get(i);
7394                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7395                    if (orig != null) {
7396                        if (verifyPackageUpdateLPr(orig, pkg)) {
7397                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7398                                    + pkg.packageName);
7399                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7400                        }
7401                    }
7402                }
7403            }
7404        }
7405
7406        final String pkgName = pkg.packageName;
7407
7408        final long scanFileTime = scanFile.lastModified();
7409        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7410        pkg.applicationInfo.processName = fixProcessName(
7411                pkg.applicationInfo.packageName,
7412                pkg.applicationInfo.processName,
7413                pkg.applicationInfo.uid);
7414
7415        if (pkg != mPlatformPackage) {
7416            // Get all of our default paths setup
7417            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7418        }
7419
7420        final String path = scanFile.getPath();
7421        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7422
7423        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7424            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7425
7426            // Some system apps still use directory structure for native libraries
7427            // in which case we might end up not detecting abi solely based on apk
7428            // structure. Try to detect abi based on directory structure.
7429            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7430                    pkg.applicationInfo.primaryCpuAbi == null) {
7431                setBundledAppAbisAndRoots(pkg, pkgSetting);
7432                setNativeLibraryPaths(pkg);
7433            }
7434
7435        } else {
7436            if ((scanFlags & SCAN_MOVE) != 0) {
7437                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7438                // but we already have this packages package info in the PackageSetting. We just
7439                // use that and derive the native library path based on the new codepath.
7440                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7441                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7442            }
7443
7444            // Set native library paths again. For moves, the path will be updated based on the
7445            // ABIs we've determined above. For non-moves, the path will be updated based on the
7446            // ABIs we determined during compilation, but the path will depend on the final
7447            // package path (after the rename away from the stage path).
7448            setNativeLibraryPaths(pkg);
7449        }
7450
7451        // This is a special case for the "system" package, where the ABI is
7452        // dictated by the zygote configuration (and init.rc). We should keep track
7453        // of this ABI so that we can deal with "normal" applications that run under
7454        // the same UID correctly.
7455        if (mPlatformPackage == pkg) {
7456            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7457                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7458        }
7459
7460        // If there's a mismatch between the abi-override in the package setting
7461        // and the abiOverride specified for the install. Warn about this because we
7462        // would've already compiled the app without taking the package setting into
7463        // account.
7464        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7465            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7466                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7467                        " for package " + pkg.packageName);
7468            }
7469        }
7470
7471        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7472        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7473        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7474
7475        // Copy the derived override back to the parsed package, so that we can
7476        // update the package settings accordingly.
7477        pkg.cpuAbiOverride = cpuAbiOverride;
7478
7479        if (DEBUG_ABI_SELECTION) {
7480            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7481                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7482                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7483        }
7484
7485        // Push the derived path down into PackageSettings so we know what to
7486        // clean up at uninstall time.
7487        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7488
7489        if (DEBUG_ABI_SELECTION) {
7490            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7491                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7492                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7493        }
7494
7495        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7496            // We don't do this here during boot because we can do it all
7497            // at once after scanning all existing packages.
7498            //
7499            // We also do this *before* we perform dexopt on this package, so that
7500            // we can avoid redundant dexopts, and also to make sure we've got the
7501            // code and package path correct.
7502            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7503                    pkg, true /* boot complete */);
7504        }
7505
7506        if (mFactoryTest && pkg.requestedPermissions.contains(
7507                android.Manifest.permission.FACTORY_TEST)) {
7508            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7509        }
7510
7511        ArrayList<PackageParser.Package> clientLibPkgs = null;
7512
7513        // writer
7514        synchronized (mPackages) {
7515            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7516                // Only system apps can add new shared libraries.
7517                if (pkg.libraryNames != null) {
7518                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7519                        String name = pkg.libraryNames.get(i);
7520                        boolean allowed = false;
7521                        if (pkg.isUpdatedSystemApp()) {
7522                            // New library entries can only be added through the
7523                            // system image.  This is important to get rid of a lot
7524                            // of nasty edge cases: for example if we allowed a non-
7525                            // system update of the app to add a library, then uninstalling
7526                            // the update would make the library go away, and assumptions
7527                            // we made such as through app install filtering would now
7528                            // have allowed apps on the device which aren't compatible
7529                            // with it.  Better to just have the restriction here, be
7530                            // conservative, and create many fewer cases that can negatively
7531                            // impact the user experience.
7532                            final PackageSetting sysPs = mSettings
7533                                    .getDisabledSystemPkgLPr(pkg.packageName);
7534                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7535                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7536                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7537                                        allowed = true;
7538                                        break;
7539                                    }
7540                                }
7541                            }
7542                        } else {
7543                            allowed = true;
7544                        }
7545                        if (allowed) {
7546                            if (!mSharedLibraries.containsKey(name)) {
7547                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7548                            } else if (!name.equals(pkg.packageName)) {
7549                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7550                                        + name + " already exists; skipping");
7551                            }
7552                        } else {
7553                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7554                                    + name + " that is not declared on system image; skipping");
7555                        }
7556                    }
7557                    if ((scanFlags & SCAN_BOOTING) == 0) {
7558                        // If we are not booting, we need to update any applications
7559                        // that are clients of our shared library.  If we are booting,
7560                        // this will all be done once the scan is complete.
7561                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7562                    }
7563                }
7564            }
7565        }
7566
7567        // Request the ActivityManager to kill the process(only for existing packages)
7568        // so that we do not end up in a confused state while the user is still using the older
7569        // version of the application while the new one gets installed.
7570        if ((scanFlags & SCAN_REPLACING) != 0) {
7571            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7572
7573            killApplication(pkg.applicationInfo.packageName,
7574                        pkg.applicationInfo.uid, "replace pkg");
7575
7576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7577        }
7578
7579        // Also need to kill any apps that are dependent on the library.
7580        if (clientLibPkgs != null) {
7581            for (int i=0; i<clientLibPkgs.size(); i++) {
7582                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7583                killApplication(clientPkg.applicationInfo.packageName,
7584                        clientPkg.applicationInfo.uid, "update lib");
7585            }
7586        }
7587
7588        // Make sure we're not adding any bogus keyset info
7589        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7590        ksms.assertScannedPackageValid(pkg);
7591
7592        // writer
7593        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7594
7595        boolean createIdmapFailed = false;
7596        synchronized (mPackages) {
7597            // We don't expect installation to fail beyond this point
7598
7599            // Add the new setting to mSettings
7600            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7601            // Add the new setting to mPackages
7602            mPackages.put(pkg.applicationInfo.packageName, pkg);
7603            // Make sure we don't accidentally delete its data.
7604            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7605            while (iter.hasNext()) {
7606                PackageCleanItem item = iter.next();
7607                if (pkgName.equals(item.packageName)) {
7608                    iter.remove();
7609                }
7610            }
7611
7612            // Take care of first install / last update times.
7613            if (currentTime != 0) {
7614                if (pkgSetting.firstInstallTime == 0) {
7615                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7616                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7617                    pkgSetting.lastUpdateTime = currentTime;
7618                }
7619            } else if (pkgSetting.firstInstallTime == 0) {
7620                // We need *something*.  Take time time stamp of the file.
7621                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7622            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7623                if (scanFileTime != pkgSetting.timeStamp) {
7624                    // A package on the system image has changed; consider this
7625                    // to be an update.
7626                    pkgSetting.lastUpdateTime = scanFileTime;
7627                }
7628            }
7629
7630            // Add the package's KeySets to the global KeySetManagerService
7631            ksms.addScannedPackageLPw(pkg);
7632
7633            int N = pkg.providers.size();
7634            StringBuilder r = null;
7635            int i;
7636            for (i=0; i<N; i++) {
7637                PackageParser.Provider p = pkg.providers.get(i);
7638                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7639                        p.info.processName, pkg.applicationInfo.uid);
7640                mProviders.addProvider(p);
7641                p.syncable = p.info.isSyncable;
7642                if (p.info.authority != null) {
7643                    String names[] = p.info.authority.split(";");
7644                    p.info.authority = null;
7645                    for (int j = 0; j < names.length; j++) {
7646                        if (j == 1 && p.syncable) {
7647                            // We only want the first authority for a provider to possibly be
7648                            // syncable, so if we already added this provider using a different
7649                            // authority clear the syncable flag. We copy the provider before
7650                            // changing it because the mProviders object contains a reference
7651                            // to a provider that we don't want to change.
7652                            // Only do this for the second authority since the resulting provider
7653                            // object can be the same for all future authorities for this provider.
7654                            p = new PackageParser.Provider(p);
7655                            p.syncable = false;
7656                        }
7657                        if (!mProvidersByAuthority.containsKey(names[j])) {
7658                            mProvidersByAuthority.put(names[j], p);
7659                            if (p.info.authority == null) {
7660                                p.info.authority = names[j];
7661                            } else {
7662                                p.info.authority = p.info.authority + ";" + names[j];
7663                            }
7664                            if (DEBUG_PACKAGE_SCANNING) {
7665                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7666                                    Log.d(TAG, "Registered content provider: " + names[j]
7667                                            + ", className = " + p.info.name + ", isSyncable = "
7668                                            + p.info.isSyncable);
7669                            }
7670                        } else {
7671                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7672                            Slog.w(TAG, "Skipping provider name " + names[j] +
7673                                    " (in package " + pkg.applicationInfo.packageName +
7674                                    "): name already used by "
7675                                    + ((other != null && other.getComponentName() != null)
7676                                            ? other.getComponentName().getPackageName() : "?"));
7677                        }
7678                    }
7679                }
7680                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7681                    if (r == null) {
7682                        r = new StringBuilder(256);
7683                    } else {
7684                        r.append(' ');
7685                    }
7686                    r.append(p.info.name);
7687                }
7688            }
7689            if (r != null) {
7690                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7691            }
7692
7693            N = pkg.services.size();
7694            r = null;
7695            for (i=0; i<N; i++) {
7696                PackageParser.Service s = pkg.services.get(i);
7697                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7698                        s.info.processName, pkg.applicationInfo.uid);
7699                mServices.addService(s);
7700                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7701                    if (r == null) {
7702                        r = new StringBuilder(256);
7703                    } else {
7704                        r.append(' ');
7705                    }
7706                    r.append(s.info.name);
7707                }
7708            }
7709            if (r != null) {
7710                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7711            }
7712
7713            N = pkg.receivers.size();
7714            r = null;
7715            for (i=0; i<N; i++) {
7716                PackageParser.Activity a = pkg.receivers.get(i);
7717                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7718                        a.info.processName, pkg.applicationInfo.uid);
7719                mReceivers.addActivity(a, "receiver");
7720                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7721                    if (r == null) {
7722                        r = new StringBuilder(256);
7723                    } else {
7724                        r.append(' ');
7725                    }
7726                    r.append(a.info.name);
7727                }
7728            }
7729            if (r != null) {
7730                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7731            }
7732
7733            N = pkg.activities.size();
7734            r = null;
7735            for (i=0; i<N; i++) {
7736                PackageParser.Activity a = pkg.activities.get(i);
7737                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7738                        a.info.processName, pkg.applicationInfo.uid);
7739                mActivities.addActivity(a, "activity");
7740                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7741                    if (r == null) {
7742                        r = new StringBuilder(256);
7743                    } else {
7744                        r.append(' ');
7745                    }
7746                    r.append(a.info.name);
7747                }
7748            }
7749            if (r != null) {
7750                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7751            }
7752
7753            N = pkg.permissionGroups.size();
7754            r = null;
7755            for (i=0; i<N; i++) {
7756                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7757                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7758                if (cur == null) {
7759                    mPermissionGroups.put(pg.info.name, pg);
7760                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7761                        if (r == null) {
7762                            r = new StringBuilder(256);
7763                        } else {
7764                            r.append(' ');
7765                        }
7766                        r.append(pg.info.name);
7767                    }
7768                } else {
7769                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7770                            + pg.info.packageName + " ignored: original from "
7771                            + cur.info.packageName);
7772                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7773                        if (r == null) {
7774                            r = new StringBuilder(256);
7775                        } else {
7776                            r.append(' ');
7777                        }
7778                        r.append("DUP:");
7779                        r.append(pg.info.name);
7780                    }
7781                }
7782            }
7783            if (r != null) {
7784                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7785            }
7786
7787            N = pkg.permissions.size();
7788            r = null;
7789            for (i=0; i<N; i++) {
7790                PackageParser.Permission p = pkg.permissions.get(i);
7791
7792                // Assume by default that we did not install this permission into the system.
7793                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7794
7795                // Now that permission groups have a special meaning, we ignore permission
7796                // groups for legacy apps to prevent unexpected behavior. In particular,
7797                // permissions for one app being granted to someone just becuase they happen
7798                // to be in a group defined by another app (before this had no implications).
7799                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7800                    p.group = mPermissionGroups.get(p.info.group);
7801                    // Warn for a permission in an unknown group.
7802                    if (p.info.group != null && p.group == null) {
7803                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7804                                + p.info.packageName + " in an unknown group " + p.info.group);
7805                    }
7806                }
7807
7808                ArrayMap<String, BasePermission> permissionMap =
7809                        p.tree ? mSettings.mPermissionTrees
7810                                : mSettings.mPermissions;
7811                BasePermission bp = permissionMap.get(p.info.name);
7812
7813                // Allow system apps to redefine non-system permissions
7814                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7815                    final boolean currentOwnerIsSystem = (bp.perm != null
7816                            && isSystemApp(bp.perm.owner));
7817                    if (isSystemApp(p.owner)) {
7818                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7819                            // It's a built-in permission and no owner, take ownership now
7820                            bp.packageSetting = pkgSetting;
7821                            bp.perm = p;
7822                            bp.uid = pkg.applicationInfo.uid;
7823                            bp.sourcePackage = p.info.packageName;
7824                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7825                        } else if (!currentOwnerIsSystem) {
7826                            String msg = "New decl " + p.owner + " of permission  "
7827                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7828                            reportSettingsProblem(Log.WARN, msg);
7829                            bp = null;
7830                        }
7831                    }
7832                }
7833
7834                if (bp == null) {
7835                    bp = new BasePermission(p.info.name, p.info.packageName,
7836                            BasePermission.TYPE_NORMAL);
7837                    permissionMap.put(p.info.name, bp);
7838                }
7839
7840                if (bp.perm == null) {
7841                    if (bp.sourcePackage == null
7842                            || bp.sourcePackage.equals(p.info.packageName)) {
7843                        BasePermission tree = findPermissionTreeLP(p.info.name);
7844                        if (tree == null
7845                                || tree.sourcePackage.equals(p.info.packageName)) {
7846                            bp.packageSetting = pkgSetting;
7847                            bp.perm = p;
7848                            bp.uid = pkg.applicationInfo.uid;
7849                            bp.sourcePackage = p.info.packageName;
7850                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7851                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7852                                if (r == null) {
7853                                    r = new StringBuilder(256);
7854                                } else {
7855                                    r.append(' ');
7856                                }
7857                                r.append(p.info.name);
7858                            }
7859                        } else {
7860                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7861                                    + p.info.packageName + " ignored: base tree "
7862                                    + tree.name + " is from package "
7863                                    + tree.sourcePackage);
7864                        }
7865                    } else {
7866                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7867                                + p.info.packageName + " ignored: original from "
7868                                + bp.sourcePackage);
7869                    }
7870                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7871                    if (r == null) {
7872                        r = new StringBuilder(256);
7873                    } else {
7874                        r.append(' ');
7875                    }
7876                    r.append("DUP:");
7877                    r.append(p.info.name);
7878                }
7879                if (bp.perm == p) {
7880                    bp.protectionLevel = p.info.protectionLevel;
7881                }
7882            }
7883
7884            if (r != null) {
7885                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7886            }
7887
7888            N = pkg.instrumentation.size();
7889            r = null;
7890            for (i=0; i<N; i++) {
7891                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7892                a.info.packageName = pkg.applicationInfo.packageName;
7893                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7894                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7895                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7896                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7897                a.info.dataDir = pkg.applicationInfo.dataDir;
7898                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7899                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7900
7901                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7902                // need other information about the application, like the ABI and what not ?
7903                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7904                mInstrumentation.put(a.getComponentName(), a);
7905                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7906                    if (r == null) {
7907                        r = new StringBuilder(256);
7908                    } else {
7909                        r.append(' ');
7910                    }
7911                    r.append(a.info.name);
7912                }
7913            }
7914            if (r != null) {
7915                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7916            }
7917
7918            if (pkg.protectedBroadcasts != null) {
7919                N = pkg.protectedBroadcasts.size();
7920                for (i=0; i<N; i++) {
7921                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7922                }
7923            }
7924
7925            pkgSetting.setTimeStamp(scanFileTime);
7926
7927            // Create idmap files for pairs of (packages, overlay packages).
7928            // Note: "android", ie framework-res.apk, is handled by native layers.
7929            if (pkg.mOverlayTarget != null) {
7930                // This is an overlay package.
7931                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7932                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7933                        mOverlays.put(pkg.mOverlayTarget,
7934                                new ArrayMap<String, PackageParser.Package>());
7935                    }
7936                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7937                    map.put(pkg.packageName, pkg);
7938                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7939                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7940                        createIdmapFailed = true;
7941                    }
7942                }
7943            } else if (mOverlays.containsKey(pkg.packageName) &&
7944                    !pkg.packageName.equals("android")) {
7945                // This is a regular package, with one or more known overlay packages.
7946                createIdmapsForPackageLI(pkg);
7947            }
7948        }
7949
7950        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7951
7952        if (createIdmapFailed) {
7953            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7954                    "scanPackageLI failed to createIdmap");
7955        }
7956        return pkg;
7957    }
7958
7959    /**
7960     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7961     * is derived purely on the basis of the contents of {@code scanFile} and
7962     * {@code cpuAbiOverride}.
7963     *
7964     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7965     */
7966    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7967                                 String cpuAbiOverride, boolean extractLibs)
7968            throws PackageManagerException {
7969        // TODO: We can probably be smarter about this stuff. For installed apps,
7970        // we can calculate this information at install time once and for all. For
7971        // system apps, we can probably assume that this information doesn't change
7972        // after the first boot scan. As things stand, we do lots of unnecessary work.
7973
7974        // Give ourselves some initial paths; we'll come back for another
7975        // pass once we've determined ABI below.
7976        setNativeLibraryPaths(pkg);
7977
7978        // We would never need to extract libs for forward-locked and external packages,
7979        // since the container service will do it for us. We shouldn't attempt to
7980        // extract libs from system app when it was not updated.
7981        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7982                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7983            extractLibs = false;
7984        }
7985
7986        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7987        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7988
7989        NativeLibraryHelper.Handle handle = null;
7990        try {
7991            handle = NativeLibraryHelper.Handle.create(pkg);
7992            // TODO(multiArch): This can be null for apps that didn't go through the
7993            // usual installation process. We can calculate it again, like we
7994            // do during install time.
7995            //
7996            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7997            // unnecessary.
7998            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7999
8000            // Null out the abis so that they can be recalculated.
8001            pkg.applicationInfo.primaryCpuAbi = null;
8002            pkg.applicationInfo.secondaryCpuAbi = null;
8003            if (isMultiArch(pkg.applicationInfo)) {
8004                // Warn if we've set an abiOverride for multi-lib packages..
8005                // By definition, we need to copy both 32 and 64 bit libraries for
8006                // such packages.
8007                if (pkg.cpuAbiOverride != null
8008                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8009                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8010                }
8011
8012                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8013                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8014                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8015                    if (extractLibs) {
8016                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8017                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8018                                useIsaSpecificSubdirs);
8019                    } else {
8020                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8021                    }
8022                }
8023
8024                maybeThrowExceptionForMultiArchCopy(
8025                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8026
8027                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8028                    if (extractLibs) {
8029                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8030                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8031                                useIsaSpecificSubdirs);
8032                    } else {
8033                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8034                    }
8035                }
8036
8037                maybeThrowExceptionForMultiArchCopy(
8038                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8039
8040                if (abi64 >= 0) {
8041                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8042                }
8043
8044                if (abi32 >= 0) {
8045                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8046                    if (abi64 >= 0) {
8047                        pkg.applicationInfo.secondaryCpuAbi = abi;
8048                    } else {
8049                        pkg.applicationInfo.primaryCpuAbi = abi;
8050                    }
8051                }
8052                if (cpuAbiOverride != null &&
8053                        cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) {
8054                    pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8055                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8056                }
8057            } else {
8058                String[] abiList = (cpuAbiOverride != null) ?
8059                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8060
8061                // Enable gross and lame hacks for apps that are built with old
8062                // SDK tools. We must scan their APKs for renderscript bitcode and
8063                // not launch them if it's present. Don't bother checking on devices
8064                // that don't have 64 bit support.
8065                boolean needsRenderScriptOverride = false;
8066                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8067                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8068                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8069                    needsRenderScriptOverride = true;
8070                }
8071
8072                final int copyRet;
8073                if (extractLibs) {
8074                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8075                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8076                } else {
8077                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8078                }
8079
8080                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8081                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8082                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8083                }
8084
8085                if (copyRet >= 0) {
8086                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8087                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8088                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8089                } else if (needsRenderScriptOverride) {
8090                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8091                }
8092            }
8093        } catch (IOException ioe) {
8094            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8095        } finally {
8096            IoUtils.closeQuietly(handle);
8097        }
8098
8099        // Now that we've calculated the ABIs and determined if it's an internal app,
8100        // we will go ahead and populate the nativeLibraryPath.
8101        setNativeLibraryPaths(pkg);
8102    }
8103
8104    /**
8105     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8106     * i.e, so that all packages can be run inside a single process if required.
8107     *
8108     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8109     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8110     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8111     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8112     * updating a package that belongs to a shared user.
8113     *
8114     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8115     * adds unnecessary complexity.
8116     */
8117    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8118            PackageParser.Package scannedPackage, boolean bootComplete) {
8119        String requiredInstructionSet = null;
8120        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8121            requiredInstructionSet = VMRuntime.getInstructionSet(
8122                     scannedPackage.applicationInfo.primaryCpuAbi);
8123        }
8124
8125        PackageSetting requirer = null;
8126        for (PackageSetting ps : packagesForUser) {
8127            // If packagesForUser contains scannedPackage, we skip it. This will happen
8128            // when scannedPackage is an update of an existing package. Without this check,
8129            // we will never be able to change the ABI of any package belonging to a shared
8130            // user, even if it's compatible with other packages.
8131            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8132                if (ps.primaryCpuAbiString == null) {
8133                    continue;
8134                }
8135
8136                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8137                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8138                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8139                    // this but there's not much we can do.
8140                    String errorMessage = "Instruction set mismatch, "
8141                            + ((requirer == null) ? "[caller]" : requirer)
8142                            + " requires " + requiredInstructionSet + " whereas " + ps
8143                            + " requires " + instructionSet;
8144                    Slog.w(TAG, errorMessage);
8145                }
8146
8147                if (requiredInstructionSet == null) {
8148                    requiredInstructionSet = instructionSet;
8149                    requirer = ps;
8150                }
8151            }
8152        }
8153
8154        if (requiredInstructionSet != null) {
8155            String adjustedAbi;
8156            if (requirer != null) {
8157                // requirer != null implies that either scannedPackage was null or that scannedPackage
8158                // did not require an ABI, in which case we have to adjust scannedPackage to match
8159                // the ABI of the set (which is the same as requirer's ABI)
8160                adjustedAbi = requirer.primaryCpuAbiString;
8161                if (scannedPackage != null) {
8162                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8163                }
8164            } else {
8165                // requirer == null implies that we're updating all ABIs in the set to
8166                // match scannedPackage.
8167                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8168            }
8169
8170            for (PackageSetting ps : packagesForUser) {
8171                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8172                    if (ps.primaryCpuAbiString != null) {
8173                        continue;
8174                    }
8175
8176                    ps.primaryCpuAbiString = adjustedAbi;
8177                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8178                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8179                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8180                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8181                                + " (requirer="
8182                                + (requirer == null ? "null" : requirer.pkg.packageName)
8183                                + ", scannedPackage="
8184                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8185                                + ")");
8186                        try {
8187                            mInstaller.rmdex(ps.codePathString,
8188                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8189                        } catch (InstallerException ignored) {
8190                        }
8191                    }
8192                }
8193            }
8194        }
8195    }
8196
8197    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8198        synchronized (mPackages) {
8199            mResolverReplaced = true;
8200            // Set up information for custom user intent resolution activity.
8201            mResolveActivity.applicationInfo = pkg.applicationInfo;
8202            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8203            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8204            mResolveActivity.processName = pkg.applicationInfo.packageName;
8205            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8206            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8207                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8208            mResolveActivity.theme = 0;
8209            mResolveActivity.exported = true;
8210            mResolveActivity.enabled = true;
8211            mResolveInfo.activityInfo = mResolveActivity;
8212            mResolveInfo.priority = 0;
8213            mResolveInfo.preferredOrder = 0;
8214            mResolveInfo.match = 0;
8215            mResolveComponentName = mCustomResolverComponentName;
8216            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8217                    mResolveComponentName);
8218        }
8219    }
8220
8221    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8222        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8223
8224        // Set up information for ephemeral installer activity
8225        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8226        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8227        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8228        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8229        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8230        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8231                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8232        mEphemeralInstallerActivity.theme = 0;
8233        mEphemeralInstallerActivity.exported = true;
8234        mEphemeralInstallerActivity.enabled = true;
8235        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8236        mEphemeralInstallerInfo.priority = 0;
8237        mEphemeralInstallerInfo.preferredOrder = 0;
8238        mEphemeralInstallerInfo.match = 0;
8239
8240        if (DEBUG_EPHEMERAL) {
8241            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8242        }
8243    }
8244
8245    private static String calculateBundledApkRoot(final String codePathString) {
8246        final File codePath = new File(codePathString);
8247        final File codeRoot;
8248        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8249            codeRoot = Environment.getRootDirectory();
8250        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8251            codeRoot = Environment.getOemDirectory();
8252        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8253            codeRoot = Environment.getVendorDirectory();
8254        } else {
8255            // Unrecognized code path; take its top real segment as the apk root:
8256            // e.g. /something/app/blah.apk => /something
8257            try {
8258                File f = codePath.getCanonicalFile();
8259                File parent = f.getParentFile();    // non-null because codePath is a file
8260                File tmp;
8261                while ((tmp = parent.getParentFile()) != null) {
8262                    f = parent;
8263                    parent = tmp;
8264                }
8265                codeRoot = f;
8266                Slog.w(TAG, "Unrecognized code path "
8267                        + codePath + " - using " + codeRoot);
8268            } catch (IOException e) {
8269                // Can't canonicalize the code path -- shenanigans?
8270                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8271                return Environment.getRootDirectory().getPath();
8272            }
8273        }
8274        return codeRoot.getPath();
8275    }
8276
8277    /**
8278     * Derive and set the location of native libraries for the given package,
8279     * which varies depending on where and how the package was installed.
8280     */
8281    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8282        final ApplicationInfo info = pkg.applicationInfo;
8283        final String codePath = pkg.codePath;
8284        final File codeFile = new File(codePath);
8285        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8286        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8287
8288        info.nativeLibraryRootDir = null;
8289        info.nativeLibraryRootRequiresIsa = false;
8290        info.nativeLibraryDir = null;
8291        info.secondaryNativeLibraryDir = null;
8292
8293        if (isApkFile(codeFile)) {
8294            // Monolithic install
8295            if (bundledApp) {
8296                // If "/system/lib64/apkname" exists, assume that is the per-package
8297                // native library directory to use; otherwise use "/system/lib/apkname".
8298                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8299                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8300                        getPrimaryInstructionSet(info));
8301
8302                // This is a bundled system app so choose the path based on the ABI.
8303                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8304                // is just the default path.
8305                final String apkName = deriveCodePathName(codePath);
8306                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8307                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8308                        apkName).getAbsolutePath();
8309
8310                if (info.secondaryCpuAbi != null) {
8311                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8312                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8313                            secondaryLibDir, apkName).getAbsolutePath();
8314                }
8315            } else if (asecApp) {
8316                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8317                        .getAbsolutePath();
8318            } else {
8319                final String apkName = deriveCodePathName(codePath);
8320                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8321                        .getAbsolutePath();
8322            }
8323
8324            info.nativeLibraryRootRequiresIsa = false;
8325            info.nativeLibraryDir = info.nativeLibraryRootDir;
8326        } else {
8327            // Cluster install
8328            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8329            info.nativeLibraryRootRequiresIsa = true;
8330
8331            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8332                    getPrimaryInstructionSet(info)).getAbsolutePath();
8333
8334            if (info.secondaryCpuAbi != null) {
8335                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8336                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8337            }
8338        }
8339    }
8340
8341    /**
8342     * Calculate the abis and roots for a bundled app. These can uniquely
8343     * be determined from the contents of the system partition, i.e whether
8344     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8345     * of this information, and instead assume that the system was built
8346     * sensibly.
8347     */
8348    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8349                                           PackageSetting pkgSetting) {
8350        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8351
8352        // If "/system/lib64/apkname" exists, assume that is the per-package
8353        // native library directory to use; otherwise use "/system/lib/apkname".
8354        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8355        setBundledAppAbi(pkg, apkRoot, apkName);
8356        // pkgSetting might be null during rescan following uninstall of updates
8357        // to a bundled app, so accommodate that possibility.  The settings in
8358        // that case will be established later from the parsed package.
8359        //
8360        // If the settings aren't null, sync them up with what we've just derived.
8361        // note that apkRoot isn't stored in the package settings.
8362        if (pkgSetting != null) {
8363            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8364            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8365        }
8366    }
8367
8368    /**
8369     * Deduces the ABI of a bundled app and sets the relevant fields on the
8370     * parsed pkg object.
8371     *
8372     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8373     *        under which system libraries are installed.
8374     * @param apkName the name of the installed package.
8375     */
8376    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8377        final File codeFile = new File(pkg.codePath);
8378
8379        final boolean has64BitLibs;
8380        final boolean has32BitLibs;
8381        if (isApkFile(codeFile)) {
8382            // Monolithic install
8383            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8384            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8385        } else {
8386            // Cluster install
8387            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8388            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8389                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8390                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8391                has64BitLibs = (new File(rootDir, isa)).exists();
8392            } else {
8393                has64BitLibs = false;
8394            }
8395            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8396                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8397                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8398                has32BitLibs = (new File(rootDir, isa)).exists();
8399            } else {
8400                has32BitLibs = false;
8401            }
8402        }
8403
8404        if (has64BitLibs && !has32BitLibs) {
8405            // The package has 64 bit libs, but not 32 bit libs. Its primary
8406            // ABI should be 64 bit. We can safely assume here that the bundled
8407            // native libraries correspond to the most preferred ABI in the list.
8408
8409            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8410            pkg.applicationInfo.secondaryCpuAbi = null;
8411        } else if (has32BitLibs && !has64BitLibs) {
8412            // The package has 32 bit libs but not 64 bit libs. Its primary
8413            // ABI should be 32 bit.
8414
8415            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8416            pkg.applicationInfo.secondaryCpuAbi = null;
8417        } else if (has32BitLibs && has64BitLibs) {
8418            // The application has both 64 and 32 bit bundled libraries. We check
8419            // here that the app declares multiArch support, and warn if it doesn't.
8420            //
8421            // We will be lenient here and record both ABIs. The primary will be the
8422            // ABI that's higher on the list, i.e, a device that's configured to prefer
8423            // 64 bit apps will see a 64 bit primary ABI,
8424
8425            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8426                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8427            }
8428
8429            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8430                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8431                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8432            } else {
8433                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8434                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8435            }
8436        } else {
8437            pkg.applicationInfo.primaryCpuAbi = null;
8438            pkg.applicationInfo.secondaryCpuAbi = null;
8439        }
8440    }
8441
8442    private void killApplication(String pkgName, int appId, String reason) {
8443        // Request the ActivityManager to kill the process(only for existing packages)
8444        // so that we do not end up in a confused state while the user is still using the older
8445        // version of the application while the new one gets installed.
8446        IActivityManager am = ActivityManagerNative.getDefault();
8447        if (am != null) {
8448            try {
8449                am.killApplicationWithAppId(pkgName, appId, reason);
8450            } catch (RemoteException e) {
8451            }
8452        }
8453    }
8454
8455    void removePackageLI(PackageSetting ps, boolean chatty) {
8456        if (DEBUG_INSTALL) {
8457            if (chatty)
8458                Log.d(TAG, "Removing package " + ps.name);
8459        }
8460
8461        // writer
8462        synchronized (mPackages) {
8463            mPackages.remove(ps.name);
8464            final PackageParser.Package pkg = ps.pkg;
8465            if (pkg != null) {
8466                cleanPackageDataStructuresLILPw(pkg, chatty);
8467            }
8468        }
8469    }
8470
8471    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8472        if (DEBUG_INSTALL) {
8473            if (chatty)
8474                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8475        }
8476
8477        // writer
8478        synchronized (mPackages) {
8479            mPackages.remove(pkg.applicationInfo.packageName);
8480            cleanPackageDataStructuresLILPw(pkg, chatty);
8481        }
8482    }
8483
8484    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8485        int N = pkg.providers.size();
8486        StringBuilder r = null;
8487        int i;
8488        for (i=0; i<N; i++) {
8489            PackageParser.Provider p = pkg.providers.get(i);
8490            mProviders.removeProvider(p);
8491            if (p.info.authority == null) {
8492
8493                /* There was another ContentProvider with this authority when
8494                 * this app was installed so this authority is null,
8495                 * Ignore it as we don't have to unregister the provider.
8496                 */
8497                continue;
8498            }
8499            String names[] = p.info.authority.split(";");
8500            for (int j = 0; j < names.length; j++) {
8501                if (mProvidersByAuthority.get(names[j]) == p) {
8502                    mProvidersByAuthority.remove(names[j]);
8503                    if (DEBUG_REMOVE) {
8504                        if (chatty)
8505                            Log.d(TAG, "Unregistered content provider: " + names[j]
8506                                    + ", className = " + p.info.name + ", isSyncable = "
8507                                    + p.info.isSyncable);
8508                    }
8509                }
8510            }
8511            if (DEBUG_REMOVE && chatty) {
8512                if (r == null) {
8513                    r = new StringBuilder(256);
8514                } else {
8515                    r.append(' ');
8516                }
8517                r.append(p.info.name);
8518            }
8519        }
8520        if (r != null) {
8521            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8522        }
8523
8524        N = pkg.services.size();
8525        r = null;
8526        for (i=0; i<N; i++) {
8527            PackageParser.Service s = pkg.services.get(i);
8528            mServices.removeService(s);
8529            if (chatty) {
8530                if (r == null) {
8531                    r = new StringBuilder(256);
8532                } else {
8533                    r.append(' ');
8534                }
8535                r.append(s.info.name);
8536            }
8537        }
8538        if (r != null) {
8539            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8540        }
8541
8542        N = pkg.receivers.size();
8543        r = null;
8544        for (i=0; i<N; i++) {
8545            PackageParser.Activity a = pkg.receivers.get(i);
8546            mReceivers.removeActivity(a, "receiver");
8547            if (DEBUG_REMOVE && chatty) {
8548                if (r == null) {
8549                    r = new StringBuilder(256);
8550                } else {
8551                    r.append(' ');
8552                }
8553                r.append(a.info.name);
8554            }
8555        }
8556        if (r != null) {
8557            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8558        }
8559
8560        N = pkg.activities.size();
8561        r = null;
8562        for (i=0; i<N; i++) {
8563            PackageParser.Activity a = pkg.activities.get(i);
8564            mActivities.removeActivity(a, "activity");
8565            if (DEBUG_REMOVE && chatty) {
8566                if (r == null) {
8567                    r = new StringBuilder(256);
8568                } else {
8569                    r.append(' ');
8570                }
8571                r.append(a.info.name);
8572            }
8573        }
8574        if (r != null) {
8575            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8576        }
8577
8578        N = pkg.permissions.size();
8579        r = null;
8580        for (i=0; i<N; i++) {
8581            PackageParser.Permission p = pkg.permissions.get(i);
8582            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8583            if (bp == null) {
8584                bp = mSettings.mPermissionTrees.get(p.info.name);
8585            }
8586            if (bp != null && bp.perm == p) {
8587                bp.perm = null;
8588                if (DEBUG_REMOVE && chatty) {
8589                    if (r == null) {
8590                        r = new StringBuilder(256);
8591                    } else {
8592                        r.append(' ');
8593                    }
8594                    r.append(p.info.name);
8595                }
8596            }
8597            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8598                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8599                if (appOpPkgs != null) {
8600                    appOpPkgs.remove(pkg.packageName);
8601                }
8602            }
8603        }
8604        if (r != null) {
8605            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8606        }
8607
8608        N = pkg.requestedPermissions.size();
8609        r = null;
8610        for (i=0; i<N; i++) {
8611            String perm = pkg.requestedPermissions.get(i);
8612            BasePermission bp = mSettings.mPermissions.get(perm);
8613            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8614                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8615                if (appOpPkgs != null) {
8616                    appOpPkgs.remove(pkg.packageName);
8617                    if (appOpPkgs.isEmpty()) {
8618                        mAppOpPermissionPackages.remove(perm);
8619                    }
8620                }
8621            }
8622        }
8623        if (r != null) {
8624            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8625        }
8626
8627        N = pkg.instrumentation.size();
8628        r = null;
8629        for (i=0; i<N; i++) {
8630            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8631            mInstrumentation.remove(a.getComponentName());
8632            if (DEBUG_REMOVE && chatty) {
8633                if (r == null) {
8634                    r = new StringBuilder(256);
8635                } else {
8636                    r.append(' ');
8637                }
8638                r.append(a.info.name);
8639            }
8640        }
8641        if (r != null) {
8642            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8643        }
8644
8645        r = null;
8646        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8647            // Only system apps can hold shared libraries.
8648            if (pkg.libraryNames != null) {
8649                for (i=0; i<pkg.libraryNames.size(); i++) {
8650                    String name = pkg.libraryNames.get(i);
8651                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8652                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8653                        mSharedLibraries.remove(name);
8654                        if (DEBUG_REMOVE && chatty) {
8655                            if (r == null) {
8656                                r = new StringBuilder(256);
8657                            } else {
8658                                r.append(' ');
8659                            }
8660                            r.append(name);
8661                        }
8662                    }
8663                }
8664            }
8665        }
8666        if (r != null) {
8667            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8668        }
8669    }
8670
8671    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8672        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8673            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8674                return true;
8675            }
8676        }
8677        return false;
8678    }
8679
8680    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8681    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8682    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8683
8684    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8685            int flags) {
8686        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8687        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8688    }
8689
8690    private void updatePermissionsLPw(String changingPkg,
8691            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8692        // Make sure there are no dangling permission trees.
8693        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8694        while (it.hasNext()) {
8695            final BasePermission bp = it.next();
8696            if (bp.packageSetting == null) {
8697                // We may not yet have parsed the package, so just see if
8698                // we still know about its settings.
8699                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8700            }
8701            if (bp.packageSetting == null) {
8702                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8703                        + " from package " + bp.sourcePackage);
8704                it.remove();
8705            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8706                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8707                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8708                            + " from package " + bp.sourcePackage);
8709                    flags |= UPDATE_PERMISSIONS_ALL;
8710                    it.remove();
8711                }
8712            }
8713        }
8714
8715        // Make sure all dynamic permissions have been assigned to a package,
8716        // and make sure there are no dangling permissions.
8717        it = mSettings.mPermissions.values().iterator();
8718        while (it.hasNext()) {
8719            final BasePermission bp = it.next();
8720            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8721                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8722                        + bp.name + " pkg=" + bp.sourcePackage
8723                        + " info=" + bp.pendingInfo);
8724                if (bp.packageSetting == null && bp.pendingInfo != null) {
8725                    final BasePermission tree = findPermissionTreeLP(bp.name);
8726                    if (tree != null && tree.perm != null) {
8727                        bp.packageSetting = tree.packageSetting;
8728                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8729                                new PermissionInfo(bp.pendingInfo));
8730                        bp.perm.info.packageName = tree.perm.info.packageName;
8731                        bp.perm.info.name = bp.name;
8732                        bp.uid = tree.uid;
8733                    }
8734                }
8735            }
8736            if (bp.packageSetting == null) {
8737                // We may not yet have parsed the package, so just see if
8738                // we still know about its settings.
8739                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8740            }
8741            if (bp.packageSetting == null) {
8742                Slog.w(TAG, "Removing dangling permission: " + bp.name
8743                        + " from package " + bp.sourcePackage);
8744                it.remove();
8745            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8746                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8747                    Slog.i(TAG, "Removing old permission: " + bp.name
8748                            + " from package " + bp.sourcePackage);
8749                    flags |= UPDATE_PERMISSIONS_ALL;
8750                    it.remove();
8751                }
8752            }
8753        }
8754
8755        // Now update the permissions for all packages, in particular
8756        // replace the granted permissions of the system packages.
8757        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8758            for (PackageParser.Package pkg : mPackages.values()) {
8759                if (pkg != pkgInfo) {
8760                    // Only replace for packages on requested volume
8761                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8762                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8763                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8764                    grantPermissionsLPw(pkg, replace, changingPkg);
8765                }
8766            }
8767        }
8768
8769        if (pkgInfo != null) {
8770            // Only replace for packages on requested volume
8771            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8772            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8773                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8774            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8775        }
8776    }
8777
8778    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8779            String packageOfInterest) {
8780        // IMPORTANT: There are two types of permissions: install and runtime.
8781        // Install time permissions are granted when the app is installed to
8782        // all device users and users added in the future. Runtime permissions
8783        // are granted at runtime explicitly to specific users. Normal and signature
8784        // protected permissions are install time permissions. Dangerous permissions
8785        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8786        // otherwise they are runtime permissions. This function does not manage
8787        // runtime permissions except for the case an app targeting Lollipop MR1
8788        // being upgraded to target a newer SDK, in which case dangerous permissions
8789        // are transformed from install time to runtime ones.
8790
8791        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8792        if (ps == null) {
8793            return;
8794        }
8795
8796        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8797
8798        PermissionsState permissionsState = ps.getPermissionsState();
8799        PermissionsState origPermissions = permissionsState;
8800
8801        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8802
8803        boolean runtimePermissionsRevoked = false;
8804        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8805
8806        boolean changedInstallPermission = false;
8807
8808        if (replace) {
8809            ps.installPermissionsFixed = false;
8810            if (!ps.isSharedUser()) {
8811                origPermissions = new PermissionsState(permissionsState);
8812                permissionsState.reset();
8813            } else {
8814                // We need to know only about runtime permission changes since the
8815                // calling code always writes the install permissions state but
8816                // the runtime ones are written only if changed. The only cases of
8817                // changed runtime permissions here are promotion of an install to
8818                // runtime and revocation of a runtime from a shared user.
8819                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8820                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8821                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8822                    runtimePermissionsRevoked = true;
8823                }
8824            }
8825        }
8826
8827        permissionsState.setGlobalGids(mGlobalGids);
8828
8829        final int N = pkg.requestedPermissions.size();
8830        for (int i=0; i<N; i++) {
8831            final String name = pkg.requestedPermissions.get(i);
8832            final BasePermission bp = mSettings.mPermissions.get(name);
8833
8834            if (DEBUG_INSTALL) {
8835                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8836            }
8837
8838            if (bp == null || bp.packageSetting == null) {
8839                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8840                    Slog.w(TAG, "Unknown permission " + name
8841                            + " in package " + pkg.packageName);
8842                }
8843                continue;
8844            }
8845
8846            final String perm = bp.name;
8847            boolean allowedSig = false;
8848            int grant = GRANT_DENIED;
8849
8850            // Keep track of app op permissions.
8851            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8852                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8853                if (pkgs == null) {
8854                    pkgs = new ArraySet<>();
8855                    mAppOpPermissionPackages.put(bp.name, pkgs);
8856                }
8857                pkgs.add(pkg.packageName);
8858            }
8859
8860            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8861            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8862                    >= Build.VERSION_CODES.M;
8863            switch (level) {
8864                case PermissionInfo.PROTECTION_NORMAL: {
8865                    // For all apps normal permissions are install time ones.
8866                    grant = GRANT_INSTALL;
8867                } break;
8868
8869                case PermissionInfo.PROTECTION_DANGEROUS: {
8870                    // If a permission review is required for legacy apps we represent
8871                    // their permissions as always granted runtime ones since we need
8872                    // to keep the review required permission flag per user while an
8873                    // install permission's state is shared across all users.
8874                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8875                        // For legacy apps dangerous permissions are install time ones.
8876                        grant = GRANT_INSTALL;
8877                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8878                        // For legacy apps that became modern, install becomes runtime.
8879                        grant = GRANT_UPGRADE;
8880                    } else if (mPromoteSystemApps
8881                            && isSystemApp(ps)
8882                            && mExistingSystemPackages.contains(ps.name)) {
8883                        // For legacy system apps, install becomes runtime.
8884                        // We cannot check hasInstallPermission() for system apps since those
8885                        // permissions were granted implicitly and not persisted pre-M.
8886                        grant = GRANT_UPGRADE;
8887                    } else {
8888                        // For modern apps keep runtime permissions unchanged.
8889                        grant = GRANT_RUNTIME;
8890                    }
8891                } break;
8892
8893                case PermissionInfo.PROTECTION_SIGNATURE: {
8894                    // For all apps signature permissions are install time ones.
8895                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8896                    if (allowedSig) {
8897                        grant = GRANT_INSTALL;
8898                    }
8899                } break;
8900            }
8901
8902            if (DEBUG_INSTALL) {
8903                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8904            }
8905
8906            if (grant != GRANT_DENIED) {
8907                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8908                    // If this is an existing, non-system package, then
8909                    // we can't add any new permissions to it.
8910                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8911                        // Except...  if this is a permission that was added
8912                        // to the platform (note: need to only do this when
8913                        // updating the platform).
8914                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8915                            grant = GRANT_DENIED;
8916                        }
8917                    }
8918                }
8919
8920                switch (grant) {
8921                    case GRANT_INSTALL: {
8922                        // Revoke this as runtime permission to handle the case of
8923                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8924                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8925                            if (origPermissions.getRuntimePermissionState(
8926                                    bp.name, userId) != null) {
8927                                // Revoke the runtime permission and clear the flags.
8928                                origPermissions.revokeRuntimePermission(bp, userId);
8929                                origPermissions.updatePermissionFlags(bp, userId,
8930                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8931                                // If we revoked a permission permission, we have to write.
8932                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8933                                        changedRuntimePermissionUserIds, userId);
8934                            }
8935                        }
8936                        // Grant an install permission.
8937                        if (permissionsState.grantInstallPermission(bp) !=
8938                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8939                            changedInstallPermission = true;
8940                        }
8941                    } break;
8942
8943                    case GRANT_RUNTIME: {
8944                        // Grant previously granted runtime permissions.
8945                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8946                            PermissionState permissionState = origPermissions
8947                                    .getRuntimePermissionState(bp.name, userId);
8948                            int flags = permissionState != null
8949                                    ? permissionState.getFlags() : 0;
8950                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8951                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8952                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8953                                    // If we cannot put the permission as it was, we have to write.
8954                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8955                                            changedRuntimePermissionUserIds, userId);
8956                                }
8957                                // If the app supports runtime permissions no need for a review.
8958                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8959                                        && appSupportsRuntimePermissions
8960                                        && (flags & PackageManager
8961                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8962                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8963                                    // Since we changed the flags, we have to write.
8964                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8965                                            changedRuntimePermissionUserIds, userId);
8966                                }
8967                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8968                                    && !appSupportsRuntimePermissions) {
8969                                // For legacy apps that need a permission review, every new
8970                                // runtime permission is granted but it is pending a review.
8971                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8972                                    permissionsState.grantRuntimePermission(bp, userId);
8973                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8974                                    // We changed the permission and flags, hence have to write.
8975                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8976                                            changedRuntimePermissionUserIds, userId);
8977                                }
8978                            }
8979                            // Propagate the permission flags.
8980                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8981                        }
8982                    } break;
8983
8984                    case GRANT_UPGRADE: {
8985                        // Grant runtime permissions for a previously held install permission.
8986                        PermissionState permissionState = origPermissions
8987                                .getInstallPermissionState(bp.name);
8988                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8989
8990                        if (origPermissions.revokeInstallPermission(bp)
8991                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8992                            // We will be transferring the permission flags, so clear them.
8993                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8994                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8995                            changedInstallPermission = true;
8996                        }
8997
8998                        // If the permission is not to be promoted to runtime we ignore it and
8999                        // also its other flags as they are not applicable to install permissions.
9000                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9001                            for (int userId : currentUserIds) {
9002                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9003                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9004                                    // Transfer the permission flags.
9005                                    permissionsState.updatePermissionFlags(bp, userId,
9006                                            flags, flags);
9007                                    // If we granted the permission, we have to write.
9008                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9009                                            changedRuntimePermissionUserIds, userId);
9010                                }
9011                            }
9012                        }
9013                    } break;
9014
9015                    default: {
9016                        if (packageOfInterest == null
9017                                || packageOfInterest.equals(pkg.packageName)) {
9018                            Slog.w(TAG, "Not granting permission " + perm
9019                                    + " to package " + pkg.packageName
9020                                    + " because it was previously installed without");
9021                        }
9022                    } break;
9023                }
9024            } else {
9025                if (permissionsState.revokeInstallPermission(bp) !=
9026                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9027                    // Also drop the permission flags.
9028                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9029                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9030                    changedInstallPermission = true;
9031                    Slog.i(TAG, "Un-granting permission " + perm
9032                            + " from package " + pkg.packageName
9033                            + " (protectionLevel=" + bp.protectionLevel
9034                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9035                            + ")");
9036                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9037                    // Don't print warning for app op permissions, since it is fine for them
9038                    // not to be granted, there is a UI for the user to decide.
9039                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9040                        Slog.w(TAG, "Not granting permission " + perm
9041                                + " to package " + pkg.packageName
9042                                + " (protectionLevel=" + bp.protectionLevel
9043                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9044                                + ")");
9045                    }
9046                }
9047            }
9048        }
9049
9050        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9051                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9052            // This is the first that we have heard about this package, so the
9053            // permissions we have now selected are fixed until explicitly
9054            // changed.
9055            ps.installPermissionsFixed = true;
9056        }
9057
9058        // Persist the runtime permissions state for users with changes. If permissions
9059        // were revoked because no app in the shared user declares them we have to
9060        // write synchronously to avoid losing runtime permissions state.
9061        for (int userId : changedRuntimePermissionUserIds) {
9062            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9063        }
9064
9065        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9066    }
9067
9068    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9069        boolean allowed = false;
9070        final int NP = PackageParser.NEW_PERMISSIONS.length;
9071        for (int ip=0; ip<NP; ip++) {
9072            final PackageParser.NewPermissionInfo npi
9073                    = PackageParser.NEW_PERMISSIONS[ip];
9074            if (npi.name.equals(perm)
9075                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9076                allowed = true;
9077                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9078                        + pkg.packageName);
9079                break;
9080            }
9081        }
9082        return allowed;
9083    }
9084
9085    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9086            BasePermission bp, PermissionsState origPermissions) {
9087        boolean allowed;
9088        allowed = (compareSignatures(
9089                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9090                        == PackageManager.SIGNATURE_MATCH)
9091                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9092                        == PackageManager.SIGNATURE_MATCH);
9093        if (!allowed && (bp.protectionLevel
9094                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9095            if (isSystemApp(pkg)) {
9096                // For updated system applications, a system permission
9097                // is granted only if it had been defined by the original application.
9098                if (pkg.isUpdatedSystemApp()) {
9099                    final PackageSetting sysPs = mSettings
9100                            .getDisabledSystemPkgLPr(pkg.packageName);
9101                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9102                        // If the original was granted this permission, we take
9103                        // that grant decision as read and propagate it to the
9104                        // update.
9105                        if (sysPs.isPrivileged()) {
9106                            allowed = true;
9107                        }
9108                    } else {
9109                        // The system apk may have been updated with an older
9110                        // version of the one on the data partition, but which
9111                        // granted a new system permission that it didn't have
9112                        // before.  In this case we do want to allow the app to
9113                        // now get the new permission if the ancestral apk is
9114                        // privileged to get it.
9115                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9116                            for (int j=0;
9117                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9118                                if (perm.equals(
9119                                        sysPs.pkg.requestedPermissions.get(j))) {
9120                                    allowed = true;
9121                                    break;
9122                                }
9123                            }
9124                        }
9125                    }
9126                } else {
9127                    allowed = isPrivilegedApp(pkg);
9128                }
9129            }
9130        }
9131        if (!allowed) {
9132            if (!allowed && (bp.protectionLevel
9133                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9134                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9135                // If this was a previously normal/dangerous permission that got moved
9136                // to a system permission as part of the runtime permission redesign, then
9137                // we still want to blindly grant it to old apps.
9138                allowed = true;
9139            }
9140            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9141                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9142                // If this permission is to be granted to the system installer and
9143                // this app is an installer, then it gets the permission.
9144                allowed = true;
9145            }
9146            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9147                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9148                // If this permission is to be granted to the system verifier and
9149                // this app is a verifier, then it gets the permission.
9150                allowed = true;
9151            }
9152            if (!allowed && (bp.protectionLevel
9153                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9154                    && isSystemApp(pkg)) {
9155                // Any pre-installed system app is allowed to get this permission.
9156                allowed = true;
9157            }
9158            if (!allowed && (bp.protectionLevel
9159                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9160                // For development permissions, a development permission
9161                // is granted only if it was already granted.
9162                allowed = origPermissions.hasInstallPermission(perm);
9163            }
9164        }
9165        return allowed;
9166    }
9167
9168    final class ActivityIntentResolver
9169            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9170        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9171                boolean defaultOnly, int userId) {
9172            if (!sUserManager.exists(userId)) return null;
9173            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9174            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9175        }
9176
9177        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9178                int userId) {
9179            if (!sUserManager.exists(userId)) return null;
9180            mFlags = flags;
9181            return super.queryIntent(intent, resolvedType,
9182                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9183        }
9184
9185        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9186                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9187            if (!sUserManager.exists(userId)) return null;
9188            if (packageActivities == null) {
9189                return null;
9190            }
9191            mFlags = flags;
9192            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9193            final int N = packageActivities.size();
9194            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9195                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9196
9197            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9198            for (int i = 0; i < N; ++i) {
9199                intentFilters = packageActivities.get(i).intents;
9200                if (intentFilters != null && intentFilters.size() > 0) {
9201                    PackageParser.ActivityIntentInfo[] array =
9202                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9203                    intentFilters.toArray(array);
9204                    listCut.add(array);
9205                }
9206            }
9207            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9208        }
9209
9210        public final void addActivity(PackageParser.Activity a, String type) {
9211            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9212            mActivities.put(a.getComponentName(), a);
9213            if (DEBUG_SHOW_INFO)
9214                Log.v(
9215                TAG, "  " + type + " " +
9216                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9217            if (DEBUG_SHOW_INFO)
9218                Log.v(TAG, "    Class=" + a.info.name);
9219            final int NI = a.intents.size();
9220            for (int j=0; j<NI; j++) {
9221                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9222                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9223                    intent.setPriority(0);
9224                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9225                            + a.className + " with priority > 0, forcing to 0");
9226                }
9227                if (DEBUG_SHOW_INFO) {
9228                    Log.v(TAG, "    IntentFilter:");
9229                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9230                }
9231                if (!intent.debugCheck()) {
9232                    Log.w(TAG, "==> For Activity " + a.info.name);
9233                }
9234                addFilter(intent);
9235            }
9236        }
9237
9238        public final void removeActivity(PackageParser.Activity a, String type) {
9239            mActivities.remove(a.getComponentName());
9240            if (DEBUG_SHOW_INFO) {
9241                Log.v(TAG, "  " + type + " "
9242                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9243                                : a.info.name) + ":");
9244                Log.v(TAG, "    Class=" + a.info.name);
9245            }
9246            final int NI = a.intents.size();
9247            for (int j=0; j<NI; j++) {
9248                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9249                if (DEBUG_SHOW_INFO) {
9250                    Log.v(TAG, "    IntentFilter:");
9251                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9252                }
9253                removeFilter(intent);
9254            }
9255        }
9256
9257        @Override
9258        protected boolean allowFilterResult(
9259                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9260            ActivityInfo filterAi = filter.activity.info;
9261            for (int i=dest.size()-1; i>=0; i--) {
9262                ActivityInfo destAi = dest.get(i).activityInfo;
9263                if (destAi.name == filterAi.name
9264                        && destAi.packageName == filterAi.packageName) {
9265                    return false;
9266                }
9267            }
9268            return true;
9269        }
9270
9271        @Override
9272        protected ActivityIntentInfo[] newArray(int size) {
9273            return new ActivityIntentInfo[size];
9274        }
9275
9276        @Override
9277        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9278            if (!sUserManager.exists(userId)) return true;
9279            PackageParser.Package p = filter.activity.owner;
9280            if (p != null) {
9281                PackageSetting ps = (PackageSetting)p.mExtras;
9282                if (ps != null) {
9283                    // System apps are never considered stopped for purposes of
9284                    // filtering, because there may be no way for the user to
9285                    // actually re-launch them.
9286                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9287                            && ps.getStopped(userId);
9288                }
9289            }
9290            return false;
9291        }
9292
9293        @Override
9294        protected boolean isPackageForFilter(String packageName,
9295                PackageParser.ActivityIntentInfo info) {
9296            return packageName.equals(info.activity.owner.packageName);
9297        }
9298
9299        @Override
9300        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9301                int match, int userId) {
9302            if (!sUserManager.exists(userId)) return null;
9303            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9304                return null;
9305            }
9306            final PackageParser.Activity activity = info.activity;
9307            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9308            if (ps == null) {
9309                return null;
9310            }
9311            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9312                    ps.readUserState(userId), userId);
9313            if (ai == null) {
9314                return null;
9315            }
9316            final ResolveInfo res = new ResolveInfo();
9317            res.activityInfo = ai;
9318            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9319                res.filter = info;
9320            }
9321            if (info != null) {
9322                res.handleAllWebDataURI = info.handleAllWebDataURI();
9323            }
9324            res.priority = info.getPriority();
9325            res.preferredOrder = activity.owner.mPreferredOrder;
9326            //System.out.println("Result: " + res.activityInfo.className +
9327            //                   " = " + res.priority);
9328            res.match = match;
9329            res.isDefault = info.hasDefault;
9330            res.labelRes = info.labelRes;
9331            res.nonLocalizedLabel = info.nonLocalizedLabel;
9332            if (userNeedsBadging(userId)) {
9333                res.noResourceId = true;
9334            } else {
9335                res.icon = info.icon;
9336            }
9337            res.iconResourceId = info.icon;
9338            res.system = res.activityInfo.applicationInfo.isSystemApp();
9339            return res;
9340        }
9341
9342        @Override
9343        protected void sortResults(List<ResolveInfo> results) {
9344            Collections.sort(results, mResolvePrioritySorter);
9345        }
9346
9347        @Override
9348        protected void dumpFilter(PrintWriter out, String prefix,
9349                PackageParser.ActivityIntentInfo filter) {
9350            out.print(prefix); out.print(
9351                    Integer.toHexString(System.identityHashCode(filter.activity)));
9352                    out.print(' ');
9353                    filter.activity.printComponentShortName(out);
9354                    out.print(" filter ");
9355                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9356        }
9357
9358        @Override
9359        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9360            return filter.activity;
9361        }
9362
9363        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9364            PackageParser.Activity activity = (PackageParser.Activity)label;
9365            out.print(prefix); out.print(
9366                    Integer.toHexString(System.identityHashCode(activity)));
9367                    out.print(' ');
9368                    activity.printComponentShortName(out);
9369            if (count > 1) {
9370                out.print(" ("); out.print(count); out.print(" filters)");
9371            }
9372            out.println();
9373        }
9374
9375//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9376//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9377//            final List<ResolveInfo> retList = Lists.newArrayList();
9378//            while (i.hasNext()) {
9379//                final ResolveInfo resolveInfo = i.next();
9380//                if (isEnabledLP(resolveInfo.activityInfo)) {
9381//                    retList.add(resolveInfo);
9382//                }
9383//            }
9384//            return retList;
9385//        }
9386
9387        // Keys are String (activity class name), values are Activity.
9388        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9389                = new ArrayMap<ComponentName, PackageParser.Activity>();
9390        private int mFlags;
9391    }
9392
9393    private final class ServiceIntentResolver
9394            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9395        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9396                boolean defaultOnly, int userId) {
9397            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9398            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9399        }
9400
9401        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9402                int userId) {
9403            if (!sUserManager.exists(userId)) return null;
9404            mFlags = flags;
9405            return super.queryIntent(intent, resolvedType,
9406                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9407        }
9408
9409        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9410                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9411            if (!sUserManager.exists(userId)) return null;
9412            if (packageServices == null) {
9413                return null;
9414            }
9415            mFlags = flags;
9416            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9417            final int N = packageServices.size();
9418            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9419                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9420
9421            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9422            for (int i = 0; i < N; ++i) {
9423                intentFilters = packageServices.get(i).intents;
9424                if (intentFilters != null && intentFilters.size() > 0) {
9425                    PackageParser.ServiceIntentInfo[] array =
9426                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9427                    intentFilters.toArray(array);
9428                    listCut.add(array);
9429                }
9430            }
9431            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9432        }
9433
9434        public final void addService(PackageParser.Service s) {
9435            mServices.put(s.getComponentName(), s);
9436            if (DEBUG_SHOW_INFO) {
9437                Log.v(TAG, "  "
9438                        + (s.info.nonLocalizedLabel != null
9439                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9440                Log.v(TAG, "    Class=" + s.info.name);
9441            }
9442            final int NI = s.intents.size();
9443            int j;
9444            for (j=0; j<NI; j++) {
9445                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9446                if (DEBUG_SHOW_INFO) {
9447                    Log.v(TAG, "    IntentFilter:");
9448                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9449                }
9450                if (!intent.debugCheck()) {
9451                    Log.w(TAG, "==> For Service " + s.info.name);
9452                }
9453                addFilter(intent);
9454            }
9455        }
9456
9457        public final void removeService(PackageParser.Service s) {
9458            mServices.remove(s.getComponentName());
9459            if (DEBUG_SHOW_INFO) {
9460                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9461                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9462                Log.v(TAG, "    Class=" + s.info.name);
9463            }
9464            final int NI = s.intents.size();
9465            int j;
9466            for (j=0; j<NI; j++) {
9467                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9468                if (DEBUG_SHOW_INFO) {
9469                    Log.v(TAG, "    IntentFilter:");
9470                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9471                }
9472                removeFilter(intent);
9473            }
9474        }
9475
9476        @Override
9477        protected boolean allowFilterResult(
9478                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9479            ServiceInfo filterSi = filter.service.info;
9480            for (int i=dest.size()-1; i>=0; i--) {
9481                ServiceInfo destAi = dest.get(i).serviceInfo;
9482                if (destAi.name == filterSi.name
9483                        && destAi.packageName == filterSi.packageName) {
9484                    return false;
9485                }
9486            }
9487            return true;
9488        }
9489
9490        @Override
9491        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9492            return new PackageParser.ServiceIntentInfo[size];
9493        }
9494
9495        @Override
9496        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9497            if (!sUserManager.exists(userId)) return true;
9498            PackageParser.Package p = filter.service.owner;
9499            if (p != null) {
9500                PackageSetting ps = (PackageSetting)p.mExtras;
9501                if (ps != null) {
9502                    // System apps are never considered stopped for purposes of
9503                    // filtering, because there may be no way for the user to
9504                    // actually re-launch them.
9505                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9506                            && ps.getStopped(userId);
9507                }
9508            }
9509            return false;
9510        }
9511
9512        @Override
9513        protected boolean isPackageForFilter(String packageName,
9514                PackageParser.ServiceIntentInfo info) {
9515            return packageName.equals(info.service.owner.packageName);
9516        }
9517
9518        @Override
9519        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9520                int match, int userId) {
9521            if (!sUserManager.exists(userId)) return null;
9522            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9523            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9524                return null;
9525            }
9526            final PackageParser.Service service = info.service;
9527            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9528            if (ps == null) {
9529                return null;
9530            }
9531            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9532                    ps.readUserState(userId), userId);
9533            if (si == null) {
9534                return null;
9535            }
9536            final ResolveInfo res = new ResolveInfo();
9537            res.serviceInfo = si;
9538            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9539                res.filter = filter;
9540            }
9541            res.priority = info.getPriority();
9542            res.preferredOrder = service.owner.mPreferredOrder;
9543            res.match = match;
9544            res.isDefault = info.hasDefault;
9545            res.labelRes = info.labelRes;
9546            res.nonLocalizedLabel = info.nonLocalizedLabel;
9547            res.icon = info.icon;
9548            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9549            return res;
9550        }
9551
9552        @Override
9553        protected void sortResults(List<ResolveInfo> results) {
9554            Collections.sort(results, mResolvePrioritySorter);
9555        }
9556
9557        @Override
9558        protected void dumpFilter(PrintWriter out, String prefix,
9559                PackageParser.ServiceIntentInfo filter) {
9560            out.print(prefix); out.print(
9561                    Integer.toHexString(System.identityHashCode(filter.service)));
9562                    out.print(' ');
9563                    filter.service.printComponentShortName(out);
9564                    out.print(" filter ");
9565                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9566        }
9567
9568        @Override
9569        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9570            return filter.service;
9571        }
9572
9573        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9574            PackageParser.Service service = (PackageParser.Service)label;
9575            out.print(prefix); out.print(
9576                    Integer.toHexString(System.identityHashCode(service)));
9577                    out.print(' ');
9578                    service.printComponentShortName(out);
9579            if (count > 1) {
9580                out.print(" ("); out.print(count); out.print(" filters)");
9581            }
9582            out.println();
9583        }
9584
9585//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9586//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9587//            final List<ResolveInfo> retList = Lists.newArrayList();
9588//            while (i.hasNext()) {
9589//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9590//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9591//                    retList.add(resolveInfo);
9592//                }
9593//            }
9594//            return retList;
9595//        }
9596
9597        // Keys are String (activity class name), values are Activity.
9598        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9599                = new ArrayMap<ComponentName, PackageParser.Service>();
9600        private int mFlags;
9601    };
9602
9603    private final class ProviderIntentResolver
9604            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9605        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9606                boolean defaultOnly, int userId) {
9607            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9608            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9609        }
9610
9611        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9612                int userId) {
9613            if (!sUserManager.exists(userId))
9614                return null;
9615            mFlags = flags;
9616            return super.queryIntent(intent, resolvedType,
9617                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9618        }
9619
9620        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9621                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9622            if (!sUserManager.exists(userId))
9623                return null;
9624            if (packageProviders == null) {
9625                return null;
9626            }
9627            mFlags = flags;
9628            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9629            final int N = packageProviders.size();
9630            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9631                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9632
9633            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9634            for (int i = 0; i < N; ++i) {
9635                intentFilters = packageProviders.get(i).intents;
9636                if (intentFilters != null && intentFilters.size() > 0) {
9637                    PackageParser.ProviderIntentInfo[] array =
9638                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9639                    intentFilters.toArray(array);
9640                    listCut.add(array);
9641                }
9642            }
9643            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9644        }
9645
9646        public final void addProvider(PackageParser.Provider p) {
9647            if (mProviders.containsKey(p.getComponentName())) {
9648                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9649                return;
9650            }
9651
9652            mProviders.put(p.getComponentName(), p);
9653            if (DEBUG_SHOW_INFO) {
9654                Log.v(TAG, "  "
9655                        + (p.info.nonLocalizedLabel != null
9656                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9657                Log.v(TAG, "    Class=" + p.info.name);
9658            }
9659            final int NI = p.intents.size();
9660            int j;
9661            for (j = 0; j < NI; j++) {
9662                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9663                if (DEBUG_SHOW_INFO) {
9664                    Log.v(TAG, "    IntentFilter:");
9665                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9666                }
9667                if (!intent.debugCheck()) {
9668                    Log.w(TAG, "==> For Provider " + p.info.name);
9669                }
9670                addFilter(intent);
9671            }
9672        }
9673
9674        public final void removeProvider(PackageParser.Provider p) {
9675            mProviders.remove(p.getComponentName());
9676            if (DEBUG_SHOW_INFO) {
9677                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9678                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9679                Log.v(TAG, "    Class=" + p.info.name);
9680            }
9681            final int NI = p.intents.size();
9682            int j;
9683            for (j = 0; j < NI; j++) {
9684                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9685                if (DEBUG_SHOW_INFO) {
9686                    Log.v(TAG, "    IntentFilter:");
9687                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9688                }
9689                removeFilter(intent);
9690            }
9691        }
9692
9693        @Override
9694        protected boolean allowFilterResult(
9695                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9696            ProviderInfo filterPi = filter.provider.info;
9697            for (int i = dest.size() - 1; i >= 0; i--) {
9698                ProviderInfo destPi = dest.get(i).providerInfo;
9699                if (destPi.name == filterPi.name
9700                        && destPi.packageName == filterPi.packageName) {
9701                    return false;
9702                }
9703            }
9704            return true;
9705        }
9706
9707        @Override
9708        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9709            return new PackageParser.ProviderIntentInfo[size];
9710        }
9711
9712        @Override
9713        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9714            if (!sUserManager.exists(userId))
9715                return true;
9716            PackageParser.Package p = filter.provider.owner;
9717            if (p != null) {
9718                PackageSetting ps = (PackageSetting) p.mExtras;
9719                if (ps != null) {
9720                    // System apps are never considered stopped for purposes of
9721                    // filtering, because there may be no way for the user to
9722                    // actually re-launch them.
9723                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9724                            && ps.getStopped(userId);
9725                }
9726            }
9727            return false;
9728        }
9729
9730        @Override
9731        protected boolean isPackageForFilter(String packageName,
9732                PackageParser.ProviderIntentInfo info) {
9733            return packageName.equals(info.provider.owner.packageName);
9734        }
9735
9736        @Override
9737        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9738                int match, int userId) {
9739            if (!sUserManager.exists(userId))
9740                return null;
9741            final PackageParser.ProviderIntentInfo info = filter;
9742            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9743                return null;
9744            }
9745            final PackageParser.Provider provider = info.provider;
9746            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9747            if (ps == null) {
9748                return null;
9749            }
9750            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9751                    ps.readUserState(userId), userId);
9752            if (pi == null) {
9753                return null;
9754            }
9755            final ResolveInfo res = new ResolveInfo();
9756            res.providerInfo = pi;
9757            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9758                res.filter = filter;
9759            }
9760            res.priority = info.getPriority();
9761            res.preferredOrder = provider.owner.mPreferredOrder;
9762            res.match = match;
9763            res.isDefault = info.hasDefault;
9764            res.labelRes = info.labelRes;
9765            res.nonLocalizedLabel = info.nonLocalizedLabel;
9766            res.icon = info.icon;
9767            res.system = res.providerInfo.applicationInfo.isSystemApp();
9768            return res;
9769        }
9770
9771        @Override
9772        protected void sortResults(List<ResolveInfo> results) {
9773            Collections.sort(results, mResolvePrioritySorter);
9774        }
9775
9776        @Override
9777        protected void dumpFilter(PrintWriter out, String prefix,
9778                PackageParser.ProviderIntentInfo filter) {
9779            out.print(prefix);
9780            out.print(
9781                    Integer.toHexString(System.identityHashCode(filter.provider)));
9782            out.print(' ');
9783            filter.provider.printComponentShortName(out);
9784            out.print(" filter ");
9785            out.println(Integer.toHexString(System.identityHashCode(filter)));
9786        }
9787
9788        @Override
9789        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9790            return filter.provider;
9791        }
9792
9793        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9794            PackageParser.Provider provider = (PackageParser.Provider)label;
9795            out.print(prefix); out.print(
9796                    Integer.toHexString(System.identityHashCode(provider)));
9797                    out.print(' ');
9798                    provider.printComponentShortName(out);
9799            if (count > 1) {
9800                out.print(" ("); out.print(count); out.print(" filters)");
9801            }
9802            out.println();
9803        }
9804
9805        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9806                = new ArrayMap<ComponentName, PackageParser.Provider>();
9807        private int mFlags;
9808    }
9809
9810    private static final class EphemeralIntentResolver
9811            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9812        @Override
9813        protected EphemeralResolveIntentInfo[] newArray(int size) {
9814            return new EphemeralResolveIntentInfo[size];
9815        }
9816
9817        @Override
9818        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9819            return true;
9820        }
9821
9822        @Override
9823        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9824                int userId) {
9825            if (!sUserManager.exists(userId)) {
9826                return null;
9827            }
9828            return info.getEphemeralResolveInfo();
9829        }
9830    }
9831
9832    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9833            new Comparator<ResolveInfo>() {
9834        public int compare(ResolveInfo r1, ResolveInfo r2) {
9835            int v1 = r1.priority;
9836            int v2 = r2.priority;
9837            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9838            if (v1 != v2) {
9839                return (v1 > v2) ? -1 : 1;
9840            }
9841            v1 = r1.preferredOrder;
9842            v2 = r2.preferredOrder;
9843            if (v1 != v2) {
9844                return (v1 > v2) ? -1 : 1;
9845            }
9846            if (r1.isDefault != r2.isDefault) {
9847                return r1.isDefault ? -1 : 1;
9848            }
9849            v1 = r1.match;
9850            v2 = r2.match;
9851            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9852            if (v1 != v2) {
9853                return (v1 > v2) ? -1 : 1;
9854            }
9855            if (r1.system != r2.system) {
9856                return r1.system ? -1 : 1;
9857            }
9858            if (r1.activityInfo != null) {
9859                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9860            }
9861            if (r1.serviceInfo != null) {
9862                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9863            }
9864            if (r1.providerInfo != null) {
9865                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9866            }
9867            return 0;
9868        }
9869    };
9870
9871    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9872            new Comparator<ProviderInfo>() {
9873        public int compare(ProviderInfo p1, ProviderInfo p2) {
9874            final int v1 = p1.initOrder;
9875            final int v2 = p2.initOrder;
9876            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9877        }
9878    };
9879
9880    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9881            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9882            final int[] userIds) {
9883        mHandler.post(new Runnable() {
9884            @Override
9885            public void run() {
9886                try {
9887                    final IActivityManager am = ActivityManagerNative.getDefault();
9888                    if (am == null) return;
9889                    final int[] resolvedUserIds;
9890                    if (userIds == null) {
9891                        resolvedUserIds = am.getRunningUserIds();
9892                    } else {
9893                        resolvedUserIds = userIds;
9894                    }
9895                    for (int id : resolvedUserIds) {
9896                        final Intent intent = new Intent(action,
9897                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9898                        if (extras != null) {
9899                            intent.putExtras(extras);
9900                        }
9901                        if (targetPkg != null) {
9902                            intent.setPackage(targetPkg);
9903                        }
9904                        // Modify the UID when posting to other users
9905                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9906                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9907                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9908                            intent.putExtra(Intent.EXTRA_UID, uid);
9909                        }
9910                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9911                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9912                        if (DEBUG_BROADCASTS) {
9913                            RuntimeException here = new RuntimeException("here");
9914                            here.fillInStackTrace();
9915                            Slog.d(TAG, "Sending to user " + id + ": "
9916                                    + intent.toShortString(false, true, false, false)
9917                                    + " " + intent.getExtras(), here);
9918                        }
9919                        am.broadcastIntent(null, intent, null, finishedReceiver,
9920                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9921                                null, finishedReceiver != null, false, id);
9922                    }
9923                } catch (RemoteException ex) {
9924                }
9925            }
9926        });
9927    }
9928
9929    /**
9930     * Check if the external storage media is available. This is true if there
9931     * is a mounted external storage medium or if the external storage is
9932     * emulated.
9933     */
9934    private boolean isExternalMediaAvailable() {
9935        return mMediaMounted || Environment.isExternalStorageEmulated();
9936    }
9937
9938    @Override
9939    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9940        // writer
9941        synchronized (mPackages) {
9942            if (!isExternalMediaAvailable()) {
9943                // If the external storage is no longer mounted at this point,
9944                // the caller may not have been able to delete all of this
9945                // packages files and can not delete any more.  Bail.
9946                return null;
9947            }
9948            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9949            if (lastPackage != null) {
9950                pkgs.remove(lastPackage);
9951            }
9952            if (pkgs.size() > 0) {
9953                return pkgs.get(0);
9954            }
9955        }
9956        return null;
9957    }
9958
9959    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9960        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9961                userId, andCode ? 1 : 0, packageName);
9962        if (mSystemReady) {
9963            msg.sendToTarget();
9964        } else {
9965            if (mPostSystemReadyMessages == null) {
9966                mPostSystemReadyMessages = new ArrayList<>();
9967            }
9968            mPostSystemReadyMessages.add(msg);
9969        }
9970    }
9971
9972    void startCleaningPackages() {
9973        // reader
9974        synchronized (mPackages) {
9975            if (!isExternalMediaAvailable()) {
9976                return;
9977            }
9978            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9979                return;
9980            }
9981        }
9982        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9983        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9984        IActivityManager am = ActivityManagerNative.getDefault();
9985        if (am != null) {
9986            try {
9987                am.startService(null, intent, null, mContext.getOpPackageName(),
9988                        UserHandle.USER_SYSTEM);
9989            } catch (RemoteException e) {
9990            }
9991        }
9992    }
9993
9994    @Override
9995    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9996            int installFlags, String installerPackageName, VerificationParams verificationParams,
9997            String packageAbiOverride) {
9998        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9999                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10000    }
10001
10002    @Override
10003    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10004            int installFlags, String installerPackageName, VerificationParams verificationParams,
10005            String packageAbiOverride, int userId) {
10006        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10007
10008        final int callingUid = Binder.getCallingUid();
10009        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10010
10011        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10012            try {
10013                if (observer != null) {
10014                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10015                }
10016            } catch (RemoteException re) {
10017            }
10018            return;
10019        }
10020
10021        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10022            installFlags |= PackageManager.INSTALL_FROM_ADB;
10023
10024        } else {
10025            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10026            // about installerPackageName.
10027
10028            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10029            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10030        }
10031
10032        UserHandle user;
10033        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10034            user = UserHandle.ALL;
10035        } else {
10036            user = new UserHandle(userId);
10037        }
10038
10039        // Only system components can circumvent runtime permissions when installing.
10040        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10041                && mContext.checkCallingOrSelfPermission(Manifest.permission
10042                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10043            throw new SecurityException("You need the "
10044                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10045                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10046        }
10047
10048        verificationParams.setInstallerUid(callingUid);
10049
10050        final File originFile = new File(originPath);
10051        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10052
10053        final Message msg = mHandler.obtainMessage(INIT_COPY);
10054        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10055                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10056        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10057        msg.obj = params;
10058
10059        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10060                System.identityHashCode(msg.obj));
10061        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10062                System.identityHashCode(msg.obj));
10063
10064        mHandler.sendMessage(msg);
10065    }
10066
10067    void installStage(String packageName, File stagedDir, String stagedCid,
10068            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10069            String installerPackageName, int installerUid, UserHandle user) {
10070        if (DEBUG_EPHEMERAL) {
10071            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10072                Slog.d(TAG, "Ephemeral install of " + packageName);
10073            }
10074        }
10075        final VerificationParams verifParams = new VerificationParams(
10076                null, sessionParams.originatingUri, sessionParams.referrerUri,
10077                sessionParams.originatingUid);
10078        verifParams.setInstallerUid(installerUid);
10079
10080        final OriginInfo origin;
10081        if (stagedDir != null) {
10082            origin = OriginInfo.fromStagedFile(stagedDir);
10083        } else {
10084            origin = OriginInfo.fromStagedContainer(stagedCid);
10085        }
10086
10087        final Message msg = mHandler.obtainMessage(INIT_COPY);
10088        final InstallParams params = new InstallParams(origin, null, observer,
10089                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10090                verifParams, user, sessionParams.abiOverride,
10091                sessionParams.grantedRuntimePermissions);
10092        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10093        msg.obj = params;
10094
10095        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10096                System.identityHashCode(msg.obj));
10097        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10098                System.identityHashCode(msg.obj));
10099
10100        mHandler.sendMessage(msg);
10101    }
10102
10103    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10104        Bundle extras = new Bundle(1);
10105        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10106
10107        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10108                packageName, extras, 0, null, null, new int[] {userId});
10109        try {
10110            IActivityManager am = ActivityManagerNative.getDefault();
10111            final boolean isSystem =
10112                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10113            if (isSystem && am.isUserRunning(userId, 0)) {
10114                // The just-installed/enabled app is bundled on the system, so presumed
10115                // to be able to run automatically without needing an explicit launch.
10116                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10117                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10118                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10119                        .setPackage(packageName);
10120                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10121                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10122            }
10123        } catch (RemoteException e) {
10124            // shouldn't happen
10125            Slog.w(TAG, "Unable to bootstrap installed package", e);
10126        }
10127    }
10128
10129    @Override
10130    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10131            int userId) {
10132        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10133        PackageSetting pkgSetting;
10134        final int uid = Binder.getCallingUid();
10135        enforceCrossUserPermission(uid, userId, true, true,
10136                "setApplicationHiddenSetting for user " + userId);
10137
10138        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10139            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10140            return false;
10141        }
10142
10143        long callingId = Binder.clearCallingIdentity();
10144        try {
10145            boolean sendAdded = false;
10146            boolean sendRemoved = false;
10147            // writer
10148            synchronized (mPackages) {
10149                pkgSetting = mSettings.mPackages.get(packageName);
10150                if (pkgSetting == null) {
10151                    return false;
10152                }
10153                if (pkgSetting.getHidden(userId) != hidden) {
10154                    pkgSetting.setHidden(hidden, userId);
10155                    mSettings.writePackageRestrictionsLPr(userId);
10156                    if (hidden) {
10157                        sendRemoved = true;
10158                    } else {
10159                        sendAdded = true;
10160                    }
10161                }
10162            }
10163            if (sendAdded) {
10164                sendPackageAddedForUser(packageName, pkgSetting, userId);
10165                return true;
10166            }
10167            if (sendRemoved) {
10168                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10169                        "hiding pkg");
10170                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10171                return true;
10172            }
10173        } finally {
10174            Binder.restoreCallingIdentity(callingId);
10175        }
10176        return false;
10177    }
10178
10179    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10180            int userId) {
10181        final PackageRemovedInfo info = new PackageRemovedInfo();
10182        info.removedPackage = packageName;
10183        info.removedUsers = new int[] {userId};
10184        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10185        info.sendBroadcast(false, false, false);
10186    }
10187
10188    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10189        if (pkgList.length > 0) {
10190            Bundle extras = new Bundle(1);
10191            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10192
10193            sendPackageBroadcast(
10194                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10195                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10196                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10197                    new int[] {userId});
10198        }
10199    }
10200
10201    /**
10202     * Returns true if application is not found or there was an error. Otherwise it returns
10203     * the hidden state of the package for the given user.
10204     */
10205    @Override
10206    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10207        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10208        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10209                false, "getApplicationHidden for user " + userId);
10210        PackageSetting pkgSetting;
10211        long callingId = Binder.clearCallingIdentity();
10212        try {
10213            // writer
10214            synchronized (mPackages) {
10215                pkgSetting = mSettings.mPackages.get(packageName);
10216                if (pkgSetting == null) {
10217                    return true;
10218                }
10219                return pkgSetting.getHidden(userId);
10220            }
10221        } finally {
10222            Binder.restoreCallingIdentity(callingId);
10223        }
10224    }
10225
10226    /**
10227     * @hide
10228     */
10229    @Override
10230    public int installExistingPackageAsUser(String packageName, int userId) {
10231        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10232                null);
10233        PackageSetting pkgSetting;
10234        final int uid = Binder.getCallingUid();
10235        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10236                + userId);
10237        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10238            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10239        }
10240
10241        long callingId = Binder.clearCallingIdentity();
10242        try {
10243            boolean installed = false;
10244
10245            // writer
10246            synchronized (mPackages) {
10247                pkgSetting = mSettings.mPackages.get(packageName);
10248                if (pkgSetting == null) {
10249                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10250                }
10251                if (!pkgSetting.getInstalled(userId)) {
10252                    pkgSetting.setInstalled(true, userId);
10253                    pkgSetting.setHidden(false, userId);
10254                    mSettings.writePackageRestrictionsLPr(userId);
10255                    if (pkgSetting.pkg != null) {
10256                        prepareAppDataAfterInstall(pkgSetting.pkg);
10257                    }
10258                    installed = true;
10259                }
10260            }
10261
10262            if (installed) {
10263                sendPackageAddedForUser(packageName, pkgSetting, userId);
10264            }
10265        } finally {
10266            Binder.restoreCallingIdentity(callingId);
10267        }
10268
10269        return PackageManager.INSTALL_SUCCEEDED;
10270    }
10271
10272    boolean isUserRestricted(int userId, String restrictionKey) {
10273        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10274        if (restrictions.getBoolean(restrictionKey, false)) {
10275            Log.w(TAG, "User is restricted: " + restrictionKey);
10276            return true;
10277        }
10278        return false;
10279    }
10280
10281    @Override
10282    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10283        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10284        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10285                "setPackageSuspended for user " + userId);
10286
10287        // TODO: investigate and add more restrictions for suspending crucial packages.
10288        if (isPackageDeviceAdmin(packageName, userId)) {
10289            Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName
10290                    + "\": has active device admin");
10291            return false;
10292        }
10293
10294        long callingId = Binder.clearCallingIdentity();
10295        try {
10296            boolean changed = false;
10297            boolean success = false;
10298            int appId = -1;
10299            synchronized (mPackages) {
10300                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10301                if (pkgSetting != null) {
10302                    if (pkgSetting.getSuspended(userId) != suspended) {
10303                        pkgSetting.setSuspended(suspended, userId);
10304                        mSettings.writePackageRestrictionsLPr(userId);
10305                        appId = pkgSetting.appId;
10306                        changed = true;
10307                    }
10308                    success = true;
10309                }
10310            }
10311
10312            if (changed) {
10313                sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended);
10314                if (suspended) {
10315                    killApplication(packageName, UserHandle.getUid(userId, appId),
10316                            "suspending package");
10317                }
10318            }
10319            return success;
10320        } finally {
10321            Binder.restoreCallingIdentity(callingId);
10322        }
10323    }
10324
10325    @Override
10326    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10327        mContext.enforceCallingOrSelfPermission(
10328                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10329                "Only package verification agents can verify applications");
10330
10331        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10332        final PackageVerificationResponse response = new PackageVerificationResponse(
10333                verificationCode, Binder.getCallingUid());
10334        msg.arg1 = id;
10335        msg.obj = response;
10336        mHandler.sendMessage(msg);
10337    }
10338
10339    @Override
10340    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10341            long millisecondsToDelay) {
10342        mContext.enforceCallingOrSelfPermission(
10343                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10344                "Only package verification agents can extend verification timeouts");
10345
10346        final PackageVerificationState state = mPendingVerification.get(id);
10347        final PackageVerificationResponse response = new PackageVerificationResponse(
10348                verificationCodeAtTimeout, Binder.getCallingUid());
10349
10350        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10351            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10352        }
10353        if (millisecondsToDelay < 0) {
10354            millisecondsToDelay = 0;
10355        }
10356        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10357                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10358            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10359        }
10360
10361        if ((state != null) && !state.timeoutExtended()) {
10362            state.extendTimeout();
10363
10364            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10365            msg.arg1 = id;
10366            msg.obj = response;
10367            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10368        }
10369    }
10370
10371    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10372            int verificationCode, UserHandle user) {
10373        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10374        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10375        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10376        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10377        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10378
10379        mContext.sendBroadcastAsUser(intent, user,
10380                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10381    }
10382
10383    private ComponentName matchComponentForVerifier(String packageName,
10384            List<ResolveInfo> receivers) {
10385        ActivityInfo targetReceiver = null;
10386
10387        final int NR = receivers.size();
10388        for (int i = 0; i < NR; i++) {
10389            final ResolveInfo info = receivers.get(i);
10390            if (info.activityInfo == null) {
10391                continue;
10392            }
10393
10394            if (packageName.equals(info.activityInfo.packageName)) {
10395                targetReceiver = info.activityInfo;
10396                break;
10397            }
10398        }
10399
10400        if (targetReceiver == null) {
10401            return null;
10402        }
10403
10404        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10405    }
10406
10407    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10408            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10409        if (pkgInfo.verifiers.length == 0) {
10410            return null;
10411        }
10412
10413        final int N = pkgInfo.verifiers.length;
10414        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10415        for (int i = 0; i < N; i++) {
10416            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10417
10418            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10419                    receivers);
10420            if (comp == null) {
10421                continue;
10422            }
10423
10424            final int verifierUid = getUidForVerifier(verifierInfo);
10425            if (verifierUid == -1) {
10426                continue;
10427            }
10428
10429            if (DEBUG_VERIFY) {
10430                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10431                        + " with the correct signature");
10432            }
10433            sufficientVerifiers.add(comp);
10434            verificationState.addSufficientVerifier(verifierUid);
10435        }
10436
10437        return sufficientVerifiers;
10438    }
10439
10440    private int getUidForVerifier(VerifierInfo verifierInfo) {
10441        synchronized (mPackages) {
10442            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10443            if (pkg == null) {
10444                return -1;
10445            } else if (pkg.mSignatures.length != 1) {
10446                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10447                        + " has more than one signature; ignoring");
10448                return -1;
10449            }
10450
10451            /*
10452             * If the public key of the package's signature does not match
10453             * our expected public key, then this is a different package and
10454             * we should skip.
10455             */
10456
10457            final byte[] expectedPublicKey;
10458            try {
10459                final Signature verifierSig = pkg.mSignatures[0];
10460                final PublicKey publicKey = verifierSig.getPublicKey();
10461                expectedPublicKey = publicKey.getEncoded();
10462            } catch (CertificateException e) {
10463                return -1;
10464            }
10465
10466            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10467
10468            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10469                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10470                        + " does not have the expected public key; ignoring");
10471                return -1;
10472            }
10473
10474            return pkg.applicationInfo.uid;
10475        }
10476    }
10477
10478    @Override
10479    public void finishPackageInstall(int token) {
10480        enforceSystemOrRoot("Only the system is allowed to finish installs");
10481
10482        if (DEBUG_INSTALL) {
10483            Slog.v(TAG, "BM finishing package install for " + token);
10484        }
10485        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10486
10487        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10488        mHandler.sendMessage(msg);
10489    }
10490
10491    /**
10492     * Get the verification agent timeout.
10493     *
10494     * @return verification timeout in milliseconds
10495     */
10496    private long getVerificationTimeout() {
10497        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10498                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10499                DEFAULT_VERIFICATION_TIMEOUT);
10500    }
10501
10502    /**
10503     * Get the default verification agent response code.
10504     *
10505     * @return default verification response code
10506     */
10507    private int getDefaultVerificationResponse() {
10508        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10509                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10510                DEFAULT_VERIFICATION_RESPONSE);
10511    }
10512
10513    /**
10514     * Check whether or not package verification has been enabled.
10515     *
10516     * @return true if verification should be performed
10517     */
10518    private boolean isVerificationEnabled(int userId, int installFlags) {
10519        if (!DEFAULT_VERIFY_ENABLE) {
10520            return false;
10521        }
10522        // Ephemeral apps don't get the full verification treatment
10523        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10524            if (DEBUG_EPHEMERAL) {
10525                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10526            }
10527            return false;
10528        }
10529
10530        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10531
10532        // Check if installing from ADB
10533        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10534            // Do not run verification in a test harness environment
10535            if (ActivityManager.isRunningInTestHarness()) {
10536                return false;
10537            }
10538            if (ensureVerifyAppsEnabled) {
10539                return true;
10540            }
10541            // Check if the developer does not want package verification for ADB installs
10542            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10543                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10544                return false;
10545            }
10546        }
10547
10548        if (ensureVerifyAppsEnabled) {
10549            return true;
10550        }
10551
10552        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10553                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10554    }
10555
10556    @Override
10557    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10558            throws RemoteException {
10559        mContext.enforceCallingOrSelfPermission(
10560                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10561                "Only intentfilter verification agents can verify applications");
10562
10563        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10564        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10565                Binder.getCallingUid(), verificationCode, failedDomains);
10566        msg.arg1 = id;
10567        msg.obj = response;
10568        mHandler.sendMessage(msg);
10569    }
10570
10571    @Override
10572    public int getIntentVerificationStatus(String packageName, int userId) {
10573        synchronized (mPackages) {
10574            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10575        }
10576    }
10577
10578    @Override
10579    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10580        mContext.enforceCallingOrSelfPermission(
10581                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10582
10583        boolean result = false;
10584        synchronized (mPackages) {
10585            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10586        }
10587        if (result) {
10588            scheduleWritePackageRestrictionsLocked(userId);
10589        }
10590        return result;
10591    }
10592
10593    @Override
10594    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10595        synchronized (mPackages) {
10596            return mSettings.getIntentFilterVerificationsLPr(packageName);
10597        }
10598    }
10599
10600    @Override
10601    public List<IntentFilter> getAllIntentFilters(String packageName) {
10602        if (TextUtils.isEmpty(packageName)) {
10603            return Collections.<IntentFilter>emptyList();
10604        }
10605        synchronized (mPackages) {
10606            PackageParser.Package pkg = mPackages.get(packageName);
10607            if (pkg == null || pkg.activities == null) {
10608                return Collections.<IntentFilter>emptyList();
10609            }
10610            final int count = pkg.activities.size();
10611            ArrayList<IntentFilter> result = new ArrayList<>();
10612            for (int n=0; n<count; n++) {
10613                PackageParser.Activity activity = pkg.activities.get(n);
10614                if (activity.intents != null && activity.intents.size() > 0) {
10615                    result.addAll(activity.intents);
10616                }
10617            }
10618            return result;
10619        }
10620    }
10621
10622    @Override
10623    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10624        mContext.enforceCallingOrSelfPermission(
10625                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10626
10627        synchronized (mPackages) {
10628            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10629            if (packageName != null) {
10630                result |= updateIntentVerificationStatus(packageName,
10631                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10632                        userId);
10633                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10634                        packageName, userId);
10635            }
10636            return result;
10637        }
10638    }
10639
10640    @Override
10641    public String getDefaultBrowserPackageName(int userId) {
10642        synchronized (mPackages) {
10643            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10644        }
10645    }
10646
10647    /**
10648     * Get the "allow unknown sources" setting.
10649     *
10650     * @return the current "allow unknown sources" setting
10651     */
10652    private int getUnknownSourcesSettings() {
10653        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10654                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10655                -1);
10656    }
10657
10658    @Override
10659    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10660        final int uid = Binder.getCallingUid();
10661        // writer
10662        synchronized (mPackages) {
10663            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10664            if (targetPackageSetting == null) {
10665                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10666            }
10667
10668            PackageSetting installerPackageSetting;
10669            if (installerPackageName != null) {
10670                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10671                if (installerPackageSetting == null) {
10672                    throw new IllegalArgumentException("Unknown installer package: "
10673                            + installerPackageName);
10674                }
10675            } else {
10676                installerPackageSetting = null;
10677            }
10678
10679            Signature[] callerSignature;
10680            Object obj = mSettings.getUserIdLPr(uid);
10681            if (obj != null) {
10682                if (obj instanceof SharedUserSetting) {
10683                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10684                } else if (obj instanceof PackageSetting) {
10685                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10686                } else {
10687                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10688                }
10689            } else {
10690                throw new SecurityException("Unknown calling UID: " + uid);
10691            }
10692
10693            // Verify: can't set installerPackageName to a package that is
10694            // not signed with the same cert as the caller.
10695            if (installerPackageSetting != null) {
10696                if (compareSignatures(callerSignature,
10697                        installerPackageSetting.signatures.mSignatures)
10698                        != PackageManager.SIGNATURE_MATCH) {
10699                    throw new SecurityException(
10700                            "Caller does not have same cert as new installer package "
10701                            + installerPackageName);
10702                }
10703            }
10704
10705            // Verify: if target already has an installer package, it must
10706            // be signed with the same cert as the caller.
10707            if (targetPackageSetting.installerPackageName != null) {
10708                PackageSetting setting = mSettings.mPackages.get(
10709                        targetPackageSetting.installerPackageName);
10710                // If the currently set package isn't valid, then it's always
10711                // okay to change it.
10712                if (setting != null) {
10713                    if (compareSignatures(callerSignature,
10714                            setting.signatures.mSignatures)
10715                            != PackageManager.SIGNATURE_MATCH) {
10716                        throw new SecurityException(
10717                                "Caller does not have same cert as old installer package "
10718                                + targetPackageSetting.installerPackageName);
10719                    }
10720                }
10721            }
10722
10723            // Okay!
10724            targetPackageSetting.installerPackageName = installerPackageName;
10725            scheduleWriteSettingsLocked();
10726        }
10727    }
10728
10729    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10730        // Queue up an async operation since the package installation may take a little while.
10731        mHandler.post(new Runnable() {
10732            public void run() {
10733                mHandler.removeCallbacks(this);
10734                 // Result object to be returned
10735                PackageInstalledInfo res = new PackageInstalledInfo();
10736                res.returnCode = currentStatus;
10737                res.uid = -1;
10738                res.pkg = null;
10739                res.removedInfo = new PackageRemovedInfo();
10740                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10741                    args.doPreInstall(res.returnCode);
10742                    synchronized (mInstallLock) {
10743                        installPackageTracedLI(args, res);
10744                    }
10745                    args.doPostInstall(res.returnCode, res.uid);
10746                }
10747
10748                // A restore should be performed at this point if (a) the install
10749                // succeeded, (b) the operation is not an update, and (c) the new
10750                // package has not opted out of backup participation.
10751                final boolean update = res.removedInfo.removedPackage != null;
10752                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10753                boolean doRestore = !update
10754                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10755
10756                // Set up the post-install work request bookkeeping.  This will be used
10757                // and cleaned up by the post-install event handling regardless of whether
10758                // there's a restore pass performed.  Token values are >= 1.
10759                int token;
10760                if (mNextInstallToken < 0) mNextInstallToken = 1;
10761                token = mNextInstallToken++;
10762
10763                PostInstallData data = new PostInstallData(args, res);
10764                mRunningInstalls.put(token, data);
10765                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10766
10767                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10768                    // Pass responsibility to the Backup Manager.  It will perform a
10769                    // restore if appropriate, then pass responsibility back to the
10770                    // Package Manager to run the post-install observer callbacks
10771                    // and broadcasts.
10772                    IBackupManager bm = IBackupManager.Stub.asInterface(
10773                            ServiceManager.getService(Context.BACKUP_SERVICE));
10774                    if (bm != null) {
10775                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10776                                + " to BM for possible restore");
10777                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10778                        try {
10779                            // TODO: http://b/22388012
10780                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10781                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10782                            } else {
10783                                doRestore = false;
10784                            }
10785                        } catch (RemoteException e) {
10786                            // can't happen; the backup manager is local
10787                        } catch (Exception e) {
10788                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10789                            doRestore = false;
10790                        }
10791                    } else {
10792                        Slog.e(TAG, "Backup Manager not found!");
10793                        doRestore = false;
10794                    }
10795                }
10796
10797                if (!doRestore) {
10798                    // No restore possible, or the Backup Manager was mysteriously not
10799                    // available -- just fire the post-install work request directly.
10800                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10801
10802                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10803
10804                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10805                    mHandler.sendMessage(msg);
10806                }
10807            }
10808        });
10809    }
10810
10811    private abstract class HandlerParams {
10812        private static final int MAX_RETRIES = 4;
10813
10814        /**
10815         * Number of times startCopy() has been attempted and had a non-fatal
10816         * error.
10817         */
10818        private int mRetries = 0;
10819
10820        /** User handle for the user requesting the information or installation. */
10821        private final UserHandle mUser;
10822        String traceMethod;
10823        int traceCookie;
10824
10825        HandlerParams(UserHandle user) {
10826            mUser = user;
10827        }
10828
10829        UserHandle getUser() {
10830            return mUser;
10831        }
10832
10833        HandlerParams setTraceMethod(String traceMethod) {
10834            this.traceMethod = traceMethod;
10835            return this;
10836        }
10837
10838        HandlerParams setTraceCookie(int traceCookie) {
10839            this.traceCookie = traceCookie;
10840            return this;
10841        }
10842
10843        final boolean startCopy() {
10844            boolean res;
10845            try {
10846                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10847
10848                if (++mRetries > MAX_RETRIES) {
10849                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10850                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10851                    handleServiceError();
10852                    return false;
10853                } else {
10854                    handleStartCopy();
10855                    res = true;
10856                }
10857            } catch (RemoteException e) {
10858                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10859                mHandler.sendEmptyMessage(MCS_RECONNECT);
10860                res = false;
10861            }
10862            handleReturnCode();
10863            return res;
10864        }
10865
10866        final void serviceError() {
10867            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10868            handleServiceError();
10869            handleReturnCode();
10870        }
10871
10872        abstract void handleStartCopy() throws RemoteException;
10873        abstract void handleServiceError();
10874        abstract void handleReturnCode();
10875    }
10876
10877    class MeasureParams extends HandlerParams {
10878        private final PackageStats mStats;
10879        private boolean mSuccess;
10880
10881        private final IPackageStatsObserver mObserver;
10882
10883        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10884            super(new UserHandle(stats.userHandle));
10885            mObserver = observer;
10886            mStats = stats;
10887        }
10888
10889        @Override
10890        public String toString() {
10891            return "MeasureParams{"
10892                + Integer.toHexString(System.identityHashCode(this))
10893                + " " + mStats.packageName + "}";
10894        }
10895
10896        @Override
10897        void handleStartCopy() throws RemoteException {
10898            synchronized (mInstallLock) {
10899                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10900            }
10901
10902            if (mSuccess) {
10903                final boolean mounted;
10904                if (Environment.isExternalStorageEmulated()) {
10905                    mounted = true;
10906                } else {
10907                    final String status = Environment.getExternalStorageState();
10908                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10909                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10910                }
10911
10912                if (mounted) {
10913                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10914
10915                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10916                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10917
10918                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10919                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10920
10921                    // Always subtract cache size, since it's a subdirectory
10922                    mStats.externalDataSize -= mStats.externalCacheSize;
10923
10924                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10925                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10926
10927                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10928                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10929                }
10930            }
10931        }
10932
10933        @Override
10934        void handleReturnCode() {
10935            if (mObserver != null) {
10936                try {
10937                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10938                } catch (RemoteException e) {
10939                    Slog.i(TAG, "Observer no longer exists.");
10940                }
10941            }
10942        }
10943
10944        @Override
10945        void handleServiceError() {
10946            Slog.e(TAG, "Could not measure application " + mStats.packageName
10947                            + " external storage");
10948        }
10949    }
10950
10951    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10952            throws RemoteException {
10953        long result = 0;
10954        for (File path : paths) {
10955            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10956        }
10957        return result;
10958    }
10959
10960    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10961        for (File path : paths) {
10962            try {
10963                mcs.clearDirectory(path.getAbsolutePath());
10964            } catch (RemoteException e) {
10965            }
10966        }
10967    }
10968
10969    static class OriginInfo {
10970        /**
10971         * Location where install is coming from, before it has been
10972         * copied/renamed into place. This could be a single monolithic APK
10973         * file, or a cluster directory. This location may be untrusted.
10974         */
10975        final File file;
10976        final String cid;
10977
10978        /**
10979         * Flag indicating that {@link #file} or {@link #cid} has already been
10980         * staged, meaning downstream users don't need to defensively copy the
10981         * contents.
10982         */
10983        final boolean staged;
10984
10985        /**
10986         * Flag indicating that {@link #file} or {@link #cid} is an already
10987         * installed app that is being moved.
10988         */
10989        final boolean existing;
10990
10991        final String resolvedPath;
10992        final File resolvedFile;
10993
10994        static OriginInfo fromNothing() {
10995            return new OriginInfo(null, null, false, false);
10996        }
10997
10998        static OriginInfo fromUntrustedFile(File file) {
10999            return new OriginInfo(file, null, false, false);
11000        }
11001
11002        static OriginInfo fromExistingFile(File file) {
11003            return new OriginInfo(file, null, false, true);
11004        }
11005
11006        static OriginInfo fromStagedFile(File file) {
11007            return new OriginInfo(file, null, true, false);
11008        }
11009
11010        static OriginInfo fromStagedContainer(String cid) {
11011            return new OriginInfo(null, cid, true, false);
11012        }
11013
11014        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11015            this.file = file;
11016            this.cid = cid;
11017            this.staged = staged;
11018            this.existing = existing;
11019
11020            if (cid != null) {
11021                resolvedPath = PackageHelper.getSdDir(cid);
11022                resolvedFile = new File(resolvedPath);
11023            } else if (file != null) {
11024                resolvedPath = file.getAbsolutePath();
11025                resolvedFile = file;
11026            } else {
11027                resolvedPath = null;
11028                resolvedFile = null;
11029            }
11030        }
11031    }
11032
11033    static class MoveInfo {
11034        final int moveId;
11035        final String fromUuid;
11036        final String toUuid;
11037        final String packageName;
11038        final String dataAppName;
11039        final int appId;
11040        final String seinfo;
11041        final int targetSdkVersion;
11042
11043        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11044                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11045            this.moveId = moveId;
11046            this.fromUuid = fromUuid;
11047            this.toUuid = toUuid;
11048            this.packageName = packageName;
11049            this.dataAppName = dataAppName;
11050            this.appId = appId;
11051            this.seinfo = seinfo;
11052            this.targetSdkVersion = targetSdkVersion;
11053        }
11054    }
11055
11056    class InstallParams extends HandlerParams {
11057        final OriginInfo origin;
11058        final MoveInfo move;
11059        final IPackageInstallObserver2 observer;
11060        int installFlags;
11061        final String installerPackageName;
11062        final String volumeUuid;
11063        final VerificationParams verificationParams;
11064        private InstallArgs mArgs;
11065        private int mRet;
11066        final String packageAbiOverride;
11067        final String[] grantedRuntimePermissions;
11068
11069        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11070                int installFlags, String installerPackageName, String volumeUuid,
11071                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11072                String[] grantedPermissions) {
11073            super(user);
11074            this.origin = origin;
11075            this.move = move;
11076            this.observer = observer;
11077            this.installFlags = installFlags;
11078            this.installerPackageName = installerPackageName;
11079            this.volumeUuid = volumeUuid;
11080            this.verificationParams = verificationParams;
11081            this.packageAbiOverride = packageAbiOverride;
11082            this.grantedRuntimePermissions = grantedPermissions;
11083        }
11084
11085        @Override
11086        public String toString() {
11087            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11088                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11089        }
11090
11091        private int installLocationPolicy(PackageInfoLite pkgLite) {
11092            String packageName = pkgLite.packageName;
11093            int installLocation = pkgLite.installLocation;
11094            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11095            // reader
11096            synchronized (mPackages) {
11097                PackageParser.Package pkg = mPackages.get(packageName);
11098                if (pkg != null) {
11099                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11100                        // Check for downgrading.
11101                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11102                            try {
11103                                checkDowngrade(pkg, pkgLite);
11104                            } catch (PackageManagerException e) {
11105                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11106                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11107                            }
11108                        }
11109                        // Check for updated system application.
11110                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11111                            if (onSd) {
11112                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11113                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11114                            }
11115                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11116                        } else {
11117                            if (onSd) {
11118                                // Install flag overrides everything.
11119                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11120                            }
11121                            // If current upgrade specifies particular preference
11122                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11123                                // Application explicitly specified internal.
11124                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11125                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11126                                // App explictly prefers external. Let policy decide
11127                            } else {
11128                                // Prefer previous location
11129                                if (isExternal(pkg)) {
11130                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11131                                }
11132                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11133                            }
11134                        }
11135                    } else {
11136                        // Invalid install. Return error code
11137                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11138                    }
11139                }
11140            }
11141            // All the special cases have been taken care of.
11142            // Return result based on recommended install location.
11143            if (onSd) {
11144                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11145            }
11146            return pkgLite.recommendedInstallLocation;
11147        }
11148
11149        /*
11150         * Invoke remote method to get package information and install
11151         * location values. Override install location based on default
11152         * policy if needed and then create install arguments based
11153         * on the install location.
11154         */
11155        public void handleStartCopy() throws RemoteException {
11156            int ret = PackageManager.INSTALL_SUCCEEDED;
11157
11158            // If we're already staged, we've firmly committed to an install location
11159            if (origin.staged) {
11160                if (origin.file != null) {
11161                    installFlags |= PackageManager.INSTALL_INTERNAL;
11162                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11163                } else if (origin.cid != null) {
11164                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11165                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11166                } else {
11167                    throw new IllegalStateException("Invalid stage location");
11168                }
11169            }
11170
11171            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11172            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11173            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11174            PackageInfoLite pkgLite = null;
11175
11176            if (onInt && onSd) {
11177                // Check if both bits are set.
11178                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11179                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11180            } else if (onSd && ephemeral) {
11181                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11182                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11183            } else {
11184                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11185                        packageAbiOverride);
11186
11187                if (DEBUG_EPHEMERAL && ephemeral) {
11188                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11189                }
11190
11191                /*
11192                 * If we have too little free space, try to free cache
11193                 * before giving up.
11194                 */
11195                if (!origin.staged && pkgLite.recommendedInstallLocation
11196                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11197                    // TODO: focus freeing disk space on the target device
11198                    final StorageManager storage = StorageManager.from(mContext);
11199                    final long lowThreshold = storage.getStorageLowBytes(
11200                            Environment.getDataDirectory());
11201
11202                    final long sizeBytes = mContainerService.calculateInstalledSize(
11203                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11204
11205                    try {
11206                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11207                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11208                                installFlags, packageAbiOverride);
11209                    } catch (InstallerException e) {
11210                        Slog.w(TAG, "Failed to free cache", e);
11211                    }
11212
11213                    /*
11214                     * The cache free must have deleted the file we
11215                     * downloaded to install.
11216                     *
11217                     * TODO: fix the "freeCache" call to not delete
11218                     *       the file we care about.
11219                     */
11220                    if (pkgLite.recommendedInstallLocation
11221                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11222                        pkgLite.recommendedInstallLocation
11223                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11224                    }
11225                }
11226            }
11227
11228            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11229                int loc = pkgLite.recommendedInstallLocation;
11230                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11231                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11232                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11233                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11234                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11235                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11236                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11237                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11238                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11239                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11240                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11241                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11242                } else {
11243                    // Override with defaults if needed.
11244                    loc = installLocationPolicy(pkgLite);
11245                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11246                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11247                    } else if (!onSd && !onInt) {
11248                        // Override install location with flags
11249                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11250                            // Set the flag to install on external media.
11251                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11252                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11253                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11254                            if (DEBUG_EPHEMERAL) {
11255                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11256                            }
11257                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11258                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11259                                    |PackageManager.INSTALL_INTERNAL);
11260                        } else {
11261                            // Make sure the flag for installing on external
11262                            // media is unset
11263                            installFlags |= PackageManager.INSTALL_INTERNAL;
11264                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11265                        }
11266                    }
11267                }
11268            }
11269
11270            final InstallArgs args = createInstallArgs(this);
11271            mArgs = args;
11272
11273            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11274                // TODO: http://b/22976637
11275                // Apps installed for "all" users use the device owner to verify the app
11276                UserHandle verifierUser = getUser();
11277                if (verifierUser == UserHandle.ALL) {
11278                    verifierUser = UserHandle.SYSTEM;
11279                }
11280
11281                /*
11282                 * Determine if we have any installed package verifiers. If we
11283                 * do, then we'll defer to them to verify the packages.
11284                 */
11285                final int requiredUid = mRequiredVerifierPackage == null ? -1
11286                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11287                                verifierUser.getIdentifier());
11288                if (!origin.existing && requiredUid != -1
11289                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11290                    final Intent verification = new Intent(
11291                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11292                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11293                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11294                            PACKAGE_MIME_TYPE);
11295                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11296
11297                    // Query all live verifiers based on current user state
11298                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11299                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11300
11301                    if (DEBUG_VERIFY) {
11302                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11303                                + verification.toString() + " with " + pkgLite.verifiers.length
11304                                + " optional verifiers");
11305                    }
11306
11307                    final int verificationId = mPendingVerificationToken++;
11308
11309                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11310
11311                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11312                            installerPackageName);
11313
11314                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11315                            installFlags);
11316
11317                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11318                            pkgLite.packageName);
11319
11320                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11321                            pkgLite.versionCode);
11322
11323                    if (verificationParams != null) {
11324                        if (verificationParams.getVerificationURI() != null) {
11325                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11326                                 verificationParams.getVerificationURI());
11327                        }
11328                        if (verificationParams.getOriginatingURI() != null) {
11329                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11330                                  verificationParams.getOriginatingURI());
11331                        }
11332                        if (verificationParams.getReferrer() != null) {
11333                            verification.putExtra(Intent.EXTRA_REFERRER,
11334                                  verificationParams.getReferrer());
11335                        }
11336                        if (verificationParams.getOriginatingUid() >= 0) {
11337                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11338                                  verificationParams.getOriginatingUid());
11339                        }
11340                        if (verificationParams.getInstallerUid() >= 0) {
11341                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11342                                  verificationParams.getInstallerUid());
11343                        }
11344                    }
11345
11346                    final PackageVerificationState verificationState = new PackageVerificationState(
11347                            requiredUid, args);
11348
11349                    mPendingVerification.append(verificationId, verificationState);
11350
11351                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11352                            receivers, verificationState);
11353
11354                    /*
11355                     * If any sufficient verifiers were listed in the package
11356                     * manifest, attempt to ask them.
11357                     */
11358                    if (sufficientVerifiers != null) {
11359                        final int N = sufficientVerifiers.size();
11360                        if (N == 0) {
11361                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11362                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11363                        } else {
11364                            for (int i = 0; i < N; i++) {
11365                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11366
11367                                final Intent sufficientIntent = new Intent(verification);
11368                                sufficientIntent.setComponent(verifierComponent);
11369                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11370                            }
11371                        }
11372                    }
11373
11374                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11375                            mRequiredVerifierPackage, receivers);
11376                    if (ret == PackageManager.INSTALL_SUCCEEDED
11377                            && mRequiredVerifierPackage != null) {
11378                        Trace.asyncTraceBegin(
11379                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11380                        /*
11381                         * Send the intent to the required verification agent,
11382                         * but only start the verification timeout after the
11383                         * target BroadcastReceivers have run.
11384                         */
11385                        verification.setComponent(requiredVerifierComponent);
11386                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11387                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11388                                new BroadcastReceiver() {
11389                                    @Override
11390                                    public void onReceive(Context context, Intent intent) {
11391                                        final Message msg = mHandler
11392                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11393                                        msg.arg1 = verificationId;
11394                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11395                                    }
11396                                }, null, 0, null, null);
11397
11398                        /*
11399                         * We don't want the copy to proceed until verification
11400                         * succeeds, so null out this field.
11401                         */
11402                        mArgs = null;
11403                    }
11404                } else {
11405                    /*
11406                     * No package verification is enabled, so immediately start
11407                     * the remote call to initiate copy using temporary file.
11408                     */
11409                    ret = args.copyApk(mContainerService, true);
11410                }
11411            }
11412
11413            mRet = ret;
11414        }
11415
11416        @Override
11417        void handleReturnCode() {
11418            // If mArgs is null, then MCS couldn't be reached. When it
11419            // reconnects, it will try again to install. At that point, this
11420            // will succeed.
11421            if (mArgs != null) {
11422                processPendingInstall(mArgs, mRet);
11423            }
11424        }
11425
11426        @Override
11427        void handleServiceError() {
11428            mArgs = createInstallArgs(this);
11429            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11430        }
11431
11432        public boolean isForwardLocked() {
11433            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11434        }
11435    }
11436
11437    /**
11438     * Used during creation of InstallArgs
11439     *
11440     * @param installFlags package installation flags
11441     * @return true if should be installed on external storage
11442     */
11443    private static boolean installOnExternalAsec(int installFlags) {
11444        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11445            return false;
11446        }
11447        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11448            return true;
11449        }
11450        return false;
11451    }
11452
11453    /**
11454     * Used during creation of InstallArgs
11455     *
11456     * @param installFlags package installation flags
11457     * @return true if should be installed as forward locked
11458     */
11459    private static boolean installForwardLocked(int installFlags) {
11460        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11461    }
11462
11463    private InstallArgs createInstallArgs(InstallParams params) {
11464        if (params.move != null) {
11465            return new MoveInstallArgs(params);
11466        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11467            return new AsecInstallArgs(params);
11468        } else {
11469            return new FileInstallArgs(params);
11470        }
11471    }
11472
11473    /**
11474     * Create args that describe an existing installed package. Typically used
11475     * when cleaning up old installs, or used as a move source.
11476     */
11477    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11478            String resourcePath, String[] instructionSets) {
11479        final boolean isInAsec;
11480        if (installOnExternalAsec(installFlags)) {
11481            /* Apps on SD card are always in ASEC containers. */
11482            isInAsec = true;
11483        } else if (installForwardLocked(installFlags)
11484                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11485            /*
11486             * Forward-locked apps are only in ASEC containers if they're the
11487             * new style
11488             */
11489            isInAsec = true;
11490        } else {
11491            isInAsec = false;
11492        }
11493
11494        if (isInAsec) {
11495            return new AsecInstallArgs(codePath, instructionSets,
11496                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11497        } else {
11498            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11499        }
11500    }
11501
11502    static abstract class InstallArgs {
11503        /** @see InstallParams#origin */
11504        final OriginInfo origin;
11505        /** @see InstallParams#move */
11506        final MoveInfo move;
11507
11508        final IPackageInstallObserver2 observer;
11509        // Always refers to PackageManager flags only
11510        final int installFlags;
11511        final String installerPackageName;
11512        final String volumeUuid;
11513        final UserHandle user;
11514        final String abiOverride;
11515        final String[] installGrantPermissions;
11516        /** If non-null, drop an async trace when the install completes */
11517        final String traceMethod;
11518        final int traceCookie;
11519
11520        // The list of instruction sets supported by this app. This is currently
11521        // only used during the rmdex() phase to clean up resources. We can get rid of this
11522        // if we move dex files under the common app path.
11523        /* nullable */ String[] instructionSets;
11524
11525        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11526                int installFlags, String installerPackageName, String volumeUuid,
11527                UserHandle user, String[] instructionSets,
11528                String abiOverride, String[] installGrantPermissions,
11529                String traceMethod, int traceCookie) {
11530            this.origin = origin;
11531            this.move = move;
11532            this.installFlags = installFlags;
11533            this.observer = observer;
11534            this.installerPackageName = installerPackageName;
11535            this.volumeUuid = volumeUuid;
11536            this.user = user;
11537            this.instructionSets = instructionSets;
11538            this.abiOverride = abiOverride;
11539            this.installGrantPermissions = installGrantPermissions;
11540            this.traceMethod = traceMethod;
11541            this.traceCookie = traceCookie;
11542        }
11543
11544        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11545        abstract int doPreInstall(int status);
11546
11547        /**
11548         * Rename package into final resting place. All paths on the given
11549         * scanned package should be updated to reflect the rename.
11550         */
11551        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11552        abstract int doPostInstall(int status, int uid);
11553
11554        /** @see PackageSettingBase#codePathString */
11555        abstract String getCodePath();
11556        /** @see PackageSettingBase#resourcePathString */
11557        abstract String getResourcePath();
11558
11559        // Need installer lock especially for dex file removal.
11560        abstract void cleanUpResourcesLI();
11561        abstract boolean doPostDeleteLI(boolean delete);
11562
11563        /**
11564         * Called before the source arguments are copied. This is used mostly
11565         * for MoveParams when it needs to read the source file to put it in the
11566         * destination.
11567         */
11568        int doPreCopy() {
11569            return PackageManager.INSTALL_SUCCEEDED;
11570        }
11571
11572        /**
11573         * Called after the source arguments are copied. This is used mostly for
11574         * MoveParams when it needs to read the source file to put it in the
11575         * destination.
11576         *
11577         * @return
11578         */
11579        int doPostCopy(int uid) {
11580            return PackageManager.INSTALL_SUCCEEDED;
11581        }
11582
11583        protected boolean isFwdLocked() {
11584            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11585        }
11586
11587        protected boolean isExternalAsec() {
11588            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11589        }
11590
11591        protected boolean isEphemeral() {
11592            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11593        }
11594
11595        UserHandle getUser() {
11596            return user;
11597        }
11598    }
11599
11600    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11601        if (!allCodePaths.isEmpty()) {
11602            if (instructionSets == null) {
11603                throw new IllegalStateException("instructionSet == null");
11604            }
11605            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11606            for (String codePath : allCodePaths) {
11607                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11608                    try {
11609                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11610                    } catch (InstallerException ignored) {
11611                    }
11612                }
11613            }
11614        }
11615    }
11616
11617    /**
11618     * Logic to handle installation of non-ASEC applications, including copying
11619     * and renaming logic.
11620     */
11621    class FileInstallArgs extends InstallArgs {
11622        private File codeFile;
11623        private File resourceFile;
11624
11625        // Example topology:
11626        // /data/app/com.example/base.apk
11627        // /data/app/com.example/split_foo.apk
11628        // /data/app/com.example/lib/arm/libfoo.so
11629        // /data/app/com.example/lib/arm64/libfoo.so
11630        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11631
11632        /** New install */
11633        FileInstallArgs(InstallParams params) {
11634            super(params.origin, params.move, params.observer, params.installFlags,
11635                    params.installerPackageName, params.volumeUuid,
11636                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11637                    params.grantedRuntimePermissions,
11638                    params.traceMethod, params.traceCookie);
11639            if (isFwdLocked()) {
11640                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11641            }
11642        }
11643
11644        /** Existing install */
11645        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11646            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11647                    null, null, null, 0);
11648            this.codeFile = (codePath != null) ? new File(codePath) : null;
11649            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11650        }
11651
11652        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11653            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11654            try {
11655                return doCopyApk(imcs, temp);
11656            } finally {
11657                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11658            }
11659        }
11660
11661        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11662            if (origin.staged) {
11663                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11664                codeFile = origin.file;
11665                resourceFile = origin.file;
11666                return PackageManager.INSTALL_SUCCEEDED;
11667            }
11668
11669            try {
11670                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11671                final File tempDir =
11672                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11673                codeFile = tempDir;
11674                resourceFile = tempDir;
11675            } catch (IOException e) {
11676                Slog.w(TAG, "Failed to create copy file: " + e);
11677                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11678            }
11679
11680            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11681                @Override
11682                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11683                    if (!FileUtils.isValidExtFilename(name)) {
11684                        throw new IllegalArgumentException("Invalid filename: " + name);
11685                    }
11686                    try {
11687                        final File file = new File(codeFile, name);
11688                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11689                                O_RDWR | O_CREAT, 0644);
11690                        Os.chmod(file.getAbsolutePath(), 0644);
11691                        return new ParcelFileDescriptor(fd);
11692                    } catch (ErrnoException e) {
11693                        throw new RemoteException("Failed to open: " + e.getMessage());
11694                    }
11695                }
11696            };
11697
11698            int ret = PackageManager.INSTALL_SUCCEEDED;
11699            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11700            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11701                Slog.e(TAG, "Failed to copy package");
11702                return ret;
11703            }
11704
11705            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11706            NativeLibraryHelper.Handle handle = null;
11707            try {
11708                handle = NativeLibraryHelper.Handle.create(codeFile);
11709                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11710                        abiOverride);
11711            } catch (IOException e) {
11712                Slog.e(TAG, "Copying native libraries failed", e);
11713                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11714            } finally {
11715                IoUtils.closeQuietly(handle);
11716            }
11717
11718            return ret;
11719        }
11720
11721        int doPreInstall(int status) {
11722            if (status != PackageManager.INSTALL_SUCCEEDED) {
11723                cleanUp();
11724            }
11725            return status;
11726        }
11727
11728        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11729            if (status != PackageManager.INSTALL_SUCCEEDED) {
11730                cleanUp();
11731                return false;
11732            }
11733
11734            final File targetDir = codeFile.getParentFile();
11735            final File beforeCodeFile = codeFile;
11736            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11737
11738            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11739            try {
11740                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11741            } catch (ErrnoException e) {
11742                Slog.w(TAG, "Failed to rename", e);
11743                return false;
11744            }
11745
11746            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11747                Slog.w(TAG, "Failed to restorecon");
11748                return false;
11749            }
11750
11751            // Reflect the rename internally
11752            codeFile = afterCodeFile;
11753            resourceFile = afterCodeFile;
11754
11755            // Reflect the rename in scanned details
11756            pkg.codePath = afterCodeFile.getAbsolutePath();
11757            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11758                    pkg.baseCodePath);
11759            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11760                    pkg.splitCodePaths);
11761
11762            // Reflect the rename in app info
11763            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11764            pkg.applicationInfo.setCodePath(pkg.codePath);
11765            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11766            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11767            pkg.applicationInfo.setResourcePath(pkg.codePath);
11768            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11769            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11770
11771            return true;
11772        }
11773
11774        int doPostInstall(int status, int uid) {
11775            if (status != PackageManager.INSTALL_SUCCEEDED) {
11776                cleanUp();
11777            }
11778            return status;
11779        }
11780
11781        @Override
11782        String getCodePath() {
11783            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11784        }
11785
11786        @Override
11787        String getResourcePath() {
11788            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11789        }
11790
11791        private boolean cleanUp() {
11792            if (codeFile == null || !codeFile.exists()) {
11793                return false;
11794            }
11795
11796            removeCodePathLI(codeFile);
11797
11798            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11799                resourceFile.delete();
11800            }
11801
11802            return true;
11803        }
11804
11805        void cleanUpResourcesLI() {
11806            // Try enumerating all code paths before deleting
11807            List<String> allCodePaths = Collections.EMPTY_LIST;
11808            if (codeFile != null && codeFile.exists()) {
11809                try {
11810                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11811                    allCodePaths = pkg.getAllCodePaths();
11812                } catch (PackageParserException e) {
11813                    // Ignored; we tried our best
11814                }
11815            }
11816
11817            cleanUp();
11818            removeDexFiles(allCodePaths, instructionSets);
11819        }
11820
11821        boolean doPostDeleteLI(boolean delete) {
11822            // XXX err, shouldn't we respect the delete flag?
11823            cleanUpResourcesLI();
11824            return true;
11825        }
11826    }
11827
11828    private boolean isAsecExternal(String cid) {
11829        final String asecPath = PackageHelper.getSdFilesystem(cid);
11830        return !asecPath.startsWith(mAsecInternalPath);
11831    }
11832
11833    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11834            PackageManagerException {
11835        if (copyRet < 0) {
11836            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11837                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11838                throw new PackageManagerException(copyRet, message);
11839            }
11840        }
11841    }
11842
11843    /**
11844     * Extract the MountService "container ID" from the full code path of an
11845     * .apk.
11846     */
11847    static String cidFromCodePath(String fullCodePath) {
11848        int eidx = fullCodePath.lastIndexOf("/");
11849        String subStr1 = fullCodePath.substring(0, eidx);
11850        int sidx = subStr1.lastIndexOf("/");
11851        return subStr1.substring(sidx+1, eidx);
11852    }
11853
11854    /**
11855     * Logic to handle installation of ASEC applications, including copying and
11856     * renaming logic.
11857     */
11858    class AsecInstallArgs extends InstallArgs {
11859        static final String RES_FILE_NAME = "pkg.apk";
11860        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11861
11862        String cid;
11863        String packagePath;
11864        String resourcePath;
11865
11866        /** New install */
11867        AsecInstallArgs(InstallParams params) {
11868            super(params.origin, params.move, params.observer, params.installFlags,
11869                    params.installerPackageName, params.volumeUuid,
11870                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11871                    params.grantedRuntimePermissions,
11872                    params.traceMethod, params.traceCookie);
11873        }
11874
11875        /** Existing install */
11876        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11877                        boolean isExternal, boolean isForwardLocked) {
11878            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11879                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11880                    instructionSets, null, null, null, 0);
11881            // Hackily pretend we're still looking at a full code path
11882            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11883                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11884            }
11885
11886            // Extract cid from fullCodePath
11887            int eidx = fullCodePath.lastIndexOf("/");
11888            String subStr1 = fullCodePath.substring(0, eidx);
11889            int sidx = subStr1.lastIndexOf("/");
11890            cid = subStr1.substring(sidx+1, eidx);
11891            setMountPath(subStr1);
11892        }
11893
11894        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11895            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11896                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11897                    instructionSets, null, null, null, 0);
11898            this.cid = cid;
11899            setMountPath(PackageHelper.getSdDir(cid));
11900        }
11901
11902        void createCopyFile() {
11903            cid = mInstallerService.allocateExternalStageCidLegacy();
11904        }
11905
11906        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11907            if (origin.staged && origin.cid != null) {
11908                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11909                cid = origin.cid;
11910                setMountPath(PackageHelper.getSdDir(cid));
11911                return PackageManager.INSTALL_SUCCEEDED;
11912            }
11913
11914            if (temp) {
11915                createCopyFile();
11916            } else {
11917                /*
11918                 * Pre-emptively destroy the container since it's destroyed if
11919                 * copying fails due to it existing anyway.
11920                 */
11921                PackageHelper.destroySdDir(cid);
11922            }
11923
11924            final String newMountPath = imcs.copyPackageToContainer(
11925                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11926                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11927
11928            if (newMountPath != null) {
11929                setMountPath(newMountPath);
11930                return PackageManager.INSTALL_SUCCEEDED;
11931            } else {
11932                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11933            }
11934        }
11935
11936        @Override
11937        String getCodePath() {
11938            return packagePath;
11939        }
11940
11941        @Override
11942        String getResourcePath() {
11943            return resourcePath;
11944        }
11945
11946        int doPreInstall(int status) {
11947            if (status != PackageManager.INSTALL_SUCCEEDED) {
11948                // Destroy container
11949                PackageHelper.destroySdDir(cid);
11950            } else {
11951                boolean mounted = PackageHelper.isContainerMounted(cid);
11952                if (!mounted) {
11953                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11954                            Process.SYSTEM_UID);
11955                    if (newMountPath != null) {
11956                        setMountPath(newMountPath);
11957                    } else {
11958                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11959                    }
11960                }
11961            }
11962            return status;
11963        }
11964
11965        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11966            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11967            String newMountPath = null;
11968            if (PackageHelper.isContainerMounted(cid)) {
11969                // Unmount the container
11970                if (!PackageHelper.unMountSdDir(cid)) {
11971                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11972                    return false;
11973                }
11974            }
11975            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11976                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11977                        " which might be stale. Will try to clean up.");
11978                // Clean up the stale container and proceed to recreate.
11979                if (!PackageHelper.destroySdDir(newCacheId)) {
11980                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11981                    return false;
11982                }
11983                // Successfully cleaned up stale container. Try to rename again.
11984                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11985                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11986                            + " inspite of cleaning it up.");
11987                    return false;
11988                }
11989            }
11990            if (!PackageHelper.isContainerMounted(newCacheId)) {
11991                Slog.w(TAG, "Mounting container " + newCacheId);
11992                newMountPath = PackageHelper.mountSdDir(newCacheId,
11993                        getEncryptKey(), Process.SYSTEM_UID);
11994            } else {
11995                newMountPath = PackageHelper.getSdDir(newCacheId);
11996            }
11997            if (newMountPath == null) {
11998                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11999                return false;
12000            }
12001            Log.i(TAG, "Succesfully renamed " + cid +
12002                    " to " + newCacheId +
12003                    " at new path: " + newMountPath);
12004            cid = newCacheId;
12005
12006            final File beforeCodeFile = new File(packagePath);
12007            setMountPath(newMountPath);
12008            final File afterCodeFile = new File(packagePath);
12009
12010            // Reflect the rename in scanned details
12011            pkg.codePath = afterCodeFile.getAbsolutePath();
12012            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12013                    pkg.baseCodePath);
12014            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
12015                    pkg.splitCodePaths);
12016
12017            // Reflect the rename in app info
12018            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12019            pkg.applicationInfo.setCodePath(pkg.codePath);
12020            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12021            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12022            pkg.applicationInfo.setResourcePath(pkg.codePath);
12023            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12024            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12025
12026            return true;
12027        }
12028
12029        private void setMountPath(String mountPath) {
12030            final File mountFile = new File(mountPath);
12031
12032            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12033            if (monolithicFile.exists()) {
12034                packagePath = monolithicFile.getAbsolutePath();
12035                if (isFwdLocked()) {
12036                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12037                } else {
12038                    resourcePath = packagePath;
12039                }
12040            } else {
12041                packagePath = mountFile.getAbsolutePath();
12042                resourcePath = packagePath;
12043            }
12044        }
12045
12046        int doPostInstall(int status, int uid) {
12047            if (status != PackageManager.INSTALL_SUCCEEDED) {
12048                cleanUp();
12049            } else {
12050                final int groupOwner;
12051                final String protectedFile;
12052                if (isFwdLocked()) {
12053                    groupOwner = UserHandle.getSharedAppGid(uid);
12054                    protectedFile = RES_FILE_NAME;
12055                } else {
12056                    groupOwner = -1;
12057                    protectedFile = null;
12058                }
12059
12060                if (uid < Process.FIRST_APPLICATION_UID
12061                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12062                    Slog.e(TAG, "Failed to finalize " + cid);
12063                    PackageHelper.destroySdDir(cid);
12064                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12065                }
12066
12067                boolean mounted = PackageHelper.isContainerMounted(cid);
12068                if (!mounted) {
12069                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12070                }
12071            }
12072            return status;
12073        }
12074
12075        private void cleanUp() {
12076            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12077
12078            // Destroy secure container
12079            PackageHelper.destroySdDir(cid);
12080        }
12081
12082        private List<String> getAllCodePaths() {
12083            final File codeFile = new File(getCodePath());
12084            if (codeFile != null && codeFile.exists()) {
12085                try {
12086                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12087                    return pkg.getAllCodePaths();
12088                } catch (PackageParserException e) {
12089                    // Ignored; we tried our best
12090                }
12091            }
12092            return Collections.EMPTY_LIST;
12093        }
12094
12095        void cleanUpResourcesLI() {
12096            // Enumerate all code paths before deleting
12097            cleanUpResourcesLI(getAllCodePaths());
12098        }
12099
12100        private void cleanUpResourcesLI(List<String> allCodePaths) {
12101            cleanUp();
12102            removeDexFiles(allCodePaths, instructionSets);
12103        }
12104
12105        String getPackageName() {
12106            return getAsecPackageName(cid);
12107        }
12108
12109        boolean doPostDeleteLI(boolean delete) {
12110            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12111            final List<String> allCodePaths = getAllCodePaths();
12112            boolean mounted = PackageHelper.isContainerMounted(cid);
12113            if (mounted) {
12114                // Unmount first
12115                if (PackageHelper.unMountSdDir(cid)) {
12116                    mounted = false;
12117                }
12118            }
12119            if (!mounted && delete) {
12120                cleanUpResourcesLI(allCodePaths);
12121            }
12122            return !mounted;
12123        }
12124
12125        @Override
12126        int doPreCopy() {
12127            if (isFwdLocked()) {
12128                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12129                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12130                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12131                }
12132            }
12133
12134            return PackageManager.INSTALL_SUCCEEDED;
12135        }
12136
12137        @Override
12138        int doPostCopy(int uid) {
12139            if (isFwdLocked()) {
12140                if (uid < Process.FIRST_APPLICATION_UID
12141                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12142                                RES_FILE_NAME)) {
12143                    Slog.e(TAG, "Failed to finalize " + cid);
12144                    PackageHelper.destroySdDir(cid);
12145                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12146                }
12147            }
12148
12149            return PackageManager.INSTALL_SUCCEEDED;
12150        }
12151    }
12152
12153    /**
12154     * Logic to handle movement of existing installed applications.
12155     */
12156    class MoveInstallArgs extends InstallArgs {
12157        private File codeFile;
12158        private File resourceFile;
12159
12160        /** New install */
12161        MoveInstallArgs(InstallParams params) {
12162            super(params.origin, params.move, params.observer, params.installFlags,
12163                    params.installerPackageName, params.volumeUuid,
12164                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12165                    params.grantedRuntimePermissions,
12166                    params.traceMethod, params.traceCookie);
12167        }
12168
12169        int copyApk(IMediaContainerService imcs, boolean temp) {
12170            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12171                    + move.fromUuid + " to " + move.toUuid);
12172            synchronized (mInstaller) {
12173                try {
12174                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12175                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12176                } catch (InstallerException e) {
12177                    Slog.w(TAG, "Failed to move app", e);
12178                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12179                }
12180            }
12181
12182            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12183            resourceFile = codeFile;
12184            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12185
12186            return PackageManager.INSTALL_SUCCEEDED;
12187        }
12188
12189        int doPreInstall(int status) {
12190            if (status != PackageManager.INSTALL_SUCCEEDED) {
12191                cleanUp(move.toUuid);
12192            }
12193            return status;
12194        }
12195
12196        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12197            if (status != PackageManager.INSTALL_SUCCEEDED) {
12198                cleanUp(move.toUuid);
12199                return false;
12200            }
12201
12202            // Reflect the move in app info
12203            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12204            pkg.applicationInfo.setCodePath(pkg.codePath);
12205            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12206            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12207            pkg.applicationInfo.setResourcePath(pkg.codePath);
12208            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12209            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12210
12211            return true;
12212        }
12213
12214        int doPostInstall(int status, int uid) {
12215            if (status == PackageManager.INSTALL_SUCCEEDED) {
12216                cleanUp(move.fromUuid);
12217            } else {
12218                cleanUp(move.toUuid);
12219            }
12220            return status;
12221        }
12222
12223        @Override
12224        String getCodePath() {
12225            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12226        }
12227
12228        @Override
12229        String getResourcePath() {
12230            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12231        }
12232
12233        private boolean cleanUp(String volumeUuid) {
12234            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12235                    move.dataAppName);
12236            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12237            synchronized (mInstallLock) {
12238                // Clean up both app data and code
12239                removeDataDirsLI(volumeUuid, move.packageName);
12240                removeCodePathLI(codeFile);
12241            }
12242            return true;
12243        }
12244
12245        void cleanUpResourcesLI() {
12246            throw new UnsupportedOperationException();
12247        }
12248
12249        boolean doPostDeleteLI(boolean delete) {
12250            throw new UnsupportedOperationException();
12251        }
12252    }
12253
12254    static String getAsecPackageName(String packageCid) {
12255        int idx = packageCid.lastIndexOf("-");
12256        if (idx == -1) {
12257            return packageCid;
12258        }
12259        return packageCid.substring(0, idx);
12260    }
12261
12262    // Utility method used to create code paths based on package name and available index.
12263    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12264        String idxStr = "";
12265        int idx = 1;
12266        // Fall back to default value of idx=1 if prefix is not
12267        // part of oldCodePath
12268        if (oldCodePath != null) {
12269            String subStr = oldCodePath;
12270            // Drop the suffix right away
12271            if (suffix != null && subStr.endsWith(suffix)) {
12272                subStr = subStr.substring(0, subStr.length() - suffix.length());
12273            }
12274            // If oldCodePath already contains prefix find out the
12275            // ending index to either increment or decrement.
12276            int sidx = subStr.lastIndexOf(prefix);
12277            if (sidx != -1) {
12278                subStr = subStr.substring(sidx + prefix.length());
12279                if (subStr != null) {
12280                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12281                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12282                    }
12283                    try {
12284                        idx = Integer.parseInt(subStr);
12285                        if (idx <= 1) {
12286                            idx++;
12287                        } else {
12288                            idx--;
12289                        }
12290                    } catch(NumberFormatException e) {
12291                    }
12292                }
12293            }
12294        }
12295        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12296        return prefix + idxStr;
12297    }
12298
12299    private File getNextCodePath(File targetDir, String packageName) {
12300        int suffix = 1;
12301        File result;
12302        do {
12303            result = new File(targetDir, packageName + "-" + suffix);
12304            suffix++;
12305        } while (result.exists());
12306        return result;
12307    }
12308
12309    // Utility method that returns the relative package path with respect
12310    // to the installation directory. Like say for /data/data/com.test-1.apk
12311    // string com.test-1 is returned.
12312    static String deriveCodePathName(String codePath) {
12313        if (codePath == null) {
12314            return null;
12315        }
12316        final File codeFile = new File(codePath);
12317        final String name = codeFile.getName();
12318        if (codeFile.isDirectory()) {
12319            return name;
12320        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12321            final int lastDot = name.lastIndexOf('.');
12322            return name.substring(0, lastDot);
12323        } else {
12324            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12325            return null;
12326        }
12327    }
12328
12329    static class PackageInstalledInfo {
12330        String name;
12331        int uid;
12332        // The set of users that originally had this package installed.
12333        int[] origUsers;
12334        // The set of users that now have this package installed.
12335        int[] newUsers;
12336        PackageParser.Package pkg;
12337        int returnCode;
12338        String returnMsg;
12339        PackageRemovedInfo removedInfo;
12340
12341        public void setError(int code, String msg) {
12342            returnCode = code;
12343            returnMsg = msg;
12344            Slog.w(TAG, msg);
12345        }
12346
12347        public void setError(String msg, PackageParserException e) {
12348            returnCode = e.error;
12349            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12350            Slog.w(TAG, msg, e);
12351        }
12352
12353        public void setError(String msg, PackageManagerException e) {
12354            returnCode = e.error;
12355            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12356            Slog.w(TAG, msg, e);
12357        }
12358
12359        // In some error cases we want to convey more info back to the observer
12360        String origPackage;
12361        String origPermission;
12362    }
12363
12364    /*
12365     * Install a non-existing package.
12366     */
12367    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12368            UserHandle user, String installerPackageName, String volumeUuid,
12369            PackageInstalledInfo res) {
12370        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12371
12372        // Remember this for later, in case we need to rollback this install
12373        String pkgName = pkg.packageName;
12374
12375        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12376        // TODO: b/23350563
12377        final boolean dataDirExists = Environment
12378                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12379
12380        synchronized(mPackages) {
12381            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12382                // A package with the same name is already installed, though
12383                // it has been renamed to an older name.  The package we
12384                // are trying to install should be installed as an update to
12385                // the existing one, but that has not been requested, so bail.
12386                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12387                        + " without first uninstalling package running as "
12388                        + mSettings.mRenamedPackages.get(pkgName));
12389                return;
12390            }
12391            if (mPackages.containsKey(pkgName)) {
12392                // Don't allow installation over an existing package with the same name.
12393                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12394                        + " without first uninstalling.");
12395                return;
12396            }
12397        }
12398
12399        try {
12400            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12401                    System.currentTimeMillis(), user);
12402
12403            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12404            prepareAppDataAfterInstall(newPackage);
12405
12406            // delete the partially installed application. the data directory will have to be
12407            // restored if it was already existing
12408            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12409                // remove package from internal structures.  Note that we want deletePackageX to
12410                // delete the package data and cache directories that it created in
12411                // scanPackageLocked, unless those directories existed before we even tried to
12412                // install.
12413                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12414                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12415                                res.removedInfo, true);
12416            }
12417
12418        } catch (PackageManagerException e) {
12419            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12420        }
12421
12422        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12423    }
12424
12425    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12426        // Can't rotate keys during boot or if sharedUser.
12427        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12428                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12429            return false;
12430        }
12431        // app is using upgradeKeySets; make sure all are valid
12432        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12433        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12434        for (int i = 0; i < upgradeKeySets.length; i++) {
12435            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12436                Slog.wtf(TAG, "Package "
12437                         + (oldPs.name != null ? oldPs.name : "<null>")
12438                         + " contains upgrade-key-set reference to unknown key-set: "
12439                         + upgradeKeySets[i]
12440                         + " reverting to signatures check.");
12441                return false;
12442            }
12443        }
12444        return true;
12445    }
12446
12447    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12448        // Upgrade keysets are being used.  Determine if new package has a superset of the
12449        // required keys.
12450        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12451        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12452        for (int i = 0; i < upgradeKeySets.length; i++) {
12453            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12454            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12455                return true;
12456            }
12457        }
12458        return false;
12459    }
12460
12461    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12462            UserHandle user, String installerPackageName, String volumeUuid,
12463            PackageInstalledInfo res) {
12464        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12465
12466        final PackageParser.Package oldPackage;
12467        final String pkgName = pkg.packageName;
12468        final int[] allUsers;
12469        final boolean[] perUserInstalled;
12470
12471        // First find the old package info and check signatures
12472        synchronized(mPackages) {
12473            oldPackage = mPackages.get(pkgName);
12474            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12475            if (isEphemeral && !oldIsEphemeral) {
12476                // can't downgrade from full to ephemeral
12477                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12478                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12479                return;
12480            }
12481            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12482            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12483            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12484                if(!checkUpgradeKeySetLP(ps, pkg)) {
12485                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12486                            "New package not signed by keys specified by upgrade-keysets: "
12487                            + pkgName);
12488                    return;
12489                }
12490            } else {
12491                // default to original signature matching
12492                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12493                    != PackageManager.SIGNATURE_MATCH) {
12494                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12495                            "New package has a different signature: " + pkgName);
12496                    return;
12497                }
12498            }
12499
12500            // In case of rollback, remember per-user/profile install state
12501            allUsers = sUserManager.getUserIds();
12502            perUserInstalled = new boolean[allUsers.length];
12503            for (int i = 0; i < allUsers.length; i++) {
12504                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12505            }
12506        }
12507
12508        boolean sysPkg = (isSystemApp(oldPackage));
12509        if (sysPkg) {
12510            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12511                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12512        } else {
12513            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12514                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12515        }
12516    }
12517
12518    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12519            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12520            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12521            String volumeUuid, PackageInstalledInfo res) {
12522        String pkgName = deletedPackage.packageName;
12523        boolean deletedPkg = true;
12524        boolean updatedSettings = false;
12525
12526        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12527                + deletedPackage);
12528        long origUpdateTime;
12529        if (pkg.mExtras != null) {
12530            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12531        } else {
12532            origUpdateTime = 0;
12533        }
12534
12535        // First delete the existing package while retaining the data directory
12536        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12537                res.removedInfo, true)) {
12538            // If the existing package wasn't successfully deleted
12539            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12540            deletedPkg = false;
12541        } else {
12542            // Successfully deleted the old package; proceed with replace.
12543
12544            // If deleted package lived in a container, give users a chance to
12545            // relinquish resources before killing.
12546            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12547                if (DEBUG_INSTALL) {
12548                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12549                }
12550                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12551                final ArrayList<String> pkgList = new ArrayList<String>(1);
12552                pkgList.add(deletedPackage.applicationInfo.packageName);
12553                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12554            }
12555
12556            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12557            try {
12558                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12559                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12560                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12561                        perUserInstalled, res, user);
12562                prepareAppDataAfterInstall(newPackage);
12563                updatedSettings = true;
12564            } catch (PackageManagerException e) {
12565                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12566            }
12567        }
12568
12569        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12570            // remove package from internal structures.  Note that we want deletePackageX to
12571            // delete the package data and cache directories that it created in
12572            // scanPackageLocked, unless those directories existed before we even tried to
12573            // install.
12574            if(updatedSettings) {
12575                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12576                deletePackageLI(
12577                        pkgName, null, true, allUsers, perUserInstalled,
12578                        PackageManager.DELETE_KEEP_DATA,
12579                                res.removedInfo, true);
12580            }
12581            // Since we failed to install the new package we need to restore the old
12582            // package that we deleted.
12583            if (deletedPkg) {
12584                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12585                File restoreFile = new File(deletedPackage.codePath);
12586                // Parse old package
12587                boolean oldExternal = isExternal(deletedPackage);
12588                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12589                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12590                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12591                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12592                try {
12593                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12594                            null);
12595                } catch (PackageManagerException e) {
12596                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12597                            + e.getMessage());
12598                    return;
12599                }
12600                // Restore of old package succeeded. Update permissions.
12601                // writer
12602                synchronized (mPackages) {
12603                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12604                            UPDATE_PERMISSIONS_ALL);
12605                    // can downgrade to reader
12606                    mSettings.writeLPr();
12607                }
12608                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12609            }
12610        }
12611    }
12612
12613    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12614            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12615            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12616            String volumeUuid, PackageInstalledInfo res) {
12617        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12618                + ", old=" + deletedPackage);
12619        boolean disabledSystem = false;
12620        boolean updatedSettings = false;
12621        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12622        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12623                != 0) {
12624            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12625        }
12626        String packageName = deletedPackage.packageName;
12627        if (packageName == null) {
12628            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12629                    "Attempt to delete null packageName.");
12630            return;
12631        }
12632        PackageParser.Package oldPkg;
12633        PackageSetting oldPkgSetting;
12634        // reader
12635        synchronized (mPackages) {
12636            oldPkg = mPackages.get(packageName);
12637            oldPkgSetting = mSettings.mPackages.get(packageName);
12638            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12639                    (oldPkgSetting == null)) {
12640                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12641                        "Couldn't find package " + packageName + " information");
12642                return;
12643            }
12644        }
12645
12646        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12647
12648        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12649        res.removedInfo.removedPackage = packageName;
12650        // Remove existing system package
12651        removePackageLI(oldPkgSetting, true);
12652        // writer
12653        synchronized (mPackages) {
12654            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12655            if (!disabledSystem && deletedPackage != null) {
12656                // We didn't need to disable the .apk as a current system package,
12657                // which means we are replacing another update that is already
12658                // installed.  We need to make sure to delete the older one's .apk.
12659                res.removedInfo.args = createInstallArgsForExisting(0,
12660                        deletedPackage.applicationInfo.getCodePath(),
12661                        deletedPackage.applicationInfo.getResourcePath(),
12662                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12663            } else {
12664                res.removedInfo.args = null;
12665            }
12666        }
12667
12668        // Successfully disabled the old package. Now proceed with re-installation
12669        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12670
12671        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12672        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12673
12674        PackageParser.Package newPackage = null;
12675        try {
12676            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12677            if (newPackage.mExtras != null) {
12678                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12679                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12680                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12681
12682                // is the update attempting to change shared user? that isn't going to work...
12683                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12684                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12685                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12686                            + " to " + newPkgSetting.sharedUser);
12687                    updatedSettings = true;
12688                }
12689            }
12690
12691            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12692                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12693                        perUserInstalled, res, user);
12694                prepareAppDataAfterInstall(newPackage);
12695                updatedSettings = true;
12696            }
12697
12698        } catch (PackageManagerException e) {
12699            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12700        }
12701
12702        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12703            // Re installation failed. Restore old information
12704            // Remove new pkg information
12705            if (newPackage != null) {
12706                removeInstalledPackageLI(newPackage, true);
12707            }
12708            // Add back the old system package
12709            try {
12710                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12711            } catch (PackageManagerException e) {
12712                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12713            }
12714            // Restore the old system information in Settings
12715            synchronized (mPackages) {
12716                if (disabledSystem) {
12717                    mSettings.enableSystemPackageLPw(packageName);
12718                }
12719                if (updatedSettings) {
12720                    mSettings.setInstallerPackageName(packageName,
12721                            oldPkgSetting.installerPackageName);
12722                }
12723                mSettings.writeLPr();
12724            }
12725        }
12726    }
12727
12728    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12729        // Collect all used permissions in the UID
12730        ArraySet<String> usedPermissions = new ArraySet<>();
12731        final int packageCount = su.packages.size();
12732        for (int i = 0; i < packageCount; i++) {
12733            PackageSetting ps = su.packages.valueAt(i);
12734            if (ps.pkg == null) {
12735                continue;
12736            }
12737            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12738            for (int j = 0; j < requestedPermCount; j++) {
12739                String permission = ps.pkg.requestedPermissions.get(j);
12740                BasePermission bp = mSettings.mPermissions.get(permission);
12741                if (bp != null) {
12742                    usedPermissions.add(permission);
12743                }
12744            }
12745        }
12746
12747        PermissionsState permissionsState = su.getPermissionsState();
12748        // Prune install permissions
12749        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12750        final int installPermCount = installPermStates.size();
12751        for (int i = installPermCount - 1; i >= 0;  i--) {
12752            PermissionState permissionState = installPermStates.get(i);
12753            if (!usedPermissions.contains(permissionState.getName())) {
12754                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12755                if (bp != null) {
12756                    permissionsState.revokeInstallPermission(bp);
12757                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12758                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12759                }
12760            }
12761        }
12762
12763        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12764
12765        // Prune runtime permissions
12766        for (int userId : allUserIds) {
12767            List<PermissionState> runtimePermStates = permissionsState
12768                    .getRuntimePermissionStates(userId);
12769            final int runtimePermCount = runtimePermStates.size();
12770            for (int i = runtimePermCount - 1; i >= 0; i--) {
12771                PermissionState permissionState = runtimePermStates.get(i);
12772                if (!usedPermissions.contains(permissionState.getName())) {
12773                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12774                    if (bp != null) {
12775                        permissionsState.revokeRuntimePermission(bp, userId);
12776                        permissionsState.updatePermissionFlags(bp, userId,
12777                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12778                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12779                                runtimePermissionChangedUserIds, userId);
12780                    }
12781                }
12782            }
12783        }
12784
12785        return runtimePermissionChangedUserIds;
12786    }
12787
12788    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12789            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12790            UserHandle user) {
12791        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12792
12793        String pkgName = newPackage.packageName;
12794        synchronized (mPackages) {
12795            //write settings. the installStatus will be incomplete at this stage.
12796            //note that the new package setting would have already been
12797            //added to mPackages. It hasn't been persisted yet.
12798            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12799            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12800            mSettings.writeLPr();
12801            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12802        }
12803
12804        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12805        synchronized (mPackages) {
12806            updatePermissionsLPw(newPackage.packageName, newPackage,
12807                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12808                            ? UPDATE_PERMISSIONS_ALL : 0));
12809            // For system-bundled packages, we assume that installing an upgraded version
12810            // of the package implies that the user actually wants to run that new code,
12811            // so we enable the package.
12812            PackageSetting ps = mSettings.mPackages.get(pkgName);
12813            if (ps != null) {
12814                if (isSystemApp(newPackage)) {
12815                    // NB: implicit assumption that system package upgrades apply to all users
12816                    if (DEBUG_INSTALL) {
12817                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12818                    }
12819                    if (res.origUsers != null) {
12820                        for (int userHandle : res.origUsers) {
12821                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12822                                    userHandle, installerPackageName);
12823                        }
12824                    }
12825                    // Also convey the prior install/uninstall state
12826                    if (allUsers != null && perUserInstalled != null) {
12827                        for (int i = 0; i < allUsers.length; i++) {
12828                            if (DEBUG_INSTALL) {
12829                                Slog.d(TAG, "    user " + allUsers[i]
12830                                        + " => " + perUserInstalled[i]);
12831                            }
12832                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12833                        }
12834                        // these install state changes will be persisted in the
12835                        // upcoming call to mSettings.writeLPr().
12836                    }
12837                }
12838                // It's implied that when a user requests installation, they want the app to be
12839                // installed and enabled.
12840                int userId = user.getIdentifier();
12841                if (userId != UserHandle.USER_ALL) {
12842                    ps.setInstalled(true, userId);
12843                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12844                }
12845            }
12846            res.name = pkgName;
12847            res.uid = newPackage.applicationInfo.uid;
12848            res.pkg = newPackage;
12849            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12850            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12851            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12852            //to update install status
12853            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12854            mSettings.writeLPr();
12855            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12856        }
12857
12858        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12859    }
12860
12861    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12862        try {
12863            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12864            installPackageLI(args, res);
12865        } finally {
12866            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12867        }
12868    }
12869
12870    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12871        final int installFlags = args.installFlags;
12872        final String installerPackageName = args.installerPackageName;
12873        final String volumeUuid = args.volumeUuid;
12874        final File tmpPackageFile = new File(args.getCodePath());
12875        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12876        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12877                || (args.volumeUuid != null));
12878        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12879        boolean replace = false;
12880        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12881        if (args.move != null) {
12882            // moving a complete application; perfom an initial scan on the new install location
12883            scanFlags |= SCAN_INITIAL;
12884        }
12885        // Result object to be returned
12886        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12887
12888        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12889
12890        // Sanity check
12891        if (ephemeral && (forwardLocked || onExternal)) {
12892            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12893                    + " external=" + onExternal);
12894            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12895            return;
12896        }
12897
12898        // Retrieve PackageSettings and parse package
12899        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12900                | PackageParser.PARSE_ENFORCE_CODE
12901                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12902                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12903                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12904        PackageParser pp = new PackageParser();
12905        pp.setSeparateProcesses(mSeparateProcesses);
12906        pp.setDisplayMetrics(mMetrics);
12907
12908        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12909        final PackageParser.Package pkg;
12910        try {
12911            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12912        } catch (PackageParserException e) {
12913            res.setError("Failed parse during installPackageLI", e);
12914            return;
12915        } finally {
12916            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12917        }
12918
12919        // If package doesn't declare API override, mark that we have an install
12920        // time CPU ABI override.
12921        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
12922            pkg.cpuAbiOverride = args.abiOverride;
12923        }
12924
12925        String pkgName = res.name = pkg.packageName;
12926        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12927            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12928                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12929                return;
12930            }
12931        }
12932
12933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12934        try {
12935            pp.collectCertificates(pkg, parseFlags);
12936        } catch (PackageParserException e) {
12937            res.setError("Failed collect during installPackageLI", e);
12938            return;
12939        } finally {
12940            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12941        }
12942
12943        // Get rid of all references to package scan path via parser.
12944        pp = null;
12945        String oldCodePath = null;
12946        boolean systemApp = false;
12947        synchronized (mPackages) {
12948            // Check if installing already existing package
12949            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12950                String oldName = mSettings.mRenamedPackages.get(pkgName);
12951                if (pkg.mOriginalPackages != null
12952                        && pkg.mOriginalPackages.contains(oldName)
12953                        && mPackages.containsKey(oldName)) {
12954                    // This package is derived from an original package,
12955                    // and this device has been updating from that original
12956                    // name.  We must continue using the original name, so
12957                    // rename the new package here.
12958                    pkg.setPackageName(oldName);
12959                    pkgName = pkg.packageName;
12960                    replace = true;
12961                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12962                            + oldName + " pkgName=" + pkgName);
12963                } else if (mPackages.containsKey(pkgName)) {
12964                    // This package, under its official name, already exists
12965                    // on the device; we should replace it.
12966                    replace = true;
12967                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12968                }
12969
12970                // Prevent apps opting out from runtime permissions
12971                if (replace) {
12972                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12973                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12974                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12975                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12976                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12977                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12978                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12979                                        + " doesn't support runtime permissions but the old"
12980                                        + " target SDK " + oldTargetSdk + " does.");
12981                        return;
12982                    }
12983                }
12984            }
12985
12986            PackageSetting ps = mSettings.mPackages.get(pkgName);
12987            if (ps != null) {
12988                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12989
12990                // Quick sanity check that we're signed correctly if updating;
12991                // we'll check this again later when scanning, but we want to
12992                // bail early here before tripping over redefined permissions.
12993                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12994                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12995                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12996                                + pkg.packageName + " upgrade keys do not match the "
12997                                + "previously installed version");
12998                        return;
12999                    }
13000                } else {
13001                    try {
13002                        verifySignaturesLP(ps, pkg);
13003                    } catch (PackageManagerException e) {
13004                        res.setError(e.error, e.getMessage());
13005                        return;
13006                    }
13007                }
13008
13009                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13010                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13011                    systemApp = (ps.pkg.applicationInfo.flags &
13012                            ApplicationInfo.FLAG_SYSTEM) != 0;
13013                }
13014                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13015            }
13016
13017            // Check whether the newly-scanned package wants to define an already-defined perm
13018            int N = pkg.permissions.size();
13019            for (int i = N-1; i >= 0; i--) {
13020                PackageParser.Permission perm = pkg.permissions.get(i);
13021                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13022                if (bp != null) {
13023                    // If the defining package is signed with our cert, it's okay.  This
13024                    // also includes the "updating the same package" case, of course.
13025                    // "updating same package" could also involve key-rotation.
13026                    final boolean sigsOk;
13027                    if (bp.sourcePackage.equals(pkg.packageName)
13028                            && (bp.packageSetting instanceof PackageSetting)
13029                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13030                                    scanFlags))) {
13031                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13032                    } else {
13033                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13034                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13035                    }
13036                    if (!sigsOk) {
13037                        // If the owning package is the system itself, we log but allow
13038                        // install to proceed; we fail the install on all other permission
13039                        // redefinitions.
13040                        if (!bp.sourcePackage.equals("android")) {
13041                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13042                                    + pkg.packageName + " attempting to redeclare permission "
13043                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13044                            res.origPermission = perm.info.name;
13045                            res.origPackage = bp.sourcePackage;
13046                            return;
13047                        } else {
13048                            Slog.w(TAG, "Package " + pkg.packageName
13049                                    + " attempting to redeclare system permission "
13050                                    + perm.info.name + "; ignoring new declaration");
13051                            pkg.permissions.remove(i);
13052                        }
13053                    }
13054                }
13055            }
13056
13057        }
13058
13059        if (systemApp) {
13060            if (onExternal) {
13061                // Abort update; system app can't be replaced with app on sdcard
13062                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13063                        "Cannot install updates to system apps on sdcard");
13064                return;
13065            } else if (ephemeral) {
13066                // Abort update; system app can't be replaced with an ephemeral app
13067                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13068                        "Cannot update a system app with an ephemeral app");
13069                return;
13070            }
13071        }
13072
13073        if (args.move != null) {
13074            // We did an in-place move, so dex is ready to roll
13075            scanFlags |= SCAN_NO_DEX;
13076            scanFlags |= SCAN_MOVE;
13077
13078            synchronized (mPackages) {
13079                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13080                if (ps == null) {
13081                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13082                            "Missing settings for moved package " + pkgName);
13083                }
13084
13085                // We moved the entire application as-is, so bring over the
13086                // previously derived ABI information.
13087                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13088                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13089            }
13090
13091        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13092            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13093            scanFlags |= SCAN_NO_DEX;
13094
13095            try {
13096                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13097                    args.abiOverride : pkg.cpuAbiOverride);
13098                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13099                        true /* extract libs */);
13100            } catch (PackageManagerException pme) {
13101                Slog.e(TAG, "Error deriving application ABI", pme);
13102                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13103                return;
13104            }
13105
13106            // Extract package to save the VM unzipping the APK in memory during
13107            // launch. Only do this if profile-guided compilation is enabled because
13108            // otherwise BackgroundDexOptService will not dexopt the package later.
13109            if (mUseJitProfiles) {
13110                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13111                // Do not run PackageDexOptimizer through the local performDexOpt
13112                // method because `pkg` is not in `mPackages` yet.
13113                int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13114                        false /* useProfiles */, true /* extractOnly */);
13115                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13116                if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13117                    String msg = "Extracking package failed for " + pkgName;
13118                    res.setError(INSTALL_FAILED_DEXOPT, msg);
13119                    return;
13120                }
13121            }
13122        }
13123
13124        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13125            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13126            return;
13127        }
13128
13129        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13130
13131        if (replace) {
13132            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13133                    installerPackageName, volumeUuid, res);
13134        } else {
13135            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13136                    args.user, installerPackageName, volumeUuid, res);
13137        }
13138        synchronized (mPackages) {
13139            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13140            if (ps != null) {
13141                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13142            }
13143        }
13144    }
13145
13146    private void startIntentFilterVerifications(int userId, boolean replacing,
13147            PackageParser.Package pkg) {
13148        if (mIntentFilterVerifierComponent == null) {
13149            Slog.w(TAG, "No IntentFilter verification will not be done as "
13150                    + "there is no IntentFilterVerifier available!");
13151            return;
13152        }
13153
13154        final int verifierUid = getPackageUid(
13155                mIntentFilterVerifierComponent.getPackageName(),
13156                MATCH_DEBUG_TRIAGED_MISSING,
13157                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13158
13159        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13160        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13161        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13162        mHandler.sendMessage(msg);
13163    }
13164
13165    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13166            PackageParser.Package pkg) {
13167        int size = pkg.activities.size();
13168        if (size == 0) {
13169            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13170                    "No activity, so no need to verify any IntentFilter!");
13171            return;
13172        }
13173
13174        final boolean hasDomainURLs = hasDomainURLs(pkg);
13175        if (!hasDomainURLs) {
13176            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13177                    "No domain URLs, so no need to verify any IntentFilter!");
13178            return;
13179        }
13180
13181        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13182                + " if any IntentFilter from the " + size
13183                + " Activities needs verification ...");
13184
13185        int count = 0;
13186        final String packageName = pkg.packageName;
13187
13188        synchronized (mPackages) {
13189            // If this is a new install and we see that we've already run verification for this
13190            // package, we have nothing to do: it means the state was restored from backup.
13191            if (!replacing) {
13192                IntentFilterVerificationInfo ivi =
13193                        mSettings.getIntentFilterVerificationLPr(packageName);
13194                if (ivi != null) {
13195                    if (DEBUG_DOMAIN_VERIFICATION) {
13196                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13197                                + ivi.getStatusString());
13198                    }
13199                    return;
13200                }
13201            }
13202
13203            // If any filters need to be verified, then all need to be.
13204            boolean needToVerify = false;
13205            for (PackageParser.Activity a : pkg.activities) {
13206                for (ActivityIntentInfo filter : a.intents) {
13207                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13208                        if (DEBUG_DOMAIN_VERIFICATION) {
13209                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13210                        }
13211                        needToVerify = true;
13212                        break;
13213                    }
13214                }
13215            }
13216
13217            if (needToVerify) {
13218                final int verificationId = mIntentFilterVerificationToken++;
13219                for (PackageParser.Activity a : pkg.activities) {
13220                    for (ActivityIntentInfo filter : a.intents) {
13221                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13222                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13223                                    "Verification needed for IntentFilter:" + filter.toString());
13224                            mIntentFilterVerifier.addOneIntentFilterVerification(
13225                                    verifierUid, userId, verificationId, filter, packageName);
13226                            count++;
13227                        }
13228                    }
13229                }
13230            }
13231        }
13232
13233        if (count > 0) {
13234            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13235                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13236                    +  " for userId:" + userId);
13237            mIntentFilterVerifier.startVerifications(userId);
13238        } else {
13239            if (DEBUG_DOMAIN_VERIFICATION) {
13240                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13241            }
13242        }
13243    }
13244
13245    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13246        final ComponentName cn  = filter.activity.getComponentName();
13247        final String packageName = cn.getPackageName();
13248
13249        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13250                packageName);
13251        if (ivi == null) {
13252            return true;
13253        }
13254        int status = ivi.getStatus();
13255        switch (status) {
13256            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13257            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13258                return true;
13259
13260            default:
13261                // Nothing to do
13262                return false;
13263        }
13264    }
13265
13266    private static boolean isMultiArch(ApplicationInfo info) {
13267        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13268    }
13269
13270    private static boolean isExternal(PackageParser.Package pkg) {
13271        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13272    }
13273
13274    private static boolean isExternal(PackageSetting ps) {
13275        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13276    }
13277
13278    private static boolean isEphemeral(PackageParser.Package pkg) {
13279        return pkg.applicationInfo.isEphemeralApp();
13280    }
13281
13282    private static boolean isEphemeral(PackageSetting ps) {
13283        return ps.pkg != null && isEphemeral(ps.pkg);
13284    }
13285
13286    private static boolean isSystemApp(PackageParser.Package pkg) {
13287        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13288    }
13289
13290    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13291        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13292    }
13293
13294    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13295        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13296    }
13297
13298    private static boolean isSystemApp(PackageSetting ps) {
13299        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13300    }
13301
13302    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13303        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13304    }
13305
13306    private int packageFlagsToInstallFlags(PackageSetting ps) {
13307        int installFlags = 0;
13308        if (isEphemeral(ps)) {
13309            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13310        }
13311        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13312            // This existing package was an external ASEC install when we have
13313            // the external flag without a UUID
13314            installFlags |= PackageManager.INSTALL_EXTERNAL;
13315        }
13316        if (ps.isForwardLocked()) {
13317            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13318        }
13319        return installFlags;
13320    }
13321
13322    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13323        if (isExternal(pkg)) {
13324            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13325                return StorageManager.UUID_PRIMARY_PHYSICAL;
13326            } else {
13327                return pkg.volumeUuid;
13328            }
13329        } else {
13330            return StorageManager.UUID_PRIVATE_INTERNAL;
13331        }
13332    }
13333
13334    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13335        if (isExternal(pkg)) {
13336            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13337                return mSettings.getExternalVersion();
13338            } else {
13339                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13340            }
13341        } else {
13342            return mSettings.getInternalVersion();
13343        }
13344    }
13345
13346    private void deleteTempPackageFiles() {
13347        final FilenameFilter filter = new FilenameFilter() {
13348            public boolean accept(File dir, String name) {
13349                return name.startsWith("vmdl") && name.endsWith(".tmp");
13350            }
13351        };
13352        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13353            file.delete();
13354        }
13355    }
13356
13357    @Override
13358    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13359            int flags) {
13360        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13361                flags);
13362    }
13363
13364    @Override
13365    public void deletePackage(final String packageName,
13366            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13367        mContext.enforceCallingOrSelfPermission(
13368                android.Manifest.permission.DELETE_PACKAGES, null);
13369        Preconditions.checkNotNull(packageName);
13370        Preconditions.checkNotNull(observer);
13371        final int uid = Binder.getCallingUid();
13372        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13373        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13374        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13375            mContext.enforceCallingOrSelfPermission(
13376                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13377                    "deletePackage for user " + userId);
13378        }
13379
13380        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13381            try {
13382                observer.onPackageDeleted(packageName,
13383                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13384            } catch (RemoteException re) {
13385            }
13386            return;
13387        }
13388
13389        for (int currentUserId : users) {
13390            if (getBlockUninstallForUser(packageName, currentUserId)) {
13391                try {
13392                    observer.onPackageDeleted(packageName,
13393                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13394                } catch (RemoteException re) {
13395                }
13396                return;
13397            }
13398        }
13399
13400        if (DEBUG_REMOVE) {
13401            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13402        }
13403        // Queue up an async operation since the package deletion may take a little while.
13404        mHandler.post(new Runnable() {
13405            public void run() {
13406                mHandler.removeCallbacks(this);
13407                final int returnCode = deletePackageX(packageName, userId, flags);
13408                try {
13409                    observer.onPackageDeleted(packageName, returnCode, null);
13410                } catch (RemoteException e) {
13411                    Log.i(TAG, "Observer no longer exists.");
13412                } //end catch
13413            } //end run
13414        });
13415    }
13416
13417    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13418        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13419                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13420        try {
13421            if (dpm != null) {
13422                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13423                        /* callingUserOnly =*/ false);
13424                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13425                        : deviceOwnerComponentName.getPackageName();
13426                // Does the package contains the device owner?
13427                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13428                // this check is probably not needed, since DO should be registered as a device
13429                // admin on some user too. (Original bug for this: b/17657954)
13430                if (packageName.equals(deviceOwnerPackageName)) {
13431                    return true;
13432                }
13433                // Does it contain a device admin for any user?
13434                int[] users;
13435                if (userId == UserHandle.USER_ALL) {
13436                    users = sUserManager.getUserIds();
13437                } else {
13438                    users = new int[]{userId};
13439                }
13440                for (int i = 0; i < users.length; ++i) {
13441                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13442                        return true;
13443                    }
13444                }
13445            }
13446        } catch (RemoteException e) {
13447        }
13448        return false;
13449    }
13450
13451    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13452        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13453    }
13454
13455    /**
13456     *  This method is an internal method that could be get invoked either
13457     *  to delete an installed package or to clean up a failed installation.
13458     *  After deleting an installed package, a broadcast is sent to notify any
13459     *  listeners that the package has been installed. For cleaning up a failed
13460     *  installation, the broadcast is not necessary since the package's
13461     *  installation wouldn't have sent the initial broadcast either
13462     *  The key steps in deleting a package are
13463     *  deleting the package information in internal structures like mPackages,
13464     *  deleting the packages base directories through installd
13465     *  updating mSettings to reflect current status
13466     *  persisting settings for later use
13467     *  sending a broadcast if necessary
13468     */
13469    private int deletePackageX(String packageName, int userId, int flags) {
13470        final PackageRemovedInfo info = new PackageRemovedInfo();
13471        final boolean res;
13472
13473        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13474                ? UserHandle.ALL : new UserHandle(userId);
13475
13476        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13477            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13478            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13479        }
13480
13481        boolean removedForAllUsers = false;
13482        boolean systemUpdate = false;
13483
13484        PackageParser.Package uninstalledPkg;
13485
13486        // for the uninstall-updates case and restricted profiles, remember the per-
13487        // userhandle installed state
13488        int[] allUsers;
13489        boolean[] perUserInstalled;
13490        synchronized (mPackages) {
13491            uninstalledPkg = mPackages.get(packageName);
13492            PackageSetting ps = mSettings.mPackages.get(packageName);
13493            allUsers = sUserManager.getUserIds();
13494            perUserInstalled = new boolean[allUsers.length];
13495            for (int i = 0; i < allUsers.length; i++) {
13496                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13497            }
13498        }
13499
13500        synchronized (mInstallLock) {
13501            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13502            res = deletePackageLI(packageName, removeForUser,
13503                    true, allUsers, perUserInstalled,
13504                    flags | REMOVE_CHATTY, info, true);
13505            systemUpdate = info.isRemovedPackageSystemUpdate;
13506            synchronized (mPackages) {
13507                if (res) {
13508                    if (!systemUpdate && mPackages.get(packageName) == null) {
13509                        removedForAllUsers = true;
13510                    }
13511                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13512                }
13513            }
13514            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13515                    + " removedForAllUsers=" + removedForAllUsers);
13516        }
13517
13518        if (res) {
13519            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13520
13521            // If the removed package was a system update, the old system package
13522            // was re-enabled; we need to broadcast this information
13523            if (systemUpdate) {
13524                Bundle extras = new Bundle(1);
13525                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13526                        ? info.removedAppId : info.uid);
13527                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13528
13529                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13530                        extras, 0, null, null, null);
13531                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13532                        extras, 0, null, null, null);
13533                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13534                        null, 0, packageName, null, null);
13535            }
13536        }
13537        // Force a gc here.
13538        Runtime.getRuntime().gc();
13539        // Delete the resources here after sending the broadcast to let
13540        // other processes clean up before deleting resources.
13541        if (info.args != null) {
13542            synchronized (mInstallLock) {
13543                info.args.doPostDeleteLI(true);
13544            }
13545        }
13546
13547        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13548    }
13549
13550    class PackageRemovedInfo {
13551        String removedPackage;
13552        int uid = -1;
13553        int removedAppId = -1;
13554        int[] removedUsers = null;
13555        boolean isRemovedPackageSystemUpdate = false;
13556        // Clean up resources deleted packages.
13557        InstallArgs args = null;
13558
13559        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13560            Bundle extras = new Bundle(1);
13561            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13562            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13563            if (replacing) {
13564                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13565            }
13566            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13567            if (removedPackage != null) {
13568                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13569                        extras, 0, null, null, removedUsers);
13570                if (fullRemove && !replacing) {
13571                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13572                            extras, 0, null, null, removedUsers);
13573                }
13574            }
13575            if (removedAppId >= 0) {
13576                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13577                        removedUsers);
13578            }
13579        }
13580    }
13581
13582    /*
13583     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13584     * flag is not set, the data directory is removed as well.
13585     * make sure this flag is set for partially installed apps. If not its meaningless to
13586     * delete a partially installed application.
13587     */
13588    private void removePackageDataLI(PackageSetting ps,
13589            int[] allUserHandles, boolean[] perUserInstalled,
13590            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13591        String packageName = ps.name;
13592        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13593        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13594        // Retrieve object to delete permissions for shared user later on
13595        final PackageSetting deletedPs;
13596        // reader
13597        synchronized (mPackages) {
13598            deletedPs = mSettings.mPackages.get(packageName);
13599            if (outInfo != null) {
13600                outInfo.removedPackage = packageName;
13601                outInfo.removedUsers = deletedPs != null
13602                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13603                        : null;
13604            }
13605        }
13606        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13607            removeDataDirsLI(ps.volumeUuid, packageName);
13608            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13609        }
13610        // writer
13611        synchronized (mPackages) {
13612            if (deletedPs != null) {
13613                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13614                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13615                    clearDefaultBrowserIfNeeded(packageName);
13616                    if (outInfo != null) {
13617                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13618                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13619                    }
13620                    updatePermissionsLPw(deletedPs.name, null, 0);
13621                    if (deletedPs.sharedUser != null) {
13622                        // Remove permissions associated with package. Since runtime
13623                        // permissions are per user we have to kill the removed package
13624                        // or packages running under the shared user of the removed
13625                        // package if revoking the permissions requested only by the removed
13626                        // package is successful and this causes a change in gids.
13627                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13628                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13629                                    userId);
13630                            if (userIdToKill == UserHandle.USER_ALL
13631                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13632                                // If gids changed for this user, kill all affected packages.
13633                                mHandler.post(new Runnable() {
13634                                    @Override
13635                                    public void run() {
13636                                        // This has to happen with no lock held.
13637                                        killApplication(deletedPs.name, deletedPs.appId,
13638                                                KILL_APP_REASON_GIDS_CHANGED);
13639                                    }
13640                                });
13641                                break;
13642                            }
13643                        }
13644                    }
13645                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13646                }
13647                // make sure to preserve per-user disabled state if this removal was just
13648                // a downgrade of a system app to the factory package
13649                if (allUserHandles != null && perUserInstalled != null) {
13650                    if (DEBUG_REMOVE) {
13651                        Slog.d(TAG, "Propagating install state across downgrade");
13652                    }
13653                    for (int i = 0; i < allUserHandles.length; i++) {
13654                        if (DEBUG_REMOVE) {
13655                            Slog.d(TAG, "    user " + allUserHandles[i]
13656                                    + " => " + perUserInstalled[i]);
13657                        }
13658                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13659                    }
13660                }
13661            }
13662            // can downgrade to reader
13663            if (writeSettings) {
13664                // Save settings now
13665                mSettings.writeLPr();
13666            }
13667        }
13668        if (outInfo != null) {
13669            // A user ID was deleted here. Go through all users and remove it
13670            // from KeyStore.
13671            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13672        }
13673    }
13674
13675    static boolean locationIsPrivileged(File path) {
13676        try {
13677            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13678                    .getCanonicalPath();
13679            return path.getCanonicalPath().startsWith(privilegedAppDir);
13680        } catch (IOException e) {
13681            Slog.e(TAG, "Unable to access code path " + path);
13682        }
13683        return false;
13684    }
13685
13686    /*
13687     * Tries to delete system package.
13688     */
13689    private boolean deleteSystemPackageLI(PackageSetting newPs,
13690            int[] allUserHandles, boolean[] perUserInstalled,
13691            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13692        final boolean applyUserRestrictions
13693                = (allUserHandles != null) && (perUserInstalled != null);
13694        PackageSetting disabledPs = null;
13695        // Confirm if the system package has been updated
13696        // An updated system app can be deleted. This will also have to restore
13697        // the system pkg from system partition
13698        // reader
13699        synchronized (mPackages) {
13700            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13701        }
13702        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13703                + " disabledPs=" + disabledPs);
13704        if (disabledPs == null) {
13705            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13706            return false;
13707        } else if (DEBUG_REMOVE) {
13708            Slog.d(TAG, "Deleting system pkg from data partition");
13709        }
13710        if (DEBUG_REMOVE) {
13711            if (applyUserRestrictions) {
13712                Slog.d(TAG, "Remembering install states:");
13713                for (int i = 0; i < allUserHandles.length; i++) {
13714                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13715                }
13716            }
13717        }
13718        // Delete the updated package
13719        outInfo.isRemovedPackageSystemUpdate = true;
13720        if (disabledPs.versionCode < newPs.versionCode) {
13721            // Delete data for downgrades
13722            flags &= ~PackageManager.DELETE_KEEP_DATA;
13723        } else {
13724            // Preserve data by setting flag
13725            flags |= PackageManager.DELETE_KEEP_DATA;
13726        }
13727        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13728                allUserHandles, perUserInstalled, outInfo, writeSettings);
13729        if (!ret) {
13730            return false;
13731        }
13732        // writer
13733        synchronized (mPackages) {
13734            // Reinstate the old system package
13735            mSettings.enableSystemPackageLPw(newPs.name);
13736            // Remove any native libraries from the upgraded package.
13737            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13738        }
13739        // Install the system package
13740        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13741        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13742        if (locationIsPrivileged(disabledPs.codePath)) {
13743            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13744        }
13745
13746        final PackageParser.Package newPkg;
13747        try {
13748            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13749        } catch (PackageManagerException e) {
13750            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13751            return false;
13752        }
13753
13754        prepareAppDataAfterInstall(newPkg);
13755
13756        // writer
13757        synchronized (mPackages) {
13758            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13759
13760            // Propagate the permissions state as we do not want to drop on the floor
13761            // runtime permissions. The update permissions method below will take
13762            // care of removing obsolete permissions and grant install permissions.
13763            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13764            updatePermissionsLPw(newPkg.packageName, newPkg,
13765                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13766
13767            if (applyUserRestrictions) {
13768                if (DEBUG_REMOVE) {
13769                    Slog.d(TAG, "Propagating install state across reinstall");
13770                }
13771                for (int i = 0; i < allUserHandles.length; i++) {
13772                    if (DEBUG_REMOVE) {
13773                        Slog.d(TAG, "    user " + allUserHandles[i]
13774                                + " => " + perUserInstalled[i]);
13775                    }
13776                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13777
13778                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13779                }
13780                // Regardless of writeSettings we need to ensure that this restriction
13781                // state propagation is persisted
13782                mSettings.writeAllUsersPackageRestrictionsLPr();
13783            }
13784            // can downgrade to reader here
13785            if (writeSettings) {
13786                mSettings.writeLPr();
13787            }
13788        }
13789        return true;
13790    }
13791
13792    private boolean deleteInstalledPackageLI(PackageSetting ps,
13793            boolean deleteCodeAndResources, int flags,
13794            int[] allUserHandles, boolean[] perUserInstalled,
13795            PackageRemovedInfo outInfo, boolean writeSettings) {
13796        if (outInfo != null) {
13797            outInfo.uid = ps.appId;
13798        }
13799
13800        // Delete package data from internal structures and also remove data if flag is set
13801        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13802
13803        // Delete application code and resources
13804        if (deleteCodeAndResources && (outInfo != null)) {
13805            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13806                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13807            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13808        }
13809        return true;
13810    }
13811
13812    @Override
13813    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13814            int userId) {
13815        mContext.enforceCallingOrSelfPermission(
13816                android.Manifest.permission.DELETE_PACKAGES, null);
13817        synchronized (mPackages) {
13818            PackageSetting ps = mSettings.mPackages.get(packageName);
13819            if (ps == null) {
13820                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13821                return false;
13822            }
13823            if (!ps.getInstalled(userId)) {
13824                // Can't block uninstall for an app that is not installed or enabled.
13825                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13826                return false;
13827            }
13828            ps.setBlockUninstall(blockUninstall, userId);
13829            mSettings.writePackageRestrictionsLPr(userId);
13830        }
13831        return true;
13832    }
13833
13834    @Override
13835    public boolean getBlockUninstallForUser(String packageName, int userId) {
13836        synchronized (mPackages) {
13837            PackageSetting ps = mSettings.mPackages.get(packageName);
13838            if (ps == null) {
13839                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13840                return false;
13841            }
13842            return ps.getBlockUninstall(userId);
13843        }
13844    }
13845
13846    @Override
13847    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13848        int callingUid = Binder.getCallingUid();
13849        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13850            throw new SecurityException(
13851                    "setRequiredForSystemUser can only be run by the system or root");
13852        }
13853        synchronized (mPackages) {
13854            PackageSetting ps = mSettings.mPackages.get(packageName);
13855            if (ps == null) {
13856                Log.w(TAG, "Package doesn't exist: " + packageName);
13857                return false;
13858            }
13859            if (systemUserApp) {
13860                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13861            } else {
13862                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13863            }
13864            mSettings.writeLPr();
13865        }
13866        return true;
13867    }
13868
13869    /*
13870     * This method handles package deletion in general
13871     */
13872    private boolean deletePackageLI(String packageName, UserHandle user,
13873            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13874            int flags, PackageRemovedInfo outInfo,
13875            boolean writeSettings) {
13876        if (packageName == null) {
13877            Slog.w(TAG, "Attempt to delete null packageName.");
13878            return false;
13879        }
13880        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13881        PackageSetting ps;
13882        boolean dataOnly = false;
13883        int removeUser = -1;
13884        int appId = -1;
13885        synchronized (mPackages) {
13886            ps = mSettings.mPackages.get(packageName);
13887            if (ps == null) {
13888                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13889                return false;
13890            }
13891            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13892                    && user.getIdentifier() != UserHandle.USER_ALL) {
13893                // The caller is asking that the package only be deleted for a single
13894                // user.  To do this, we just mark its uninstalled state and delete
13895                // its data.  If this is a system app, we only allow this to happen if
13896                // they have set the special DELETE_SYSTEM_APP which requests different
13897                // semantics than normal for uninstalling system apps.
13898                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13899                final int userId = user.getIdentifier();
13900                ps.setUserState(userId,
13901                        COMPONENT_ENABLED_STATE_DEFAULT,
13902                        false, //installed
13903                        true,  //stopped
13904                        true,  //notLaunched
13905                        false, //hidden
13906                        false, //suspended
13907                        null, null, null,
13908                        false, // blockUninstall
13909                        ps.readUserState(userId).domainVerificationStatus, 0);
13910                if (!isSystemApp(ps)) {
13911                    // Do not uninstall the APK if an app should be cached
13912                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13913                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13914                        // Other user still have this package installed, so all
13915                        // we need to do is clear this user's data and save that
13916                        // it is uninstalled.
13917                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13918                        removeUser = user.getIdentifier();
13919                        appId = ps.appId;
13920                        scheduleWritePackageRestrictionsLocked(removeUser);
13921                    } else {
13922                        // We need to set it back to 'installed' so the uninstall
13923                        // broadcasts will be sent correctly.
13924                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13925                        ps.setInstalled(true, user.getIdentifier());
13926                    }
13927                } else {
13928                    // This is a system app, so we assume that the
13929                    // other users still have this package installed, so all
13930                    // we need to do is clear this user's data and save that
13931                    // it is uninstalled.
13932                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13933                    removeUser = user.getIdentifier();
13934                    appId = ps.appId;
13935                    scheduleWritePackageRestrictionsLocked(removeUser);
13936                }
13937            }
13938        }
13939
13940        if (removeUser >= 0) {
13941            // From above, we determined that we are deleting this only
13942            // for a single user.  Continue the work here.
13943            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13944            if (outInfo != null) {
13945                outInfo.removedPackage = packageName;
13946                outInfo.removedAppId = appId;
13947                outInfo.removedUsers = new int[] {removeUser};
13948            }
13949            // TODO: triage flags as part of 26466827
13950            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
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 = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
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 = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
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 = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
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 UserManager um = mContext.getSystemService(UserManager.class);
16791        for (UserInfo user : um.getUsers()) {
16792            if (um.isUserUnlocked(user.id)) {
16793                reconcileAppsData(volumeUuid, user.id,
16794                        Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE);
16795            } else if (um.isUserRunning(user.id)) {
16796                reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE);
16797            } else {
16798                continue;
16799            }
16800        }
16801
16802        synchronized (mPackages) {
16803            int updateFlags = UPDATE_PERMISSIONS_ALL;
16804            if (ver.sdkVersion != mSdkVersion) {
16805                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16806                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16807                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16808            }
16809            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16810
16811            // Yay, everything is now upgraded
16812            ver.forceCurrent();
16813
16814            mSettings.writeLPr();
16815        }
16816
16817        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16818        sendResourcesChangedBroadcast(true, false, loaded, null);
16819    }
16820
16821    private void unloadPrivatePackages(final VolumeInfo vol) {
16822        mHandler.post(new Runnable() {
16823            @Override
16824            public void run() {
16825                unloadPrivatePackagesInner(vol);
16826            }
16827        });
16828    }
16829
16830    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16831        final String volumeUuid = vol.fsUuid;
16832        if (TextUtils.isEmpty(volumeUuid)) {
16833            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16834            return;
16835        }
16836
16837        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16838        synchronized (mInstallLock) {
16839        synchronized (mPackages) {
16840            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16841            for (PackageSetting ps : packages) {
16842                if (ps.pkg == null) continue;
16843
16844                final ApplicationInfo info = ps.pkg.applicationInfo;
16845                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16846                if (deletePackageLI(ps.name, null, false, null, null,
16847                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16848                    unloaded.add(info);
16849                } else {
16850                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16851                }
16852            }
16853
16854            mSettings.writeLPr();
16855        }
16856        }
16857
16858        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16859        sendResourcesChangedBroadcast(false, false, unloaded, null);
16860    }
16861
16862    /**
16863     * Examine all users present on given mounted volume, and destroy data
16864     * belonging to users that are no longer valid, or whose user ID has been
16865     * recycled.
16866     */
16867    private void reconcileUsers(String volumeUuid) {
16868        final File[] files = FileUtils
16869                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16870        for (File file : files) {
16871            if (!file.isDirectory()) continue;
16872
16873            final int userId;
16874            final UserInfo info;
16875            try {
16876                userId = Integer.parseInt(file.getName());
16877                info = sUserManager.getUserInfo(userId);
16878            } catch (NumberFormatException e) {
16879                Slog.w(TAG, "Invalid user directory " + file);
16880                continue;
16881            }
16882
16883            boolean destroyUser = false;
16884            if (info == null) {
16885                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16886                        + " because no matching user was found");
16887                destroyUser = true;
16888            } else {
16889                try {
16890                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16891                } catch (IOException e) {
16892                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16893                            + " because we failed to enforce serial number: " + e);
16894                    destroyUser = true;
16895                }
16896            }
16897
16898            if (destroyUser) {
16899                synchronized (mInstallLock) {
16900                    try {
16901                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16902                    } catch (InstallerException e) {
16903                        Slog.w(TAG, "Failed to clean up user dirs", e);
16904                    }
16905                }
16906            }
16907        }
16908
16909        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16910        final UserManager um = mContext.getSystemService(UserManager.class);
16911        for (UserInfo user : um.getUsers()) {
16912            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16913            if (userDir.exists()) continue;
16914
16915            try {
16916                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16917                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16918            } catch (IOException e) {
16919                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16920            }
16921        }
16922    }
16923
16924    private void assertPackageKnown(String volumeUuid, String packageName)
16925            throws PackageManagerException {
16926        synchronized (mPackages) {
16927            final PackageSetting ps = mSettings.mPackages.get(packageName);
16928            if (ps == null) {
16929                throw new PackageManagerException("Package " + packageName + " is unknown");
16930            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16931                throw new PackageManagerException(
16932                        "Package " + packageName + " found on unknown volume " + volumeUuid
16933                                + "; expected volume " + ps.volumeUuid);
16934            }
16935        }
16936    }
16937
16938    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16939            throws PackageManagerException {
16940        synchronized (mPackages) {
16941            final PackageSetting ps = mSettings.mPackages.get(packageName);
16942            if (ps == null) {
16943                throw new PackageManagerException("Package " + packageName + " is unknown");
16944            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16945                throw new PackageManagerException(
16946                        "Package " + packageName + " found on unknown volume " + volumeUuid
16947                                + "; expected volume " + ps.volumeUuid);
16948            } else if (!ps.getInstalled(userId)) {
16949                throw new PackageManagerException(
16950                        "Package " + packageName + " not installed for user " + userId);
16951            }
16952        }
16953    }
16954
16955    /**
16956     * Examine all apps present on given mounted volume, and destroy apps that
16957     * aren't expected, either due to uninstallation or reinstallation on
16958     * another volume.
16959     */
16960    private void reconcileApps(String volumeUuid) {
16961        final File[] files = FileUtils
16962                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16963        for (File file : files) {
16964            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16965                    && !PackageInstallerService.isStageName(file.getName());
16966            if (!isPackage) {
16967                // Ignore entries which are not packages
16968                continue;
16969            }
16970
16971            try {
16972                final PackageLite pkg = PackageParser.parsePackageLite(file,
16973                        PackageParser.PARSE_MUST_BE_APK);
16974                assertPackageKnown(volumeUuid, pkg.packageName);
16975
16976            } catch (PackageParserException | PackageManagerException e) {
16977                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16978                synchronized (mInstallLock) {
16979                    removeCodePathLI(file);
16980                }
16981            }
16982        }
16983    }
16984
16985    /**
16986     * Reconcile all app data for the given user.
16987     * <p>
16988     * Verifies that directories exist and that ownership and labeling is
16989     * correct for all installed apps on all mounted volumes.
16990     */
16991    void reconcileAppsData(int userId, @StorageFlags int flags) {
16992        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16993        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16994            final String volumeUuid = vol.getFsUuid();
16995            reconcileAppsData(volumeUuid, userId, flags);
16996        }
16997    }
16998
16999    /**
17000     * Reconcile all app data on given mounted volume.
17001     * <p>
17002     * Destroys app data that isn't expected, either due to uninstallation or
17003     * reinstallation on another volume.
17004     * <p>
17005     * Verifies that directories exist and that ownership and labeling is
17006     * correct for all installed apps.
17007     */
17008    private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) {
17009        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
17010                + Integer.toHexString(flags));
17011
17012        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
17013        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
17014
17015        boolean restoreconNeeded = false;
17016
17017        // First look for stale data that doesn't belong, and check if things
17018        // have changed since we did our last restorecon
17019        if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17020            if (!isUserKeyUnlocked(userId)) {
17021                throw new RuntimeException(
17022                        "Yikes, someone asked us to reconcile CE storage while " + userId
17023                                + " was still locked; this would have caused massive data loss!");
17024            }
17025
17026            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
17027
17028            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
17029            for (File file : files) {
17030                final String packageName = file.getName();
17031                try {
17032                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17033                } catch (PackageManagerException e) {
17034                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17035                    synchronized (mInstallLock) {
17036                        destroyAppDataLI(volumeUuid, packageName, userId,
17037                                Installer.FLAG_CE_STORAGE);
17038                    }
17039                }
17040            }
17041        }
17042        if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
17043            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
17044
17045            final File[] files = FileUtils.listFilesOrEmpty(deDir);
17046            for (File file : files) {
17047                final String packageName = file.getName();
17048                try {
17049                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
17050                } catch (PackageManagerException e) {
17051                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
17052                    synchronized (mInstallLock) {
17053                        destroyAppDataLI(volumeUuid, packageName, userId,
17054                                Installer.FLAG_DE_STORAGE);
17055                    }
17056                }
17057            }
17058        }
17059
17060        // Ensure that data directories are ready to roll for all packages
17061        // installed for this volume and user
17062        final List<PackageSetting> packages;
17063        synchronized (mPackages) {
17064            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17065        }
17066        int preparedCount = 0;
17067        for (PackageSetting ps : packages) {
17068            final String packageName = ps.name;
17069            if (ps.pkg == null) {
17070                Slog.w(TAG, "Odd, missing scanned package " + packageName);
17071                // TODO: might be due to legacy ASEC apps; we should circle back
17072                // and reconcile again once they're scanned
17073                continue;
17074            }
17075
17076            if (ps.getInstalled(userId)) {
17077                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
17078                preparedCount++;
17079            }
17080        }
17081
17082        if (restoreconNeeded) {
17083            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17084                SELinuxMMAC.setRestoreconDone(ceDir);
17085            }
17086            if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
17087                SELinuxMMAC.setRestoreconDone(deDir);
17088            }
17089        }
17090
17091        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
17092                + " packages; restoreconNeeded was " + restoreconNeeded);
17093    }
17094
17095    /**
17096     * Prepare app data for the given app just after it was installed or
17097     * upgraded. This method carefully only touches users that it's installed
17098     * for, and it forces a restorecon to handle any seinfo changes.
17099     * <p>
17100     * Verifies that directories exist and that ownership and labeling is
17101     * correct for all installed apps. If there is an ownership mismatch, it
17102     * will try recovering system apps by wiping data; third-party app data is
17103     * left intact.
17104     */
17105    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
17106        final PackageSetting ps;
17107        synchronized (mPackages) {
17108            ps = mSettings.mPackages.get(pkg.packageName);
17109        }
17110
17111        final UserManager um = mContext.getSystemService(UserManager.class);
17112        for (UserInfo user : um.getUsers()) {
17113            final int flags;
17114            if (um.isUserUnlocked(user.id)) {
17115                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
17116            } else if (um.isUserRunning(user.id)) {
17117                flags = Installer.FLAG_DE_STORAGE;
17118            } else {
17119                continue;
17120            }
17121
17122            if (ps.getInstalled(user.id)) {
17123                // Whenever an app changes, force a restorecon of its data
17124                // TODO: when user data is locked, mark that we're still dirty
17125                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
17126            }
17127        }
17128    }
17129
17130    /**
17131     * Prepare app data for the given app.
17132     * <p>
17133     * Verifies that directories exist and that ownership and labeling is
17134     * correct for all installed apps. If there is an ownership mismatch, this
17135     * will try recovering system apps by wiping data; third-party app data is
17136     * left intact.
17137     */
17138    private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags,
17139            PackageParser.Package pkg, boolean restoreconNeeded) {
17140        if (DEBUG_APP_DATA) {
17141            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
17142                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
17143        }
17144
17145        final String packageName = pkg.packageName;
17146        final ApplicationInfo app = pkg.applicationInfo;
17147        final int appId = UserHandle.getAppId(app.uid);
17148
17149        Preconditions.checkNotNull(app.seinfo);
17150
17151        synchronized (mInstallLock) {
17152            try {
17153                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17154                        appId, app.seinfo, app.targetSdkVersion);
17155            } catch (InstallerException e) {
17156                if (app.isSystemApp()) {
17157                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
17158                            + ", but trying to recover: " + e);
17159                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
17160                    try {
17161                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
17162                                appId, app.seinfo, app.targetSdkVersion);
17163                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
17164                    } catch (InstallerException e2) {
17165                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
17166                    }
17167                } else {
17168                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
17169                }
17170            }
17171
17172            if (restoreconNeeded) {
17173                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
17174            }
17175
17176            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
17177                // Create a native library symlink only if we have native libraries
17178                // and if the native libraries are 32 bit libraries. We do not provide
17179                // this symlink for 64 bit libraries.
17180                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
17181                    final String nativeLibPath = app.nativeLibraryDir;
17182                    try {
17183                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
17184                                nativeLibPath, userId);
17185                    } catch (InstallerException e) {
17186                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
17187                    }
17188                }
17189            }
17190        }
17191    }
17192
17193    private void unfreezePackage(String packageName) {
17194        synchronized (mPackages) {
17195            final PackageSetting ps = mSettings.mPackages.get(packageName);
17196            if (ps != null) {
17197                ps.frozen = false;
17198            }
17199        }
17200    }
17201
17202    @Override
17203    public int movePackage(final String packageName, final String volumeUuid) {
17204        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17205
17206        final int moveId = mNextMoveId.getAndIncrement();
17207        mHandler.post(new Runnable() {
17208            @Override
17209            public void run() {
17210                try {
17211                    movePackageInternal(packageName, volumeUuid, moveId);
17212                } catch (PackageManagerException e) {
17213                    Slog.w(TAG, "Failed to move " + packageName, e);
17214                    mMoveCallbacks.notifyStatusChanged(moveId,
17215                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17216                }
17217            }
17218        });
17219        return moveId;
17220    }
17221
17222    private void movePackageInternal(final String packageName, final String volumeUuid,
17223            final int moveId) throws PackageManagerException {
17224        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
17225        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17226        final PackageManager pm = mContext.getPackageManager();
17227
17228        final boolean currentAsec;
17229        final String currentVolumeUuid;
17230        final File codeFile;
17231        final String installerPackageName;
17232        final String packageAbiOverride;
17233        final int appId;
17234        final String seinfo;
17235        final String label;
17236        final int targetSdkVersion;
17237
17238        // reader
17239        synchronized (mPackages) {
17240            final PackageParser.Package pkg = mPackages.get(packageName);
17241            final PackageSetting ps = mSettings.mPackages.get(packageName);
17242            if (pkg == null || ps == null) {
17243                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
17244            }
17245
17246            if (pkg.applicationInfo.isSystemApp()) {
17247                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
17248                        "Cannot move system application");
17249            }
17250
17251            if (pkg.applicationInfo.isExternalAsec()) {
17252                currentAsec = true;
17253                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
17254            } else if (pkg.applicationInfo.isForwardLocked()) {
17255                currentAsec = true;
17256                currentVolumeUuid = "forward_locked";
17257            } else {
17258                currentAsec = false;
17259                currentVolumeUuid = ps.volumeUuid;
17260
17261                final File probe = new File(pkg.codePath);
17262                final File probeOat = new File(probe, "oat");
17263                if (!probe.isDirectory() || !probeOat.isDirectory()) {
17264                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17265                            "Move only supported for modern cluster style installs");
17266                }
17267            }
17268
17269            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
17270                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17271                        "Package already moved to " + volumeUuid);
17272            }
17273
17274            if (ps.frozen) {
17275                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
17276                        "Failed to move already frozen package");
17277            }
17278            ps.frozen = true;
17279
17280            codeFile = new File(pkg.codePath);
17281            installerPackageName = ps.installerPackageName;
17282            packageAbiOverride = ps.cpuAbiOverrideString;
17283            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
17284            seinfo = pkg.applicationInfo.seinfo;
17285            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
17286            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
17287        }
17288
17289        // Now that we're guarded by frozen state, kill app during move
17290        final long token = Binder.clearCallingIdentity();
17291        try {
17292            killApplication(packageName, appId, "move pkg");
17293        } finally {
17294            Binder.restoreCallingIdentity(token);
17295        }
17296
17297        final Bundle extras = new Bundle();
17298        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
17299        extras.putString(Intent.EXTRA_TITLE, label);
17300        mMoveCallbacks.notifyCreated(moveId, extras);
17301
17302        int installFlags;
17303        final boolean moveCompleteApp;
17304        final File measurePath;
17305
17306        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
17307            installFlags = INSTALL_INTERNAL;
17308            moveCompleteApp = !currentAsec;
17309            measurePath = Environment.getDataAppDirectory(volumeUuid);
17310        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
17311            installFlags = INSTALL_EXTERNAL;
17312            moveCompleteApp = false;
17313            measurePath = storage.getPrimaryPhysicalVolume().getPath();
17314        } else {
17315            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
17316            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
17317                    || !volume.isMountedWritable()) {
17318                unfreezePackage(packageName);
17319                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17320                        "Move location not mounted private volume");
17321            }
17322
17323            Preconditions.checkState(!currentAsec);
17324
17325            installFlags = INSTALL_INTERNAL;
17326            moveCompleteApp = true;
17327            measurePath = Environment.getDataAppDirectory(volumeUuid);
17328        }
17329
17330        final PackageStats stats = new PackageStats(null, -1);
17331        synchronized (mInstaller) {
17332            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
17333                unfreezePackage(packageName);
17334                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17335                        "Failed to measure package size");
17336            }
17337        }
17338
17339        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
17340                + stats.dataSize);
17341
17342        final long startFreeBytes = measurePath.getFreeSpace();
17343        final long sizeBytes;
17344        if (moveCompleteApp) {
17345            sizeBytes = stats.codeSize + stats.dataSize;
17346        } else {
17347            sizeBytes = stats.codeSize;
17348        }
17349
17350        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
17351            unfreezePackage(packageName);
17352            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
17353                    "Not enough free space to move");
17354        }
17355
17356        mMoveCallbacks.notifyStatusChanged(moveId, 10);
17357
17358        final CountDownLatch installedLatch = new CountDownLatch(1);
17359        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
17360            @Override
17361            public void onUserActionRequired(Intent intent) throws RemoteException {
17362                throw new IllegalStateException();
17363            }
17364
17365            @Override
17366            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
17367                    Bundle extras) throws RemoteException {
17368                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
17369                        + PackageManager.installStatusToString(returnCode, msg));
17370
17371                installedLatch.countDown();
17372
17373                // Regardless of success or failure of the move operation,
17374                // always unfreeze the package
17375                unfreezePackage(packageName);
17376
17377                final int status = PackageManager.installStatusToPublicStatus(returnCode);
17378                switch (status) {
17379                    case PackageInstaller.STATUS_SUCCESS:
17380                        mMoveCallbacks.notifyStatusChanged(moveId,
17381                                PackageManager.MOVE_SUCCEEDED);
17382                        break;
17383                    case PackageInstaller.STATUS_FAILURE_STORAGE:
17384                        mMoveCallbacks.notifyStatusChanged(moveId,
17385                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17386                        break;
17387                    default:
17388                        mMoveCallbacks.notifyStatusChanged(moveId,
17389                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17390                        break;
17391                }
17392            }
17393        };
17394
17395        final MoveInfo move;
17396        if (moveCompleteApp) {
17397            // Kick off a thread to report progress estimates
17398            new Thread() {
17399                @Override
17400                public void run() {
17401                    while (true) {
17402                        try {
17403                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17404                                break;
17405                            }
17406                        } catch (InterruptedException ignored) {
17407                        }
17408
17409                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17410                        final int progress = 10 + (int) MathUtils.constrain(
17411                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17412                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17413                    }
17414                }
17415            }.start();
17416
17417            final String dataAppName = codeFile.getName();
17418            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17419                    dataAppName, appId, seinfo, targetSdkVersion);
17420        } else {
17421            move = null;
17422        }
17423
17424        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17425
17426        final Message msg = mHandler.obtainMessage(INIT_COPY);
17427        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17428        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17429                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17430        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17431        msg.obj = params;
17432
17433        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17434                System.identityHashCode(msg.obj));
17435        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17436                System.identityHashCode(msg.obj));
17437
17438        mHandler.sendMessage(msg);
17439    }
17440
17441    @Override
17442    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17443        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17444
17445        final int realMoveId = mNextMoveId.getAndIncrement();
17446        final Bundle extras = new Bundle();
17447        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17448        mMoveCallbacks.notifyCreated(realMoveId, extras);
17449
17450        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17451            @Override
17452            public void onCreated(int moveId, Bundle extras) {
17453                // Ignored
17454            }
17455
17456            @Override
17457            public void onStatusChanged(int moveId, int status, long estMillis) {
17458                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17459            }
17460        };
17461
17462        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17463        storage.setPrimaryStorageUuid(volumeUuid, callback);
17464        return realMoveId;
17465    }
17466
17467    @Override
17468    public int getMoveStatus(int moveId) {
17469        mContext.enforceCallingOrSelfPermission(
17470                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17471        return mMoveCallbacks.mLastStatus.get(moveId);
17472    }
17473
17474    @Override
17475    public void registerMoveCallback(IPackageMoveObserver callback) {
17476        mContext.enforceCallingOrSelfPermission(
17477                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17478        mMoveCallbacks.register(callback);
17479    }
17480
17481    @Override
17482    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17483        mContext.enforceCallingOrSelfPermission(
17484                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17485        mMoveCallbacks.unregister(callback);
17486    }
17487
17488    @Override
17489    public boolean setInstallLocation(int loc) {
17490        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17491                null);
17492        if (getInstallLocation() == loc) {
17493            return true;
17494        }
17495        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17496                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17497            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17498                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17499            return true;
17500        }
17501        return false;
17502   }
17503
17504    @Override
17505    public int getInstallLocation() {
17506        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17507                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17508                PackageHelper.APP_INSTALL_AUTO);
17509    }
17510
17511    /** Called by UserManagerService */
17512    void cleanUpUser(UserManagerService userManager, int userHandle) {
17513        synchronized (mPackages) {
17514            mDirtyUsers.remove(userHandle);
17515            mUserNeedsBadging.delete(userHandle);
17516            mSettings.removeUserLPw(userHandle);
17517            mPendingBroadcasts.remove(userHandle);
17518            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17519        }
17520        synchronized (mInstallLock) {
17521            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17522            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17523                final String volumeUuid = vol.getFsUuid();
17524                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17525                try {
17526                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17527                } catch (InstallerException e) {
17528                    Slog.w(TAG, "Failed to remove user data", e);
17529                }
17530            }
17531            synchronized (mPackages) {
17532                removeUnusedPackagesLILPw(userManager, userHandle);
17533            }
17534        }
17535    }
17536
17537    /**
17538     * We're removing userHandle and would like to remove any downloaded packages
17539     * that are no longer in use by any other user.
17540     * @param userHandle the user being removed
17541     */
17542    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17543        final boolean DEBUG_CLEAN_APKS = false;
17544        int [] users = userManager.getUserIds();
17545        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17546        while (psit.hasNext()) {
17547            PackageSetting ps = psit.next();
17548            if (ps.pkg == null) {
17549                continue;
17550            }
17551            final String packageName = ps.pkg.packageName;
17552            // Skip over if system app
17553            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17554                continue;
17555            }
17556            if (DEBUG_CLEAN_APKS) {
17557                Slog.i(TAG, "Checking package " + packageName);
17558            }
17559            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17560            if (keep) {
17561                if (DEBUG_CLEAN_APKS) {
17562                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17563                }
17564            } else {
17565                for (int i = 0; i < users.length; i++) {
17566                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17567                        keep = true;
17568                        if (DEBUG_CLEAN_APKS) {
17569                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17570                                    + users[i]);
17571                        }
17572                        break;
17573                    }
17574                }
17575            }
17576            if (!keep) {
17577                if (DEBUG_CLEAN_APKS) {
17578                    Slog.i(TAG, "  Removing package " + packageName);
17579                }
17580                mHandler.post(new Runnable() {
17581                    public void run() {
17582                        deletePackageX(packageName, userHandle, 0);
17583                    } //end run
17584                });
17585            }
17586        }
17587    }
17588
17589    /** Called by UserManagerService */
17590    void createNewUser(int userHandle) {
17591        synchronized (mInstallLock) {
17592            try {
17593                mInstaller.createUserConfig(userHandle);
17594            } catch (InstallerException e) {
17595                Slog.w(TAG, "Failed to create user config", e);
17596            }
17597            mSettings.createNewUserLI(this, mInstaller, userHandle);
17598        }
17599        synchronized (mPackages) {
17600            applyFactoryDefaultBrowserLPw(userHandle);
17601            primeDomainVerificationsLPw(userHandle);
17602        }
17603    }
17604
17605    void newUserCreated(final int userHandle) {
17606        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17607        // If permission review for legacy apps is required, we represent
17608        // dagerous permissions for such apps as always granted runtime
17609        // permissions to keep per user flag state whether review is needed.
17610        // Hence, if a new user is added we have to propagate dangerous
17611        // permission grants for these legacy apps.
17612        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17613            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17614                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17615        }
17616    }
17617
17618    @Override
17619    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17620        mContext.enforceCallingOrSelfPermission(
17621                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17622                "Only package verification agents can read the verifier device identity");
17623
17624        synchronized (mPackages) {
17625            return mSettings.getVerifierDeviceIdentityLPw();
17626        }
17627    }
17628
17629    @Override
17630    public void setPermissionEnforced(String permission, boolean enforced) {
17631        // TODO: Now that we no longer change GID for storage, this should to away.
17632        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17633                "setPermissionEnforced");
17634        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17635            synchronized (mPackages) {
17636                if (mSettings.mReadExternalStorageEnforced == null
17637                        || mSettings.mReadExternalStorageEnforced != enforced) {
17638                    mSettings.mReadExternalStorageEnforced = enforced;
17639                    mSettings.writeLPr();
17640                }
17641            }
17642            // kill any non-foreground processes so we restart them and
17643            // grant/revoke the GID.
17644            final IActivityManager am = ActivityManagerNative.getDefault();
17645            if (am != null) {
17646                final long token = Binder.clearCallingIdentity();
17647                try {
17648                    am.killProcessesBelowForeground("setPermissionEnforcement");
17649                } catch (RemoteException e) {
17650                } finally {
17651                    Binder.restoreCallingIdentity(token);
17652                }
17653            }
17654        } else {
17655            throw new IllegalArgumentException("No selective enforcement for " + permission);
17656        }
17657    }
17658
17659    @Override
17660    @Deprecated
17661    public boolean isPermissionEnforced(String permission) {
17662        return true;
17663    }
17664
17665    @Override
17666    public boolean isStorageLow() {
17667        final long token = Binder.clearCallingIdentity();
17668        try {
17669            final DeviceStorageMonitorInternal
17670                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17671            if (dsm != null) {
17672                return dsm.isMemoryLow();
17673            } else {
17674                return false;
17675            }
17676        } finally {
17677            Binder.restoreCallingIdentity(token);
17678        }
17679    }
17680
17681    @Override
17682    public IPackageInstaller getPackageInstaller() {
17683        return mInstallerService;
17684    }
17685
17686    private boolean userNeedsBadging(int userId) {
17687        int index = mUserNeedsBadging.indexOfKey(userId);
17688        if (index < 0) {
17689            final UserInfo userInfo;
17690            final long token = Binder.clearCallingIdentity();
17691            try {
17692                userInfo = sUserManager.getUserInfo(userId);
17693            } finally {
17694                Binder.restoreCallingIdentity(token);
17695            }
17696            final boolean b;
17697            if (userInfo != null && userInfo.isManagedProfile()) {
17698                b = true;
17699            } else {
17700                b = false;
17701            }
17702            mUserNeedsBadging.put(userId, b);
17703            return b;
17704        }
17705        return mUserNeedsBadging.valueAt(index);
17706    }
17707
17708    @Override
17709    public KeySet getKeySetByAlias(String packageName, String alias) {
17710        if (packageName == null || alias == null) {
17711            return null;
17712        }
17713        synchronized(mPackages) {
17714            final PackageParser.Package pkg = mPackages.get(packageName);
17715            if (pkg == null) {
17716                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17717                throw new IllegalArgumentException("Unknown package: " + packageName);
17718            }
17719            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17720            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17721        }
17722    }
17723
17724    @Override
17725    public KeySet getSigningKeySet(String packageName) {
17726        if (packageName == null) {
17727            return null;
17728        }
17729        synchronized(mPackages) {
17730            final PackageParser.Package pkg = mPackages.get(packageName);
17731            if (pkg == null) {
17732                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17733                throw new IllegalArgumentException("Unknown package: " + packageName);
17734            }
17735            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17736                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17737                throw new SecurityException("May not access signing KeySet of other apps.");
17738            }
17739            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17740            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17741        }
17742    }
17743
17744    @Override
17745    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17746        if (packageName == null || ks == null) {
17747            return false;
17748        }
17749        synchronized(mPackages) {
17750            final PackageParser.Package pkg = mPackages.get(packageName);
17751            if (pkg == null) {
17752                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17753                throw new IllegalArgumentException("Unknown package: " + packageName);
17754            }
17755            IBinder ksh = ks.getToken();
17756            if (ksh instanceof KeySetHandle) {
17757                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17758                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17759            }
17760            return false;
17761        }
17762    }
17763
17764    @Override
17765    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17766        if (packageName == null || ks == null) {
17767            return false;
17768        }
17769        synchronized(mPackages) {
17770            final PackageParser.Package pkg = mPackages.get(packageName);
17771            if (pkg == null) {
17772                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17773                throw new IllegalArgumentException("Unknown package: " + packageName);
17774            }
17775            IBinder ksh = ks.getToken();
17776            if (ksh instanceof KeySetHandle) {
17777                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17778                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17779            }
17780            return false;
17781        }
17782    }
17783
17784    private void deletePackageIfUnusedLPr(final String packageName) {
17785        PackageSetting ps = mSettings.mPackages.get(packageName);
17786        if (ps == null) {
17787            return;
17788        }
17789        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17790            // TODO Implement atomic delete if package is unused
17791            // It is currently possible that the package will be deleted even if it is installed
17792            // after this method returns.
17793            mHandler.post(new Runnable() {
17794                public void run() {
17795                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17796                }
17797            });
17798        }
17799    }
17800
17801    /**
17802     * Check and throw if the given before/after packages would be considered a
17803     * downgrade.
17804     */
17805    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17806            throws PackageManagerException {
17807        if (after.versionCode < before.mVersionCode) {
17808            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17809                    "Update version code " + after.versionCode + " is older than current "
17810                    + before.mVersionCode);
17811        } else if (after.versionCode == before.mVersionCode) {
17812            if (after.baseRevisionCode < before.baseRevisionCode) {
17813                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17814                        "Update base revision code " + after.baseRevisionCode
17815                        + " is older than current " + before.baseRevisionCode);
17816            }
17817
17818            if (!ArrayUtils.isEmpty(after.splitNames)) {
17819                for (int i = 0; i < after.splitNames.length; i++) {
17820                    final String splitName = after.splitNames[i];
17821                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17822                    if (j != -1) {
17823                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17824                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17825                                    "Update split " + splitName + " revision code "
17826                                    + after.splitRevisionCodes[i] + " is older than current "
17827                                    + before.splitRevisionCodes[j]);
17828                        }
17829                    }
17830                }
17831            }
17832        }
17833    }
17834
17835    private static class MoveCallbacks extends Handler {
17836        private static final int MSG_CREATED = 1;
17837        private static final int MSG_STATUS_CHANGED = 2;
17838
17839        private final RemoteCallbackList<IPackageMoveObserver>
17840                mCallbacks = new RemoteCallbackList<>();
17841
17842        private final SparseIntArray mLastStatus = new SparseIntArray();
17843
17844        public MoveCallbacks(Looper looper) {
17845            super(looper);
17846        }
17847
17848        public void register(IPackageMoveObserver callback) {
17849            mCallbacks.register(callback);
17850        }
17851
17852        public void unregister(IPackageMoveObserver callback) {
17853            mCallbacks.unregister(callback);
17854        }
17855
17856        @Override
17857        public void handleMessage(Message msg) {
17858            final SomeArgs args = (SomeArgs) msg.obj;
17859            final int n = mCallbacks.beginBroadcast();
17860            for (int i = 0; i < n; i++) {
17861                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17862                try {
17863                    invokeCallback(callback, msg.what, args);
17864                } catch (RemoteException ignored) {
17865                }
17866            }
17867            mCallbacks.finishBroadcast();
17868            args.recycle();
17869        }
17870
17871        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17872                throws RemoteException {
17873            switch (what) {
17874                case MSG_CREATED: {
17875                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17876                    break;
17877                }
17878                case MSG_STATUS_CHANGED: {
17879                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17880                    break;
17881                }
17882            }
17883        }
17884
17885        private void notifyCreated(int moveId, Bundle extras) {
17886            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17887
17888            final SomeArgs args = SomeArgs.obtain();
17889            args.argi1 = moveId;
17890            args.arg2 = extras;
17891            obtainMessage(MSG_CREATED, args).sendToTarget();
17892        }
17893
17894        private void notifyStatusChanged(int moveId, int status) {
17895            notifyStatusChanged(moveId, status, -1);
17896        }
17897
17898        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17899            Slog.v(TAG, "Move " + moveId + " status " + status);
17900
17901            final SomeArgs args = SomeArgs.obtain();
17902            args.argi1 = moveId;
17903            args.argi2 = status;
17904            args.arg3 = estMillis;
17905            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17906
17907            synchronized (mLastStatus) {
17908                mLastStatus.put(moveId, status);
17909            }
17910        }
17911    }
17912
17913    private final static class OnPermissionChangeListeners extends Handler {
17914        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17915
17916        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17917                new RemoteCallbackList<>();
17918
17919        public OnPermissionChangeListeners(Looper looper) {
17920            super(looper);
17921        }
17922
17923        @Override
17924        public void handleMessage(Message msg) {
17925            switch (msg.what) {
17926                case MSG_ON_PERMISSIONS_CHANGED: {
17927                    final int uid = msg.arg1;
17928                    handleOnPermissionsChanged(uid);
17929                } break;
17930            }
17931        }
17932
17933        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17934            mPermissionListeners.register(listener);
17935
17936        }
17937
17938        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17939            mPermissionListeners.unregister(listener);
17940        }
17941
17942        public void onPermissionsChanged(int uid) {
17943            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17944                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17945            }
17946        }
17947
17948        private void handleOnPermissionsChanged(int uid) {
17949            final int count = mPermissionListeners.beginBroadcast();
17950            try {
17951                for (int i = 0; i < count; i++) {
17952                    IOnPermissionsChangeListener callback = mPermissionListeners
17953                            .getBroadcastItem(i);
17954                    try {
17955                        callback.onPermissionsChanged(uid);
17956                    } catch (RemoteException e) {
17957                        Log.e(TAG, "Permission listener is dead", e);
17958                    }
17959                }
17960            } finally {
17961                mPermissionListeners.finishBroadcast();
17962            }
17963        }
17964    }
17965
17966    private class PackageManagerInternalImpl extends PackageManagerInternal {
17967        @Override
17968        public void setLocationPackagesProvider(PackagesProvider provider) {
17969            synchronized (mPackages) {
17970                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17971            }
17972        }
17973
17974        @Override
17975        public void setImePackagesProvider(PackagesProvider provider) {
17976            synchronized (mPackages) {
17977                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17978            }
17979        }
17980
17981        @Override
17982        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17983            synchronized (mPackages) {
17984                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17985            }
17986        }
17987
17988        @Override
17989        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17990            synchronized (mPackages) {
17991                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17992            }
17993        }
17994
17995        @Override
17996        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17997            synchronized (mPackages) {
17998                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17999            }
18000        }
18001
18002        @Override
18003        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
18004            synchronized (mPackages) {
18005                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
18006            }
18007        }
18008
18009        @Override
18010        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
18011            synchronized (mPackages) {
18012                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
18013            }
18014        }
18015
18016        @Override
18017        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
18018            synchronized (mPackages) {
18019                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
18020                        packageName, userId);
18021            }
18022        }
18023
18024        @Override
18025        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
18026            synchronized (mPackages) {
18027                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
18028                        packageName, userId);
18029            }
18030        }
18031
18032        @Override
18033        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
18034            synchronized (mPackages) {
18035                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
18036                        packageName, userId);
18037            }
18038        }
18039
18040        @Override
18041        public void setKeepUninstalledPackages(final List<String> packageList) {
18042            Preconditions.checkNotNull(packageList);
18043            List<String> removedFromList = null;
18044            synchronized (mPackages) {
18045                if (mKeepUninstalledPackages != null) {
18046                    final int packagesCount = mKeepUninstalledPackages.size();
18047                    for (int i = 0; i < packagesCount; i++) {
18048                        String oldPackage = mKeepUninstalledPackages.get(i);
18049                        if (packageList != null && packageList.contains(oldPackage)) {
18050                            continue;
18051                        }
18052                        if (removedFromList == null) {
18053                            removedFromList = new ArrayList<>();
18054                        }
18055                        removedFromList.add(oldPackage);
18056                    }
18057                }
18058                mKeepUninstalledPackages = new ArrayList<>(packageList);
18059                if (removedFromList != null) {
18060                    final int removedCount = removedFromList.size();
18061                    for (int i = 0; i < removedCount; i++) {
18062                        deletePackageIfUnusedLPr(removedFromList.get(i));
18063                    }
18064                }
18065            }
18066        }
18067
18068        @Override
18069        public boolean isPermissionsReviewRequired(String packageName, int userId) {
18070            synchronized (mPackages) {
18071                // If we do not support permission review, done.
18072                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
18073                    return false;
18074                }
18075
18076                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
18077                if (packageSetting == null) {
18078                    return false;
18079                }
18080
18081                // Permission review applies only to apps not supporting the new permission model.
18082                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
18083                    return false;
18084                }
18085
18086                // Legacy apps have the permission and get user consent on launch.
18087                PermissionsState permissionsState = packageSetting.getPermissionsState();
18088                return permissionsState.isPermissionReviewRequired(userId);
18089            }
18090        }
18091    }
18092
18093    @Override
18094    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
18095        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
18096        synchronized (mPackages) {
18097            final long identity = Binder.clearCallingIdentity();
18098            try {
18099                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
18100                        packageNames, userId);
18101            } finally {
18102                Binder.restoreCallingIdentity(identity);
18103            }
18104        }
18105    }
18106
18107    private static void enforceSystemOrPhoneCaller(String tag) {
18108        int callingUid = Binder.getCallingUid();
18109        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
18110            throw new SecurityException(
18111                    "Cannot call " + tag + " from UID " + callingUid);
18112        }
18113    }
18114
18115    boolean isHistoricalPackageUsageAvailable() {
18116        return mPackageUsage.isHistoricalPackageUsageAvailable();
18117    }
18118}
18119